Skip to content

The agent that grows with you

54.1 KB
Raw Blame
import { describe, expect, it } from 'vitest'

import type { HermesGitWorktree } from '@/global'
import { makeCwdSession } from '@/test/session-info'
import type { ProjectInfo, SessionInfo } from '@/types/hermes'

import {
  baseName,
  excludeProjectSessions,
  kanbanWorktreeDir,
  laneSwitchTarget,
  liveSessionProjectId,
  mergeRepoWorktreeGroups,
  NO_PROJECT_ID,
  overlayLiveLanes,
  overlayLivePreviews,
  projectOwnerBySessionId,
  reconcileEnteredProjectSessions,
  sessionBucketId,
  sessionMatchesProjectFilter,
  sessionProjectColor,
  type SidebarProjectTree,
  type SidebarSessionGroup,
  sortWorktreeGroups
} from './workspace-groups'

// The grouping itself now lives on the backend (tui_gateway/project_tree.py,
// covered by tests/tui_gateway/test_project_tree.py). This file only covers the
// thin render helpers the desktop still owns + the VISUAL worktree enhancer.

const lane = (over: Partial<SidebarSessionGroup> & Pick<SidebarSessionGroup, 'id' | 'label'>): SidebarSessionGroup => ({
  path: null,
  sessions: [],
  ...over
})

describe('baseName', () => {
  it('returns the final path segment, ignoring trailing slashes and separators', () => {
    expect(baseName('/www/hermes-agent/')).toBe('hermes-agent')
    expect(baseName('C:\\repos\\app')).toBe('app')
    expect(baseName('')).toBeUndefined()
  })
})

describe('laneSwitchTarget (#108694)', () => {
  const main = { isMain: true, label: 'main', path: '/repo' }
  const local = (name: string) => ({ isRemote: false, name })

  it('skips the synthetic main fallback on a repo whose trunk is master', () => {
    expect(laneSwitchTarget(main, [local('master')])).toBeNull()
  })

  it('switches to a label git lists as a local branch', () => {
    expect(laneSwitchTarget(main, [local('master'), local('main')])).toBe('main')
  })

  it('switches to a remote-only branch git switch can DWIM', () => {
    expect(laneSwitchTarget(main, [local('dev'), { isRemote: true, name: 'origin/main' }])).toBe('main')
  })

  it('never switches non-git, linked, or unverifiable lanes', () => {
    expect(laneSwitchTarget({ ...main, isGit: false }, [local('main')])).toBeNull()
    expect(laneSwitchTarget({ ...main, isMain: false }, [local('main')])).toBeNull()
    expect(laneSwitchTarget({ ...main, path: null }, [local('main')])).toBeNull()
    expect(laneSwitchTarget(main, [])).toBeNull()
  })
})

describe('kanbanWorktreeDir', () => {
  it('matches a kanban task worktree (t_<hex>) and returns its .worktrees dir', () => {
    expect(kanbanWorktreeDir('/repo/.worktrees/t_aaaaaaaa')).toBe('/repo/.worktrees')
  })

  it('does NOT match a user-named "New worktree" under .worktrees/ (its own lane)', () => {
    expect(kanbanWorktreeDir('/repo/.worktrees/test-gui-stuff')).toBeNull()
  })

  it('returns null for non-kanban paths', () => {
    expect(kanbanWorktreeDir('/repo/src')).toBeNull()
    expect(kanbanWorktreeDir('/repo')).toBeNull()
  })
})

describe('sortWorktreeGroups', () => {
  it('pins trunk to the top, sinks kanban to the bottom, and orders the rest by recency', () => {
    const at = (t: number) => [makeCwdSession('/x', { last_active: t })]

    const groups = [
      lane({ id: 'k', label: 'kanban', isKanban: true, sessions: at(999) }),
      lane({ id: 'stale', label: 'stale-branch', isMain: true, sessions: at(10) }),
      lane({ id: 'wt', label: 'busy-worktree', isMain: false, sessions: at(500) }),
      lane({ id: 'main', label: 'main', isMain: true, sessions: at(1) })
    ]

    // main (trunk) first despite being least recent; kanban last despite being
    // most recent; busy-worktree ahead of stale-branch by activity.
    expect(sortWorktreeGroups(groups).map(g => g.label)).toEqual(['main', 'busy-worktree', 'stale-branch', 'kanban'])
  })

  it('pins the live home checkout above trunk, even when it has no sessions yet', () => {
    const groups = [
      lane({ id: 'main', label: 'main', isMain: true, sessions: [makeCwdSession('/x', { last_active: 999 })] }),
      lane({ id: 'home', label: 'bb/projects-paradigm', isMain: true, isHome: true })
    ]

    expect(sortWorktreeGroups(groups).map(g => g.label)).toEqual(['bb/projects-paradigm', 'main'])
  })

  it('falls back to label order for equally-idle lanes', () => {
    const groups = [lane({ id: 'b', label: 'beta', isMain: false }), lane({ id: 'a', label: 'alpha', isMain: false })]

    expect(sortWorktreeGroups(groups).map(g => g.label)).toEqual(['alpha', 'beta'])
  })
})

