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.

6.0 KB
Raw Blame
import type { Page } from '@stablyai/playwright-test'
import { linkWorkspaces, writeWorkspaceMeta } from './helpers/repo-with-workspaces'

export type LineageScenario = {
  parentId: string
  childId: string
}

export async function seedLineageScenario(
  page: Page,
  options: { inlineOnly?: boolean; preserveGrouping?: boolean } = {}
): Promise<LineageScenario> {
  const family = await page.evaluate((preserveGrouping) => {
    const store = window.__store
    if (!store) {
      throw new Error('window.__store is not available')
    }

    const state = store.getState()
    state.setActiveView('terminal')
    state.setSidebarOpen(true)
    if (!preserveGrouping) {
      state.setGroupBy('none')
    }
    state.setSortBy('recent')
    // Clear persisted sidebar filters so structure tests render the child even without a live PTY.
    state.setShowActiveOnly(false)
    state.setShowSleepingWorkspaces(true)
    state.setHideDefaultBranchWorkspace(false)
    state.setFilterRepoIds([])

    const worktrees = Object.values(state.worktreesByRepo)
      .flat()
      .filter((worktree) => !worktree.isArchived)
    if (worktrees.length < 2) {
      throw new Error('Worktree lineage E2E needs at least two worktrees')
    }

    const [parent, child] = worktrees
    if (!parent.instanceId || !child.instanceId) {
      throw new Error('Worktree lineage E2E needs instance-stamped worktrees')
    }
    return {
      parentId: parent.id,
      childId: child.id,
      parentInstanceId: parent.instanceId,
      childInstanceId: child.instanceId
    }
  }, options.preserveGrouping ?? false)
  const { parentId, childId } = family
  await writeWorkspaceMeta(page, [
    { worktreeId: parentId, updates: { displayName: 'E2E lineage parent', sortOrder: 0 } },
    { worktreeId: childId, updates: { displayName: 'E2E lineage child', sortOrder: 1 } }
  ])
  if (!options.inlineOnly) {
    await linkWorkspaces(page, [{ childId, parentId }])
  }
  if (options.inlineOnly) {
    // Window-only on purpose: the records' inline link with no side map, which main cannot produce.
    await page.evaluate(({ parentId, childId, parentInstanceId, childInstanceId }) => {
      const lineage = {
        worktreeId: childId,
        worktreeInstanceId: childInstanceId,
        parentWorktreeId: parentId,
        parentWorktreeInstanceId: parentInstanceId,
        origin: 'manual' as const,
        capture: { source: 'manual-action' as const, confidence: 'explicit' as const },
        createdAt: Date.now()
      }
      window.__store!.setState((current) => ({
        worktreesByRepo: Object.fromEntries(
          Object.entries(current.worktreesByRepo).map(([repoId, repoWorktrees]) => [
            repoId,
            repoWorktrees.map((worktree) =>
              worktree.id === parentId
                ? {
                    ...worktree,
                    parentWorktreeId: null,
                    childWorktreeIds: [childId],
                    lineage: null
                  }
                : worktree.id === childId
                  ? { ...worktree, parentWorktreeId: parentId, childWorktreeIds: [], lineage }
                  : worktree
            )
          ])
        ),
        worktreeLineageById: {}
      }))
    }, family)
  }
  await page.evaluate(
    (parentId) => window.__store!.getState().setActiveWorktree(parentId),
    parentId
  )
  return { parentId, childId }
}

export async function seedWorkspaceAgentStatus(
  page: Page,
  worktreeId: string,
  label: string
): Promise<string> {
  return page.evaluate(
    ({ worktreeId, label }) => {
      const store = window.__store
      if (!store) {
        throw new Error('window.__store is not available')
      }

      const state = store.getState()
      if (!state.worktreeCardProperties.includes('inline-agents')) {
        state.setWorktreeCardProperties([...state.worktreeCardProperties, 'inline-agents'])
      }
      if ((state.tabsByWorktree[worktreeId] ?? []).length === 0) {
        state.createTab(worktreeId)
      }

      const next = store.getState()
      const tab = next.tabsByWorktree[worktreeId]?.[0]
      if (!tab) {
        throw new Error(`Worktree lineage E2E failed to create a ${label} workspace tab`)
      }

      const prompt = `LINEAGE_${label}_AGENT_${Date.now()}`
      const leafId = crypto.randomUUID()
      const now = Date.now()
      next.setAgentStatus(
        `${tab.id}:${leafId}`,
        { state: 'working', prompt, agentType: 'codex' },
        'codex',
        { updatedAt: now, stateStartedAt: now }
      )
      return prompt
    },
    { worktreeId, label }
  )
}

export async function seedWorkspaceLiveTerminal(page: Page, worktreeId: string): Promise<string> {
  return page.evaluate((worktreeId) => {
    const store = window.__store
    if (!store) {
      throw new Error('window.__store is not available')
    }

    const state = store.getState()
    if ((state.tabsByWorktree[worktreeId] ?? []).length === 0) {
      state.createTab(worktreeId)
    }

    const next = store.getState()
    const tab = next.tabsByWorktree[worktreeId]?.[0]
    if (!tab) {
      throw new Error('Worktree lineage E2E failed to create a live terminal tab')
    }

    next.dropAgentStatusByWorktree(worktreeId)
    store.setState((current) => ({
      ptyIdsByTabId: {
        ...current.ptyIdsByTabId,
        [tab.id]: [`e2e-live-pty-${Date.now()}`]
      },
      browserTabsByWorktree: {
        ...current.browserTabsByWorktree,
        [worktreeId]: []
      }
    }))
    return tab.id
  }, worktreeId)
}

export async function markWorkspaceTerminalSlept(
  page: Page,
  args: { worktreeId: string; tabId: string }
): Promise<void> {
  await page.evaluate(({ worktreeId, tabId }) => {
    const store = window.__store
    if (!store) {
      throw new Error('window.__store is not available')
    }

    store.getState().dropAgentStatusByWorktree(worktreeId)
    store.setState((current) => ({
      ptyIdsByTabId: {
        ...current.ptyIdsByTabId,
        [tabId]: []
      },
      browserTabsByWorktree: {
        ...current.browserTabsByWorktree,
        [worktreeId]: []
      }
    }))
  }, args)
}