Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

7.1 KB
Raw Blame
import { execFileSync } from 'node:child_process'
import { mkdtempSync, realpathSync, rmSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { test, expect } from './helpers/orca-app'
import { loadWorktreesUntilPathsPresent } from './helpers/worktree-registration'

test.describe('Workspace Space git status checks', () => {
  test('checks every scanned deletable row, including rows after the first 50', async ({
    electronApp,
    orcaPage,
    testRepoPath
  }) => {
    // Canonicalize parent before git worktree add so macOS/CI tmp symlinks match Orca’s realpath-registered rows.
    const worktreeParent = realpathSync(
      mkdtempSync(path.join(os.tmpdir(), 'orca-space-git-status-'))
    )
    const worktreePaths = Array.from({ length: 60 }, (_, index) =>
      path.join(worktreeParent, `worktree-${index}`)
    )

    try {
      for (const worktreePath of worktreePaths) {
        execFileSync('git', ['worktree', 'add', '--detach', worktreePath, 'HEAD'], {
          cwd: testRepoPath,
          stdio: 'pipe'
        })
      }
      const registeredWorktreePaths = worktreePaths.map((worktreePath) =>
        realpathSync(worktreePath)
      )

      const repoId = await orcaPage.evaluate((testRepoPath) => {
        const store = window.__store
        if (!store) {
          throw new Error('Expected e2e store to be exposed')
        }
        const repo = store.getState().repos.find((item) => item.path === testRepoPath)
        if (!repo) {
          throw new Error('Expected test repo to be loaded')
        }
        return repo.id
      }, testRepoPath)

      // Poll past the 5s scan cache until all 60 raw-git-added worktrees register before deriving space rows.
      await loadWorktreesUntilPathsPresent(orcaPage, repoId, registeredWorktreePaths)

      const rowDisplayNames = await orcaPage.evaluate(
        async ({ testRepoPath, worktreePaths }) => {
          const store = window.__store
          if (!store) {
            throw new Error('Expected e2e store to be exposed')
          }

          const initialState = store.getState()
          const repo = initialState.repos.find((item) => item.path === testRepoPath)
          if (!repo) {
            throw new Error('Expected test repo to be loaded')
          }
          await window.api.git.status({ worktreePath: worktreePaths[0] })

          const state = store.getState()
          const expectedPaths = new Set(worktreePaths)
          const worktrees = (state.worktreesByRepo[repo.id] ?? []).filter((worktree) =>
            expectedPaths.has(worktree.path)
          )
          if (worktrees.length !== worktreePaths.length) {
            throw new Error(
              `Expected ${worktreePaths.length} registered worktrees, got ${
                worktrees.length
              } from ${(state.worktreesByRepo[repo.id] ?? []).length}: ${(
                state.worktreesByRepo[repo.id] ?? []
              )
                .slice(0, 5)
                .map((worktree) => worktree.path)
                .join(', ')}`
            )
          }
          const rows = worktrees.map((worktree, index) => ({
            worktreeId: worktree.id,
            repoId: repo.id,
            repoDisplayName: repo.displayName,
            repoPath: testRepoPath,
            displayName: worktree.displayName,
            path: worktree.path,
            branch: worktree.branch,
            isMainWorktree: false,
            isRemote: false,
            isSparse: worktree.isSparse === true,
            canDelete: true,
            lastActivityAt: worktree.lastActivityAt,
            status: 'ok' as const,
            error: null,
            scannedAt: Date.now(),
            sizeBytes: 1000 + index,
            reclaimableBytes: 1000 + index,
            skippedEntryCount: 0,
            topLevelItems: [],
            omittedTopLevelItemCount: 0,
            omittedTopLevelSizeBytes: 0
          }))

          store.setState({
            gitStatusByWorktree: {},
            workspaceSpaceAnalysis: {
              scannedAt: Date.now(),
              totalSizeBytes: rows.reduce((sum, row) => sum + row.sizeBytes, 0),
              reclaimableBytes: rows.reduce((sum, row) => sum + row.reclaimableBytes, 0),
              worktreeCount: rows.length,
              scannedWorktreeCount: rows.length,
              unavailableWorktreeCount: 0,
              repos: [
                {
                  repoId: repo.id,
                  displayName: repo.displayName,
                  path: repo.path,
                  isRemote: false,
                  worktreeCount: rows.length,
                  scannedWorktreeCount: rows.length,
                  unavailableWorktreeCount: 0,
                  totalSizeBytes: rows.reduce((sum, row) => sum + row.sizeBytes, 0),
                  reclaimableBytes: rows.reduce((sum, row) => sum + row.reclaimableBytes, 0),
                  error: null
                }
              ],
              worktrees: rows
            }
          })
          store.getState().openSpacePage()
          return rows.map((row) => row.displayName)
        },
        { testRepoPath, worktreePaths: registeredWorktreePaths }
      )

      // Visit every virtualized row so offscreen unchecked statuses cannot pass unnoticed.
      const findSpacePage = () =>
        electronApp.windows().find((page) => page.url().endsWith('/space.html'))
      await expect.poll(() => Boolean(findSpacePage())).toBe(true)
      const spacePage = findSpacePage()
      if (!spacePage) {
        throw new Error('Expected the Space window to open')
      }
      const rowName = new RegExp(
        `^Select (?:${rowDisplayNames
          .map((displayName) => displayName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
          .join('|')})$`
      )
      const list = spacePage.getByTestId('virtualized-list')
      for (let position = 1; position <= rowDisplayNames.length; position += 1) {
        const row = list.locator(`[aria-posinset="${position}"]`)
        if ((await row.count()) === 0) {
          await list.evaluate(
            (element, { position, count }) => {
              const scroller = element.parentElement
              if (!scroller) {
                throw new Error('Expected the workspace list scroll container')
              }
              scroller.scrollTop = (element.clientHeight * (position - 1)) / count
            },
            { position, count: rowDisplayNames.length }
          )
        }
        await expect(row).toHaveAttribute('aria-setsize', String(rowDisplayNames.length))
        await expect(row.getByRole('checkbox', { name: rowName })).toHaveCount(1)
        await expect(row.getByText('Keep: git not checked')).toHaveCount(0, {
          timeout: 30_000
        })
      }
    } finally {
      for (const worktreePath of worktreePaths) {
        try {
          execFileSync('git', ['worktree', 'remove', '--force', worktreePath], {
            cwd: testRepoPath,
            stdio: 'pipe'
          })
        } catch {
          // Best effort cleanup; the fixture removes the source repo after the test.
        }
      }
      rmSync(worktreeParent, { recursive: true, force: true })
    }
  })
})