describe('mergeRepoWorktreeGroups (visual enhancer)', () => {
  it('injects a linked worktree lane discovered by git that has no sessions yet', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [lane({ id: '/repo::branch::main', label: 'main', isMain: true, path: '/repo' })]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'feature', detached: false, isMain: false, locked: false, path: '/repo-wt-feature' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)

    expect(merged.map(g => g.label)).toEqual(['main', 'feature'])
    // The injected lane is empty (visual only — never carries sessions).
    expect(merged.find(g => g.label === 'feature')?.sessions).toEqual([])
  })

  it('never spawns a lane per kanban task worktree', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [lane({ id: '/repo::branch::main', label: 'main', isMain: true, path: '/repo' })]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'wt/t_aaaaaaaa', detached: false, isMain: false, locked: false, path: '/repo/.worktrees/t_aaaaaaaa' },
      { branch: 'wt/t_bbbbbbbb', detached: false, isMain: false, locked: false, path: '/repo/.worktrees/t_bbbbbbbb' }
    ]

    expect(mergeRepoWorktreeGroups(repo, discovered).map(g => g.label)).toEqual(['main'])
  })

  it('does not duplicate a lane already present from the backend (by id/path)', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo::branch::main',
          label: 'main',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo')]
        })
      ]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'main', detached: false, isMain: true, locked: false, path: '/repo' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)

    expect(merged).toHaveLength(1)
    // The backend lane keeps its session rows; the enhancer left it untouched.
    expect(merged[0].sessions).toHaveLength(1)
  })

  it('is a no-op when git worktree list is unavailable (remote backend)', () => {
    const groups = [lane({ id: '/repo::branch::main', label: 'main', isMain: true, path: '/repo' })]

    expect(mergeRepoWorktreeGroups({ id: '/repo', path: '/repo', groups }, undefined).map(g => g.label)).toEqual([
      'main'
    ])
  })

  it('does not add a second "main" for a linked worktree checked out on main', () => {
    const groups = [
      lane({
        id: '/repo::branch::main',
        label: 'main',
        isMain: true,
        path: '/repo',
        sessions: [makeCwdSession('/repo')]
      })
    ]

    const discovered: HermesGitWorktree[] = [
      { branch: 'main', detached: false, isMain: false, locked: false, path: '/repo/.worktrees/main-mirror' }
    ]

    expect(
      mergeRepoWorktreeGroups({ id: '/repo', path: '/repo', groups }, discovered).filter(g => g.label === 'main')
    ).toHaveLength(1)
  })

  it('surfaces a user-named "New worktree" under .worktrees/ as its own lane', () => {
    const discovered: HermesGitWorktree[] = [
      {
        branch: 'hermes/test-gui-stuff',
        detached: false,
        isMain: false,
        locked: false,
        path: '/repo/.worktrees/test-gui-stuff'
      }
    ]

    const merged = mergeRepoWorktreeGroups({ id: '/repo', path: '/repo', groups: [] }, discovered)

    expect(merged.map(g => g.label)).toContain('hermes/test-gui-stuff')
  })

  it('relabels a dir-named linked worktree lane to its live checked-out branch', () => {
    // Backend labels the lane by the worktree dir (`hermes-agent-ci`); the live
    // `git worktree list` says HEAD there is `bb/ci-affected-only` → branch wins.
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo::branch::main',
          label: 'main',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo')]
        }),
        lane({
          id: '/repo-ci',
          label: 'hermes-agent-ci',
          isMain: false,
          path: '/repo-ci',
          sessions: [makeCwdSession('/repo-ci')]
        })
      ]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'main', detached: false, isMain: true, locked: false, path: '/repo' },
      { branch: 'bb/ci-affected-only', detached: false, isMain: false, locked: false, path: '/repo-ci' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)
    const ci = merged.find(g => g.id === '/repo-ci')

    expect(ci?.label).toBe('bb/ci-affected-only')
    // The relabel is label-only — the lane keeps its id, path, and sessions.
    expect(ci?.path).toBe('/repo-ci')
    expect(ci?.sessions).toHaveLength(1)
  })

  it('re-anchors a lane whose path drifted from git truth back to its branch path', () => {
    // The reported bug: a lane is correctly labeled by its branch (`bb/attempts`)
    // but its stored PATH points at a stale/old worktree dir. git pins a branch
    // to exactly one worktree, so the lane must follow the branch's real path —
    // otherwise "reveal in Finder" opens a completely different worktree.
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo/.worktrees/attempts',
          label: 'bb/attempts',
          isMain: false,
          path: '/repo/.worktrees/attempts',
          sessions: [makeCwdSession('/repo/.worktrees/attempts')]
        })
      ]
    }

    // git now has `bb/attempts` at a sibling dir, not the stale `.worktrees` one.
    const discovered: HermesGitWorktree[] = [
      { branch: 'bb/attempts', detached: false, isMain: false, locked: false, path: '/repo-pr-attempts' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)
    const attempts = merged.filter(g => g.label === 'bb/attempts')

    // Exactly one lane, re-pointed at git's real path (label preserved, sessions
    // preserved), and NO leftover lane on the stale path.
    expect(attempts).toHaveLength(1)
    expect(attempts[0].path).toBe('/repo-pr-attempts')
    expect(attempts[0].sessions).toHaveLength(1)
    expect(merged.some(g => g.path === '/repo/.worktrees/attempts')).toBe(false)
  })

  it('collapses a re-anchored lane onto the real lane that already holds that path', () => {
    // A stale lane (branch label, wrong path) AND the real worktree lane both
    // exist. Re-anchoring the stale one onto git's path must not leave a twin —
    // keep the richer (more sessions) lane.
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({ id: 'stale', label: 'bb/feature', isMain: false, path: '/repo/.worktrees/old', sessions: [] }),
        lane({
          id: '/repo-feature',
          label: 'bb/feature',
          isMain: false,
          path: '/repo-feature',
          sessions: [makeCwdSession('/repo-feature'), makeCwdSession('/repo-feature')]
        })
      ]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'bb/feature', detached: false, isMain: false, locked: false, path: '/repo-feature' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)
    const feature = merged.filter(g => g.path === '/repo-feature')

    expect(feature).toHaveLength(1)
    expect(feature[0].sessions).toHaveLength(2)
    expect(merged.some(g => g.path === '/repo/.worktrees/old')).toBe(false)
  })

  it('keeps the dir label for a detached-HEAD worktree (no branch to show)', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo-ci',
          label: 'repo-ci',
          isMain: false,
          path: '/repo-ci',
          sessions: [makeCwdSession('/repo-ci')]
        })
      ]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: null, detached: true, isMain: false, locked: false, path: '/repo-ci' }
    ]

    expect(mergeRepoWorktreeGroups(repo, discovered).find(g => g.id === '/repo-ci')?.label).toBe('repo-ci')
  })

  it('collapses the main checkout into one home lane labeled by the live branch (off-trunk)', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo::branch::main',
          label: 'main',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo')]
        })
      ]
    }

    // The repo root is switched to a feature branch. The historical "main"
    // sessions fold into ONE home lane labeled by the live branch — no stale
    // "main" lane lingering beside it.
    const discovered: HermesGitWorktree[] = [
      { branch: 'some-feature', detached: false, isMain: true, locked: false, path: '/repo' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)
    const home = merged.find(g => g.isHome)

    expect(merged.filter(g => g.isMain)).toHaveLength(1)
    expect(home?.label).toBe('some-feature')
    expect(home?.path).toBe('/repo')
    expect(home?.sessions).toHaveLength(1)
    expect(merged.some(g => g.label === 'main')).toBe(false)
  })

  it('labels the home lane "main" (still home-flagged) when the root is on trunk', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo::branch::main',
          label: 'main',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo')]
        })
      ]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'main', detached: false, isMain: true, locked: false, path: '/repo' }
    ]

    const home = mergeRepoWorktreeGroups(repo, discovered).find(g => g.isHome)

    expect(home?.label).toBe('main')
    expect(home?.isHome).toBe(true)
  })

  it('folds multiple historical main-checkout branch lanes into the single live home lane', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo::branch::main',
          label: 'main',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo', { id: 'a' })]
        }),
        lane({
          id: '/repo::branch::old',
          label: 'old-feature',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo', { id: 'b' })]
        })
      ]
    }

    const discovered: HermesGitWorktree[] = [
      { branch: 'bb/live', detached: false, isMain: true, locked: false, path: '/repo' }
    ]

    const merged = mergeRepoWorktreeGroups(repo, discovered)
    const home = merged.find(g => g.isHome)

    expect(merged.filter(g => g.isMain)).toHaveLength(1)
    expect(home?.label).toBe('bb/live')
    expect(home?.sessions.map(s => s.id).sort()).toEqual(['a', 'b'])
  })

  it('leaves main lanes untouched on a remote backend (no git probe)', () => {
    const repo = {
      id: '/repo',
      path: '/repo',
      groups: [
        lane({
          id: '/repo::branch::main',
          label: 'main',
          isMain: true,
          path: '/repo',
          sessions: [makeCwdSession('/repo')]
        })
      ]
    }

    // No discovered worktrees → no live branch truth → backend label stands.
    const merged = mergeRepoWorktreeGroups(repo, undefined)

    expect(merged.map(g => g.label)).toEqual(['main'])
    expect(merged[0].isHome).toBeFalsy()
  })
})

const makeProject = (id: string, folders: string[]): ProjectInfo => ({
  archived: false,
  board_slug: null,
  color: null,
  created_at: 0,
  description: null,
  folders: folders.map((path, i) => ({ added_at: 0, is_primary: i === 0, label: null, path })),
  icon: null,
  id,
  name: id,
  primary_path: folders[0] ?? null,
  slug: id
})

const projectNode = (over: Partial<SidebarProjectTree> & Pick<SidebarProjectTree, 'id'>): SidebarProjectTree => ({
  label: over.id,
  path: over.id,
  repos: [],
  sessionCount: 0,
  ...over
})

// Home as the backend emits it: no path, one synthetic lane carrying the rows.
const homeNode = (sessions: SessionInfo[]): SidebarProjectTree =>
  projectNode({
    id: NO_PROJECT_ID,
    isNoProject: true,
    label: 'Home',
    path: null,
    repos: [
      {
        id: NO_PROJECT_ID,
        label: 'Home',
        path: null,
        sessionCount: sessions.length,
        groups: [lane({ id: NO_PROJECT_ID, label: 'Home', sessions })]
      }
    ],
    sessionCount: sessions.length
  })

describe('liveSessionProjectId', () => {
  it('maps a brand-new (unpersisted) session to its auto project (the repo root)', () => {
    expect(liveSessionProjectId(makeCwdSession('/www/app'), [])).toBe('/www/app')
  })

  it('routes a session under an explicit project folder to that project', () => {
    const id = liveSessionProjectId(makeCwdSession('/www/app/src', { git_repo_root: '/www/app', git_branch: 'feat' }), [
      makeProject('p_app', ['/www/app'])
    ])

    expect(id).toBe('p_app')
  })

  it('anchors a cwd-less session on its git_repo_root (backend groups it there too)', () => {
    // Older/imported rows carry only a repo root; the sidebar files them under
    // the repo's project, so membership (and color) must resolve from the root.
    expect(liveSessionProjectId(makeCwdSession(null, { git_repo_root: '/www/app' }), [])).toBe('/www/app')
    expect(
      liveSessionProjectId(makeCwdSession(null, { git_repo_root: '/www/app' }), [makeProject('p_app', ['/www/app'])])
    ).toBe('p_app')
  })

  it('skips cwd-less, kanban-task, and out-of-tree (sibling) worktree sessions', () => {
    expect(liveSessionProjectId(makeCwdSession(null), [])).toBeNull()
    // Kanban task worktree → folds into the kanban bucket, not a project preview.
    expect(liveSessionProjectId(makeCwdSession('/repo/.worktrees/t_aaaaaaaa'), [])).toBeNull()
    // Sibling worktree OUTSIDE the repo root → project can't be derived from the row.
    expect(liveSessionProjectId(makeCwdSession('/elsewhere/wt', { git_repo_root: '/repo' }), [])).toBeNull()
  })

  it('places an in-tree worktree session under its repo project (the root is in the path)', () => {
    // "Convert a branch" / "new worktree" land at `<repoRoot>/.worktrees/<slug>`,
    // so they belong to the same auto project as the repo root and must show in
    // the overview at once, not wait for the next backend refresh.
    expect(liveSessionProjectId(makeCwdSession('/www/app/.worktrees/test1', { git_repo_root: '/www/app' }), [])).toBe(
      '/www/app'
    )
  })

  it('routes an in-tree worktree session to the owning explicit project', () => {
    const id = liveSessionProjectId(makeCwdSession('/www/app/.worktrees/test1', { git_repo_root: '/www/app' }), [
      makeProject('p_app', ['/www/app'])
    ])

    expect(id).toBe('p_app')
  })

  it('places a cwd-outside-root session under an explicit project matching either path', () => {
    // A mid-session relocation (or a sibling worktree) leaves cwd outside the
    // recorded repo root. An explicit folder match is still authoritative —
    // only the auto-project (repo root) fallback needs cwd-under-root
    // confidence. Match via the repo root...
    expect(
      liveSessionProjectId(makeCwdSession('/www/elsewhere', { git_repo_root: '/home/u/proj' }), [
        makeProject('p_proj', ['/home/u/proj'])
      ])
    ).toBe('p_proj')
    // ...and via the cwd.
    expect(
      liveSessionProjectId(makeCwdSession('/www/elsewhere/sub', { git_repo_root: '/home/u/proj' }), [
        makeProject('p_www', ['/www/elsewhere'])
      ])
    ).toBe('p_www')
  })

  it('matches a mixed-case/separator Windows cwd to its explicit project in the live overlay', () => {
    // The bug: a fresh Windows session drops into the overlay before the next
    // backend refresh; case-sensitive matching missed its project until then.
    const id = liveSessionProjectId(makeCwdSession('c:/work/notes/SUB'), [makeProject('p_notes', ['C:\\Work\\Notes'])])

    expect(id).toBe('p_notes')
  })

  it('matches a root-relative WSL cwd (single backslash) case-insensitively', () => {
    const id = liveSessionProjectId(makeCwdSession('//wsl.localhost/Ubuntu/home/alice/PROJ'), [
      makeProject('p_proj', ['\\wsl.localhost\\Ubuntu\\home\\alice\\proj'])
    ])

    expect(id).toBe('p_proj')
  })

  it('keeps POSIX cwd matching case-sensitive (no false project match)', () => {
    // Distinct case on POSIX is a distinct path → falls back to its own auto id.
    expect(liveSessionProjectId(makeCwdSession('/work/notes'), [makeProject('p_notes', ['/Work/Notes'])])).toBe(
      '/work/notes'
    )
  })

  it('matches NFD and NFC spellings of the same accented folder (#65014)', () => {
    // The same on-disk folder can reach us as NFC (typed paths, backend cwd)
    // or NFD (macOS file pickers) — byte-different, visually identical.
    const nfc = '/projects/sv/bist\u00e5nd'
    const nfd = nfc.normalize('NFD')

    expect(nfd).not.toBe(nfc) // premise: distinct byte strings
    expect(liveSessionProjectId(makeCwdSession(nfd), [makeProject('p_bistand', [nfc])])).toBe('p_bistand')
  })

  it('matches a Windows cwd differing in both case and normalization form (#65014)', () => {
    const id = liveSessionProjectId(makeCwdSession('d:/projects/sv/bist\u00e5nd'.normalize('NFD')), [
      makeProject('p_sv', ['D:\\Projects\\SV\\Bist\u00e5nd'.normalize('NFC')])
    ])

    expect(id).toBe('p_sv')
  })
})

describe('sessionProjectColor', () => {
  const colored = (id: string, folders: string[], color: string): ProjectInfo => ({
    ...makeProject(id, folders),
    color
  })

  it('inherits the color of the explicit project the session belongs to', () => {
    const session = makeCwdSession('/www/app/src', { git_repo_root: '/www/app' })

    expect(sessionProjectColor(session, [colored('p_app', ['/www/app'], '#4a9eff')])).toBe('#4a9eff')
  })

  it('returns null when the owning project has no color set', () => {
    const session = makeCwdSession('/www/app/src', { git_repo_root: '/www/app' })

    expect(sessionProjectColor(session, [makeProject('p_app', ['/www/app'])])).toBeNull()
  })

  it('colors a cwd-less session by its git_repo_root project (the grouped-but-grey fix)', () => {
    const session = makeCwdSession(null, { git_repo_root: '/www/app' })

    expect(sessionProjectColor(session, [colored('p_app', ['/www/app'], '#4a9eff')])).toBe('#4a9eff')
  })

  it('colors a cwd-outside-root session when an explicit project folder matches', () => {
    // The backend tree groups such a row under the project; the client color
    // derivation must agree instead of leaving the row (and its tab) grey.
    const session = makeCwdSession('/www/elsewhere', { git_repo_root: '/home/u/proj' })

    expect(sessionProjectColor(session, [colored('p_proj', ['/home/u/proj'], '#4a9eff')])).toBe('#4a9eff')
  })

  it('returns null for a session that only maps to an auto repo root (no explicit project)', () => {
    // liveSessionProjectId falls back to the repo root id, which is not a
    // project row and therefore carries no color.
    expect(sessionProjectColor(makeCwdSession('/www/app'), [])).toBeNull()
  })

  it('returns null for an unplaceable (cwd-less) session', () => {
    expect(sessionProjectColor(makeCwdSession(null), [colored('p_app', ['/www/app'], '#4a9eff')])).toBeNull()
  })

  it('uses the longest-prefix project when nested projects both match', () => {
    const session = makeCwdSession('/www/app/packages/api/src', { git_repo_root: '/www/app' })

    const projects = [
      colored('p_root', ['/www/app'], '#111111'),
      colored('p_api', ['/www/app/packages/api'], '#222222')
    ]

    expect(sessionProjectColor(session, projects)).toBe('#222222')
  })
})

describe('overlayLiveLanes', () => {
  // Issue layout: explicit "work" (/work) + explicit "app" (/work/repos/app);
  // the session's cwd is the SIBLING linked worktree /work/repos/app-2, which
  // the backend's git common-root probe assigns to "app" while the renderer's
  // cwd walk alone only finds "work".
  it.each([null, '/work/repos/app'])(
    'entering an ancestor project does not inject a backend-owned sibling worktree session (git_repo_root=%s)',
    gitRepoRoot => {
      const sibling = makeCwdSession('/work/repos/app-2', { id: 'sibling', git_repo_root: gitRepoRoot })

      const ancestor = projectNode({
        id: 'p_work',
        path: '/work',
        repos: [{ id: '/work', label: 'work', path: '/work', groups: [], sessionCount: 0 }]
      })

      const appRepo = {
        id: '/work/repos/app',
        label: 'app',
        path: '/work/repos/app',
        groups: [lane({ id: '/work/repos/app-2', label: 'app-2', path: '/work/repos/app-2', sessions: [] })],
        sessionCount: 0
      }

      // Overview snapshot: the row sits beyond the preview window, so only the
      // backend's claimed-id set knows the owner.
      const repo = projectNode({ id: 'p_app', path: '/work/repos/app', previewSessions: [], sessionIds: ['sibling'] })
      const owners = projectOwnerBySessionId([ancestor, repo])

      const enteredAncestor = overlayLiveLanes(ancestor, [sibling], new Set(), owners)
      const enteredRepo = overlayLiveLanes({ ...repo, repos: [appRepo] }, [sibling], new Set(), owners)

      expect(enteredAncestor.sessionCount).toBe(0)
      expect(enteredRepo.repos[0].groups.find(g => g.id === '/work/repos/app-2')?.sessions.map(s => s.id)).toEqual([
        'sibling'
      ])
      // A row the tree does not know yet (just created) still lands by cwd.
      const fresh = makeCwdSession('/work/notes', { id: 'fresh', git_repo_root: null })

      expect(overlayLiveLanes(ancestor, [fresh], new Set(), owners).sessionCount).toBe(1)
    }
  )

  it('keeps an overview preview visible when the hydrated drill-in is stale', () => {
    const staleHistory = makeCwdSession('/www/app', {
      id: 'stale-history',
      git_branch: 'main',
      last_active: 10
    })

    const currentPreview = makeCwdSession('/www/app', {
      id: 'current-preview',
      git_branch: 'main',
      last_active: 20
    })

    const project = projectNode({
      id: '/www/app',
      isAuto: true,
      previewSessions: [currentPreview],
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({
              id: '/www/app::branch::main',
              label: 'main',
              isMain: true,
              path: '/www/app',
              sessions: [staleHistory]
            })
          ]
        }
      ]
    })

    const overlaySessions = reconcileEnteredProjectSessions([], project.previewSessions)
    const overlaid = overlayLiveLanes(project, overlaySessions)

    expect(overlaid.repos[0].groups[0].sessions.map(session => session.id)).toEqual([
      'current-preview',
      'stale-history'
    ])
  })

  it('keeps the live row when it is also present in the overview preview', () => {
    const live = makeCwdSession('/www/app', { id: 'same', title: 'live title' })
    const preview = makeCwdSession('/www/app', { id: 'same', title: 'preview title' })
    const reconciled = reconcileEnteredProjectSessions([live], [preview])

    expect(reconciled).toEqual([live])
  })

  it('injects a live session into the matching main lane instantly', () => {
    const project = projectNode({
      id: '/www/app',
      isAuto: true,
      repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups: [] }]
    })

    const live = [makeCwdSession('/www/app', { id: 'fresh', git_branch: 'main' })]

    const overlaid = overlayLiveLanes(project, live)
    const lane = overlaid.repos[0].groups.find(g => g.label === 'main')

    expect(lane?.sessions.map(session => session.id)).toContain('fresh')
    expect(overlaid.sessionCount).toBe(1)
  })

  it('keeps cwd-less repo sessions visible in both the overview and project drill-in', () => {
    const project = projectNode({
      id: '/www/app',
      isAuto: true,
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 0,
          groups: [lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app' })]
        }
      ]
    })

    const live = makeCwdSession(null, { id: 'fresh', git_branch: 'main', git_repo_root: '/www/app' })

    expect(overlayLivePreviews([project], [live], [], 3)['/www/app'].map(session => session.id)).toEqual(['fresh'])

    const overlaid = overlayLiveLanes(project, [live])

    expect(overlaid.repos[0].groups.flatMap(group => group.sessions.map(session => session.id))).toEqual(['fresh'])
    expect(overlaid.sessionCount).toBe(1)
  })

  it('places a cwd-less repo session only in its exact repo subtree', () => {
    const project = projectNode({
      id: '/www',
      repos: [
        {
          id: '/www',
          label: 'www',
          path: '/www',
          sessionCount: 0,
          groups: [lane({ id: '/www::branch::main', label: 'main', isMain: true, path: '/www' })]
        },
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 0,
          groups: [lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app' })]
        }
      ]
    })

    const live = makeCwdSession(null, { id: 'fresh', git_branch: 'main', git_repo_root: '/www/app' })
    const overlaid = overlayLiveLanes(project, [live])

    expect(overlaid.repos[0].groups.flatMap(group => group.sessions)).toEqual([])
    expect(overlaid.repos[1].groups.flatMap(group => group.sessions.map(session => session.id))).toEqual(['fresh'])
    expect(overlaid.sessionCount).toBe(1)
  })

  it('injects a session created in a fresh worktree into that worktree lane (no git_repo_root yet)', () => {
    // The brand-new session row has only a cwd — no git_repo_root. The entered
    // project knows its repo root, so the worktree session still lands in its
    // own lane (not kanban, not skipped) optimistically.
    const project = projectNode({
      id: '/www/app',
      isAuto: true,
      repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups: [] }]
    })

    const live = [makeCwdSession('/www/app/.worktrees/baby', { id: 'fresh' })]

    const overlaid = overlayLiveLanes(project, live)
    const lane = overlaid.repos[0].groups.find(g => g.id === '/www/app/.worktrees/baby')

    expect(lane?.label).toBe('baby')
    expect(lane?.sessions.map(s => s.id)).toEqual(['fresh'])
  })

  it('folds a kanban-task worktree session into the kanban lane', () => {
    const project = projectNode({
      id: '/www/app',
      isAuto: true,
      repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups: [] }]
    })

    const live = [makeCwdSession('/www/app/.worktrees/t_abc12345', { id: 'k' })]

    const overlaid = overlayLiveLanes(project, live)
    const lane = overlaid.repos[0].groups.find(g => g.isKanban)

    expect(lane?.id).toBe('/www/app::kanban')
    expect(lane?.sessions.map(s => s.id)).toEqual(['k'])
  })

  it('does not duplicate a session already present in a backend lane', () => {
    const existing = makeCwdSession('/www/app', { id: 'dup', git_branch: 'main' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app', sessions: [existing] })
          ]
        }
      ]
    })

    const overlaid = overlayLiveLanes(project, [existing])

    expect(overlaid.repos[0].groups.flatMap(g => g.sessions.map(s => s.id))).toEqual(['dup'])
  })

  it('does not fork a phantom main lane for a non-git backend workspace lane', () => {
    // Backend non-git heuristic (`project_tree._place_by_heuristic`): lane id =
    // folder path, label = basename, isMain=true. Live overlay used to always
    // place under `::branch::main` / label "main", miss that lane by id+label,
    // and CREATE a second main lane with the same sessions — dual lanes in the
    // project drill-in (e.g. main + codex-research-guardian).
    const root = '/home/hermes/hermes-workspace/codex-research-guardian'
    const a = makeCwdSession(root, { id: 's1' }) // empty git_branch / git_repo_root
    const b = makeCwdSession(root, { id: 's2' })

    const project = projectNode({
      id: root,
      isAuto: true,
      path: root,
      repos: [
        {
          id: root,
          label: 'codex-research-guardian',
          path: root,
          sessionCount: 2,
          groups: [
            lane({
              id: root,
              label: 'codex-research-guardian',
              isMain: true,
              path: root,
              sessions: [a, b]
            })
          ]
        }
      ]
    })

    const overlaid = overlayLiveLanes(project, [a, b])
    const groups = overlaid.repos[0].groups

    expect(groups).toHaveLength(1)
    expect(groups[0].id).toBe(root)
    expect(groups[0].label).toBe('codex-research-guardian')
    expect(groups[0].sessions.map(s => s.id).sort()).toEqual(['s1', 's2'])
    expect(groups.some(g => g.label === 'main' || g.id.endsWith('::branch::main'))).toBe(false)
  })

  it('joins a fresh live session into an existing non-git workspace lane (no branch id)', () => {
    const root = '/work/notes'
    const existing = makeCwdSession(root, { id: 'old' })

    const project = projectNode({
      id: root,
      isAuto: true,
      path: root,
      repos: [
        {
          id: root,
          label: 'notes',
          path: root,
          sessionCount: 1,
          groups: [lane({ id: root, label: 'notes', isMain: true, path: root, sessions: [existing] })]
        }
      ]
    })

    const fresh = makeCwdSession(root, { id: 'fresh' })
    const overlaid = overlayLiveLanes(project, [existing, fresh])
    const groups = overlaid.repos[0].groups

    expect(groups).toHaveLength(1)
    expect(groups[0].id).toBe(root)
    expect(groups[0].sessions.map(s => s.id).sort()).toEqual(['fresh', 'old'])
  })

  it('preserves backend recency order when live sessions overlay a lane', () => {
    const recentlyActive = makeCwdSession('/www/app', {
      id: 'recently-active',
      git_branch: 'main',
      started_at: 1,
      last_active: 3
    })

    const newlyCreated = makeCwdSession('/www/app', {
      id: 'newly-created',
      git_branch: 'main',
      started_at: 2,
      last_active: 2
    })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 2,
          groups: [
            lane({
              id: '/www/app::branch::main',
              label: 'main',
              isMain: true,
              path: '/www/app',
              sessions: [recentlyActive, newlyCreated]
            })
          ]
        }
      ]
    })

    const overlaid = overlayLiveLanes(project, [recentlyActive, newlyCreated])

    expect(overlaid.repos[0].groups[0].sessions.map(session => session.id)).toEqual([
      'recently-active',
      'newly-created'
    ])
  })

  it('adds a new session to an existing worktree lane keyed by a divergent id (matches by path)', () => {
    // Backend keyed the worktree lane off a branch-style id (no live git probe),
    // but the lane PATH is the worktree dir. A new session under that worktree
    // must join the existing lane, not spawn a twin.
    const existing = makeCwdSession('/www/app/.worktrees/baby', { id: 'old' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({
              id: '/www/app::branch::baby',
              label: 'baby',
              path: '/www/app/.worktrees/baby',
              sessions: [existing]
            })
          ]
        }
      ]
    })

    const fresh = makeCwdSession('/www/app/.worktrees/baby', { id: 'fresh' })

    const overlaid = overlayLiveLanes(project, [existing, fresh])
    const lanes = overlaid.repos[0].groups.filter(g => g.path === '/www/app/.worktrees/baby')

    expect(lanes).toHaveLength(1)
    expect(lanes[0].sessions.map(s => s.id).sort()).toEqual(['fresh', 'old'])
  })

  it('places a session into an out-of-tree (sibling) worktree lane by its path', () => {
    // `hermes-agent-ci` is a linked worktree living BESIDE the repo, not under
    // it — repo-root nesting fails, but the existing lane carries its real path.
    const existing = makeCwdSession('/www/app-ci', { id: 'old' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app', sessions: [] }),
            lane({ id: '/www/app-ci', label: 'app-ci', path: '/www/app-ci', sessions: [existing] })
          ]
        }
      ]
    })

    const fresh = makeCwdSession('/www/app-ci', { id: 'fresh' })

    const overlaid = overlayLiveLanes(project, [existing, fresh])
    const ci = overlaid.repos[0].groups.find(g => g.path === '/www/app-ci')
    const main = overlaid.repos[0].groups.find(g => g.label === 'main')

    expect(ci?.sessions.map(s => s.id).sort()).toEqual(['fresh', 'old'])
    expect(main?.sessions ?? []).toHaveLength(0)
  })

  it('places into a visual-only discovered worktree lane after merge', () => {
    const discovered = [
      { path: '/www/app-retry', branch: 'bb/ci-install-retry', isMain: false, detached: false, locked: false }
    ]

    const groups = mergeRepoWorktreeGroups({ id: '/www/app', path: '/www/app', groups: [] }, discovered)

    const project = projectNode({
      id: '/www/app',
      repos: [{ id: '/www/app', label: 'app', path: '/www/app', sessionCount: 0, groups }]
    })

    const fresh = makeCwdSession('/www/app-retry', { id: 'fresh' })

    const overlaid = overlayLiveLanes(project, [fresh])
    const lane = overlaid.repos[0].groups.find(g => g.path === '/www/app-retry')

    expect(lane?.sessions.map(s => s.id)).toEqual(['fresh'])
  })

  it('evicts a deleted/archived snapshot row (and drops the lane once empty)', () => {
    const a = makeCwdSession('/www/app', { id: 'keep', git_branch: 'main' })
    const b = makeCwdSession('/www/app/.worktrees/baby', { id: 'gone' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 2,
          groups: [
            lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app', sessions: [a] }),
            lane({ id: '/www/app/.worktrees/baby', label: 'baby', path: '/www/app/.worktrees/baby', sessions: [b] })
          ]
        }
      ]
    })

    // No live rows (both deleted from $sessions); only 'gone' is tombstoned.
    const overlaid = overlayLiveLanes(project, [a], new Set(['gone']))

    expect(overlaid.repos[0].groups.map(g => g.id)).toEqual(['/www/app::branch::main'])
    expect(overlaid.repos[0].groups[0].sessions.map(s => s.id)).toEqual(['keep'])
    expect(overlaid.sessionCount).toBe(1)
  })

  it('adds a brand-new detached chat to Home, and evicts a deleted one', () => {
    const existing = makeCwdSession(null, { id: 'old', started_at: 1 })
    const doomed = makeCwdSession(null, { id: 'gone', started_at: 2 })
    const home = homeNode([existing, doomed])

    const overlaid = overlayLiveLanes(home, [makeCwdSession(null, { id: 'fresh', started_at: 9 })], new Set(['gone']))

    expect(overlaid.repos[0].groups[0].sessions.map(s => s.id)).toEqual(['fresh', 'old'])
    expect(overlaid.sessionCount).toBe(2)
  })

  it('never lists a chat owned by a named project in Home, even while its live copy is detached', () => {
    // #77591: the snapshot assigns the chat to p_app, but session.info can land
    // with an empty cwd + root. Home must defer to the one owner, including by
    // lineage root after compression rotates the live id.
    const home = homeNode([makeCwdSession(null, { id: 'stale' })])

    const owners = new Map([
      ['owned', 'p_app'],
      ['root', 'p_app'],
      ['stale', 'p_app'],
      ['homeless', NO_PROJECT_ID]
    ])

    const live = [
      makeCwdSession(null, { id: 'owned' }),
      makeCwdSession(null, { id: 'tip', _lineage_root_id: 'root' }),
      makeCwdSession(null, { id: 'homeless' })
    ]

    const overlaid = overlayLiveLanes(home, live, new Set(), owners)

    expect(overlaid.repos[0].groups[0].sessions.map(s => s.id)).toEqual(['homeless'])
    expect(overlaid.sessionCount).toBe(1)
  })

  it('leaves Home alone for a session that has a cwd', () => {
    // A cwd-carrying row the backend hasn't placed yet (junk root, deleted
    // workspace) needs its probes — guessing here would flicker it into Home
    // and back out on the next snapshot.
    const home = homeNode([])

    expect(overlayLiveLanes(home, [makeCwdSession('/www/app', { id: 'fresh' })])).toBe(home)
  })

  it('lists a cwd-carrying chat the snapshot filed in Home (#139909)', () => {
    // A Desktop chat stamped with the bare home dir: the backend files it in
    // Home, but the unhydrated tree carries only its id (`sessionIds`), so the
    // overlay is the only thing that can paint its row.
    const stamped = makeCwdSession('C:\\Users\\wrain', { id: 'stamped' })
    const home = { ...homeNode([]), previewSessions: [stamped], sessionCount: 1, sessionIds: ['stamped'] }

    const overlaid = overlayLiveLanes(home, [stamped], new Set(), projectOwnerBySessionId([home]))

    expect(overlaid.repos[0].groups[0].sessions.map(s => s.id)).toEqual(['stamped'])
    expect(overlaid.sessionCount).toBe(1)
  })

  // #77591 C: compression rotates the live id (root -> tip) while the snapshot
  // still holds the older segment. Both are one conversation, so one row.
  it.each([
    ['a first compression', { id: 'root' }, { id: 'tip', _lineage_root_id: 'root', _lineage_ids: ['root', 'tip'] }],
    [
      'a deeper chain',
      { id: 'mid', _lineage_root_id: 'root', _lineage_ids: ['root', 'mid'] },
      { id: 'tip', _lineage_root_id: 'root', _lineage_ids: ['root', 'mid', 'tip'] }
    ]
  ])('replaces the snapshot row with its compressed live tip after %s', (_label, snapshotIds, liveIds) => {
    const stale = makeCwdSession('/www/app', { ...snapshotIds, git_branch: 'main', last_active: 10 })
    const tip = makeCwdSession('/www/app', { ...liveIds, git_branch: 'main', last_active: 20 })

    const project = projectNode({
      id: '/www/app',
      isAuto: true,
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app', sessions: [stale] })
          ]
        }
      ]
    })

    const overlaid = overlayLiveLanes(project, [tip])

    expect(overlaid.repos[0].groups.flatMap(g => g.sessions.map(s => s.id))).toEqual(['tip'])
    expect(overlaid.sessionCount).toBe(1)
    // The drill-in's preview backfill must not re-add the older segment either.
    expect(reconcileEnteredProjectSessions([tip], [stale]).map(s => s.id)).toEqual(['tip'])
  })

  it('keeps a compressed tip out of an ancestor project the snapshot did not give it to', () => {
    // The owner map only knows the pre-compression id; the tip must inherit it
    // instead of being re-placed by cwd into the umbrella project as well.
    const tip = makeCwdSession('/work/repos/app-2', {
      id: 'tip',
      _lineage_root_id: 'root',
      _lineage_ids: ['root', 'tip'],
      git_repo_root: null
    })

    const ancestor = projectNode({
      id: 'p_work',
      path: '/work',
      repos: [{ id: '/work', label: 'work', path: '/work', groups: [], sessionCount: 0 }]
    })

    const repo = projectNode({ id: 'p_app', path: '/work/repos/app', sessionIds: ['root'] })
    const owners = projectOwnerBySessionId([ancestor, repo])

    expect(overlayLiveLanes(ancestor, [tip], new Set(), owners).sessionCount).toBe(0)
  })

  it('evicts a session from the main lane when the live overlay places it into a worktree lane', () => {
    // Session was in main when the backend tree was captured, but the live
    // $sessions cache now has it under a worktree cwd. The overlay must place
    // it ONLY in the worktree lane — not both.
    const session = makeCwdSession('/www/app/.worktrees/feature', { id: 'moved', git_branch: 'feature' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({ id: '/www/app::branch::main', label: 'main', isMain: true, path: '/www/app', sessions: [session] }),
            lane({
              id: '/www/app/.worktrees/feature',
              label: 'feature',
              path: '/www/app/.worktrees/feature',
              sessions: []
            })
          ]
        }
      ]
    })

    const overlaid = overlayLiveLanes(project, [session])
    const mainLane = overlaid.repos[0].groups.find(g => g.isMain)
    const featureLane = overlaid.repos[0].groups.find(g => g.path === '/www/app/.worktrees/feature')

    // Session must NOT appear in the main lane
    expect(mainLane?.sessions ?? []).toHaveLength(0)
    // Session must appear only in the worktree lane
    expect(featureLane?.sessions.map(s => s.id)).toEqual(['moved'])
    expect(overlaid.sessionCount).toBe(1)
  })
})

describe('overlayLivePreviews', () => {
  it.each([null, '/work/repos/app'])(
    'shows a backend-owned sibling worktree session only under its repo project (git_repo_root=%s)',
    gitRepoRoot => {
      const sibling = makeCwdSession('/work/repos/app-2', { id: 'sibling', git_repo_root: gitRepoRoot })
      const ancestor = projectNode({ id: 'p_work', path: '/work', previewSessions: [], sessionCount: 0 })

      const repo = projectNode({
        id: 'p_app',
        path: '/work/repos/app',
        previewSessions: [sibling],
        sessionCount: 1,
        sessionIds: ['sibling']
      })

      const previews = overlayLivePreviews(
        [ancestor, repo],
        [sibling],
        [makeProject('p_work', ['/work']), makeProject('p_app', ['/work/repos/app'])],
        3
      )

      expect(previews.p_work).toBeUndefined()
      expect(previews.p_app?.map(session => session.id)).toEqual(['sibling'])
    }
  )
  it('merges live sessions into a project preview, live first, capped to the limit', () => {
    const project = projectNode({
      id: '/www/app',
      previewSessions: [makeCwdSession('/www/app', { id: 'old', started_at: 1, last_active: 1 })]
    })

    const live = [makeCwdSession('/www/app', { id: 'fresh', started_at: 99, last_active: 99 })]

    const previews = overlayLivePreviews([project], live, [], 3)

    expect(previews['/www/app'].map(s => s.id)).toEqual(['fresh', 'old'])
  })

  it('previews a compressed chat once, as its live tip (#77591)', () => {
    const stale = makeCwdSession('/www/app', { id: 'root', last_active: 10 })

    const tip = makeCwdSession('/www/app', {
      id: 'tip',
      _lineage_root_id: 'root',
      _lineage_ids: ['root', 'tip'],
      last_active: 20
    })

    const project = projectNode({ id: '/www/app', previewSessions: [stale], sessionIds: ['root'] })
    const previews = overlayLivePreviews([project], [tip], [], 3)

    expect(previews['/www/app'].map(s => s.id)).toEqual(['tip'])
  })

  it('evicts a deleted session from a project preview (snapshot + live)', () => {
    const project = projectNode({
      id: '/www/app',
      previewSessions: [
        makeCwdSession('/www/app', { id: 'gone', started_at: 5, last_active: 5 }),
        makeCwdSession('/www/app', { id: 'old', started_at: 1, last_active: 1 })
      ]
    })

    const previews = overlayLivePreviews([project], [], [], 3, { removed: new Set(['gone']) })

    expect(previews['/www/app'].map(s => s.id)).toEqual(['old'])
  })

  it('ranks by the active sort key before trimming, so the preview is its top rows', () => {
    const project = projectNode({
      id: '/www/app',
      previewSessions: [
        makeCwdSession('/www/app', { id: 'newest', last_active: 9, started_at: 9 }),
        makeCwdSession('/www/app', { id: 'cheap', last_active: 8, started_at: 8 }),
        makeCwdSession('/www/app', { id: 'priciest', last_active: 1, started_at: 1 })
      ]
    })

    const previews = overlayLivePreviews([project], [], [], 2, { rankIds: ['priciest', 'newest', 'cheap'] })

    expect(previews['/www/app'].map(s => s.id)).toEqual(['priciest', 'newest'])
  })

  it('previews a detached session under Home, which no cwd could place', () => {
    const previews = overlayLivePreviews([homeNode([])], [makeCwdSession(null, { id: 'fresh' })], [], 3)

    expect(previews[NO_PROJECT_ID].map(s => s.id)).toEqual(['fresh'])
  })
})

describe('excludeProjectSessions', () => {
  it('drops matching rows from every lane and recounts the subtree', () => {
    const keep = makeCwdSession('/www/app', { id: 'keep' })
    const pinnedRow = makeCwdSession('/www/app', { id: 'pinned' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 2,
          groups: [lane({ id: 'main', isMain: true, label: 'main', path: '/www/app', sessions: [keep, pinnedRow] })]
        }
      ],
      sessionCount: 2
    })

    const filtered = excludeProjectSessions(project, session => session.id === 'pinned')

    expect(filtered.repos[0].groups[0].sessions.map(s => s.id)).toEqual(['keep'])
    expect(filtered.repos[0].sessionCount).toBe(1)
    expect(filtered.sessionCount).toBe(1)
  })

  it('keeps a lane the filter emptied — a worktree is structure, not a row', () => {
    const pinnedRow = makeCwdSession('/www/app/wt', { id: 'pinned' })

    const project = projectNode({
      id: '/www/app',
      previewSessions: [pinnedRow],
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [lane({ id: 'wt', label: 'wt', path: '/www/app/wt', sessions: [pinnedRow] })]
        }
      ],
      sessionCount: 1
    })

    const filtered = excludeProjectSessions(project, session => session.id === 'pinned')

    expect(filtered.repos[0].groups.map(g => g.id)).toEqual(['wt'])
    expect(filtered.repos[0].groups[0].sessions).toEqual([])
    expect(filtered.previewSessions).toEqual([])
    expect(filtered.sessionCount).toBe(0)
  })

  it('returns the same node when nothing matches (memo-stable)', () => {
    const project = projectNode({
      id: '/www/app',
      previewSessions: [makeCwdSession('/www/app', { id: 'keep' })],
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [
            lane({ id: 'main', isMain: true, label: 'main', sessions: [makeCwdSession('/www/app', { id: 'keep' })] })
          ]
        }
      ],
      sessionCount: 1
    })

    expect(excludeProjectSessions(project, () => false)).toBe(project)
  })

  it('survives the live overlay: a lane left empty by the filter is not pruned', () => {
    // The two run in sequence on an entered project (filter, then overlay), and
    // the overlay drops lanes it empties — it must not take the filter's with it.
    const pinnedRow = makeCwdSession('/www/app/wt', { id: 'pinned' })

    const project = projectNode({
      id: '/www/app',
      repos: [
        {
          id: '/www/app',
          label: 'app',
          path: '/www/app',
          sessionCount: 1,
          groups: [lane({ id: 'wt', label: 'wt', path: '/www/app/wt', sessions: [pinnedRow] })]
        }
      ],
      sessionCount: 1
    })

    const filtered = excludeProjectSessions(project, session => session.id === 'pinned')
    const overlaid = overlayLiveLanes(filtered, [], new Set(['someone-else']))

    expect(overlaid.repos[0].groups.map(g => g.id)).toEqual(['wt'])
  })
})

describe('project filter row rule (#97762)', () => {
  const projects = [makeProject('p_app', ['/www/app'])]
  const appRow = makeCwdSession('/www/app/src', { git_repo_root: '/www/app' })
  const homeRow = makeCwdSession(null)

  it('filtering to Home keeps the detached Home rows', () => {
    expect(sessionMatchesProjectFilter(homeRow, [NO_PROJECT_ID], projects)).toBe(true)
    expect(sessionMatchesProjectFilter(appRow, [NO_PROJECT_ID], projects)).toBe(false)
  })

  it('a live id still narrows', () => {
    expect(sessionMatchesProjectFilter(appRow, ['p_app'], projects)).toBe(true)
    expect(sessionMatchesProjectFilter(homeRow, ['p_app'], projects)).toBe(false)
  })

  // Issue layout: the sibling worktree /work/repos/app-2 sits under the
  // ancestor "work" folder by cwd alone, but the backend tree owns it via "app".
  // Filter, bucket and color must follow that owner, like the lane overlay does.
  it('follows the backend owner map for a sibling worktree row, not the cwd walk', () => {
    const explicit = [makeProject('p_work', ['/work']), { ...makeProject('p_app', ['/work/repos/app']), color: '#abc' }]
    const sibling = makeCwdSession('/work/repos/app-2', { id: 'sibling', git_repo_root: null })

    const owners = projectOwnerBySessionId([
      projectNode({ id: 'p_work', path: '/work' }),
      projectNode({ id: 'p_app', path: '/work/repos/app', sessionIds: ['sibling'] })
    ])

    expect(sessionMatchesProjectFilter(sibling, ['p_work'], explicit, owners)).toBe(false)
    expect(sessionMatchesProjectFilter(sibling, ['p_app'], explicit, owners)).toBe(true)
    expect(sessionBucketId(sibling, explicit, owners)).toBe('p_app')
    expect(sessionProjectColor(sibling, explicit, owners)).toBe('#abc')
  })

  // #139909: the backend files a home-dir-stamped chat in Home; its cwd alone
  // would make it a phantom project named after the home dir.
  it('files a row the backend placed in Home under Home, cwd or not', () => {
    const stamped = makeCwdSession('/home/me', { id: 'stamped', git_repo_root: null })

    const owners = projectOwnerBySessionId([
      projectNode({ id: NO_PROJECT_ID, isNoProject: true, sessionIds: ['stamped'] })
    ])

    expect(sessionBucketId(stamped, projects, owners)).toBe(NO_PROJECT_ID)
    expect(sessionMatchesProjectFilter(stamped, [NO_PROJECT_ID], projects, owners)).toBe(true)
  })
})