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.

9.8 KB
Raw Blame
import { getFileOpenPosition } from './file-open-position'
import type { GitStatusEntry, GitStatusResult } from '../../shared/git-status-types'
import type { RuntimeFileOpenResult, RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation'
import { isRuntimePathAbsolute, relativePathInsideRoot } from '../../shared/cross-platform-path'
import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import { printResult } from '../format'
import { RuntimeClientError } from '../runtime-client'
import { callFileOpen } from './file-open-call'
import { getOptionalWorktreeSelector, resolveCurrentWorktreeSelector } from '../selectors'

type FileOpenMode = 'edit' | 'diff'
type OpenChangedMode = FileOpenMode | 'both'

type FileOpenRecord = {
  path: string
  mode: FileOpenMode
  staged?: boolean
  opened: boolean
  kind?: RuntimeFileOpenResult['kind']
  skipped?: boolean
  reason?: string
}

type FileOpenChangedResult = {
  worktree: string
  mode: OpenChangedMode
  opened: FileOpenRecord[]
  skipped: FileOpenRecord[]
  totalChanged: number
}

async function getFileWorktreeSelector({ flags, cwd, client }: HandlerContext): Promise<string> {
  const worktree = flags.get('worktree')
  if (flags.has('worktree') && (typeof worktree !== 'string' || worktree.length === 0)) {
    throw new RuntimeClientError('invalid_argument', 'Missing value for --worktree.')
  }
  const explicit = await getOptionalWorktreeSelector(flags, 'worktree', cwd, client)
  if (explicit) {
    return explicit
  }
  if (client.isRemote) {
    throw new RuntimeClientError(
      'invalid_argument',
      'Remote file commands require --worktree because the client cwd cannot identify a server worktree.'
    )
  }
  return await resolveCurrentWorktreeSelector(cwd, client)
}

// Only UNC roots need Linux-path translation; backslash filenames have no equivalent Windows spelling.
function toWorktreeRootPathFlavor(rootPath: string, cwd: string, path: string): string {
  // Interop may omit WSL_DISTRO_NAME; the launcher's UNC cwd also identifies the caller's distro.
  const distro = process.env.WSL_DISTRO_NAME || parseWslUncPath(cwd)?.distro
  if (
    !distro ||
    !path.startsWith('/') ||
    path.startsWith('//') ||
    path.includes('\\') ||
    !isWslUncPath(rootPath)
  ) {
    return path
  }
  return toWindowsWslPath(path, distro)
}

async function resolveFilePath(
  ctx: HandlerContext,
  worktree: string,
  path: string
): Promise<string> {
  if (!isRuntimePathAbsolute(path)) {
    return path
  }
  // Relativize only paths inside the worktree; leave others for the runtime guard.
  const result = await ctx.client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
    worktree
  })

  const rootPath = result.result.worktree.path
  const relativePath = relativePathInsideRoot(
    rootPath,
    toWorktreeRootPathFlavor(rootPath, ctx.cwd, path)
  )
  if (relativePath === '') {
    throw new RuntimeClientError(
      'invalid_argument',
      'The selected worktree root is a directory, not a file-open target.'
    )
  }
  return relativePath ?? path
}

function getOpenChangedMode(flags: Map<string, string | boolean>): OpenChangedMode {
  const value = flags.get('mode')
  if (flags.has('mode') && (typeof value !== 'string' || value.length === 0)) {
    throw new RuntimeClientError(
      'invalid_argument',
      'Missing value for --mode. Use edit, diff, or both.'
    )
  }
  const mode = getOptionalStringFlag(flags, 'mode') ?? 'diff'
  if (mode === 'edit' || mode === 'diff' || mode === 'both') {
    return mode
  }
  throw new RuntimeClientError('invalid_argument', 'Invalid --mode. Use edit, diff, or both.')
}

// caller leaves views unchanged; --focus moves only the host window, preserving paired viewers.
function getFileOpenNavigation(flags: Map<string, string | boolean>): RuntimeNavigationTarget {
  return flags.get('focus') === true ? 'all' : 'caller'
}

function canOpenEntryForEdit(entry: GitStatusEntry): string | null {
  if (entry.status === 'deleted') {
    return 'deleted file has no edit target'
  }
  if (entry.conflictStatus === 'unresolved') {
    return 'unresolved conflict may not have a single editable file'
  }
  return null
}

async function openFileEdit(
  ctx: HandlerContext,
  worktree: string,
  path: string,
  navigation: RuntimeNavigationTarget
): Promise<FileOpenRecord> {
  const result = await callFileOpen(ctx, 'files.open', {
    worktree,
    relativePath: path,
    navigation
  })
  return {
    path,
    mode: 'edit',
    opened: result.result.opened,
    kind: result.result.kind,
    ...(result.result.opened ? {} : { skipped: true, reason: `${result.result.kind} file` })
  }
}

async function openFileDiff(
  ctx: HandlerContext,
  worktree: string,
  path: string,
  staged: boolean,
  navigation: RuntimeNavigationTarget
): Promise<FileOpenRecord> {
  const result = await callFileOpen(ctx, 'files.openDiff', {
    worktree,
    relativePath: path,
    staged,
    navigation
  })
  return {
    path,
    mode: 'diff',
    staged,
    opened: result.result.opened,
    kind: result.result.kind,
    ...(result.result.opened ? {} : { skipped: true, reason: `${result.result.kind} file` })
  }
}

function formatOpenChangedResult(result: FileOpenChangedResult): string {
  if (result.totalChanged === 0) {
    return 'No changed files.'
  }
  const lines = [`Opened ${result.opened.length} changed file targets.`]
  if (result.skipped.length > 0) {
    lines.push(`Skipped ${result.skipped.length} changed file targets:`)
    for (const skipped of result.skipped) {
      lines.push(`- ${skipped.path}: ${skipped.reason ?? 'not opened'}`)
    }
  }
  return lines.join('\n')
}

// A declined single-file open must exit unsuccessfully even when the RPC succeeded.
function requireOpened(result: RuntimeFileOpenResult, target: string): void {
  if (!result.opened) {
    throw new RuntimeClientError(
      'file_not_opened',
      `Did not open ${target}: the Orca app declined this ${result.kind} file.`,
      { nextSteps: ['Update the Orca app, which opens every file type the File Explorer does.'] }
    )
  }
}

function formatFileOpen(result: RuntimeFileOpenResult): string {
  return `Opened ${result.relativePath}.`
}

function formatFileDiff(result: RuntimeFileOpenResult): string {
  return `Opened diff for ${result.relativePath}.`
}

export const FILE_HANDLERS: Record<string, CommandHandler> = {
  'file open': async (ctx) => {
    const path = getRequiredStringFlag(ctx.flags, 'path')
    const position = getFileOpenPosition(ctx.flags)
    const worktree = await getFileWorktreeSelector(ctx)
    const relativePath = await resolveFilePath(ctx, worktree, path)
    const result = await callFileOpen(ctx, 'files.open', {
      worktree,
      relativePath,
      navigation: getFileOpenNavigation(ctx.flags),
      ...position
    })
    requireOpened(result.result, relativePath)
    printResult(result, ctx.json, formatFileOpen)
  },
  'file diff': async (ctx) => {
    const path = getRequiredStringFlag(ctx.flags, 'path')
    const staged = ctx.flags.get('staged') === true
    const worktree = await getFileWorktreeSelector(ctx)
    const relativePath = await resolveFilePath(ctx, worktree, path)
    const result = await callFileOpen(ctx, 'files.openDiff', {
      worktree,
      relativePath,
      staged,
      navigation: getFileOpenNavigation(ctx.flags)
    })
    requireOpened(result.result, `diff for ${relativePath}`)
    printResult(result, ctx.json, formatFileDiff)
  },
  'file open-changed': async (ctx) => {
    const mode = getOpenChangedMode(ctx.flags)
    const worktree = await getFileWorktreeSelector(ctx)
    const status = await ctx.client.call<GitStatusResult>('git.status', { worktree })
    const opened: FileOpenRecord[] = []
    const skipped: FileOpenRecord[] = []
    const openedEditPaths = new Set<string>()
    // Apply focus to the first successful open only.
    let navigation = getFileOpenNavigation(ctx.flags)
    const openWithFocusOnce = async (
      open: () => Promise<FileOpenRecord>
    ): Promise<FileOpenRecord> => {
      const record = await open()
      if (record.opened) {
        navigation = 'caller'
      }
      return record
    }

    for (const entry of status.result.entries) {
      if (mode === 'edit' || mode === 'both') {
        const editSkipReason = canOpenEntryForEdit(entry)
        if (editSkipReason) {
          skipped.push({
            path: entry.path,
            mode: 'edit',
            opened: false,
            skipped: true,
            reason: editSkipReason
          })
        } else if (!openedEditPaths.has(entry.path)) {
          openedEditPaths.add(entry.path)
          const record = await openWithFocusOnce(() =>
            openFileEdit(ctx, worktree, entry.path, navigation)
          )
          const records = record.opened ? opened : skipped
          records.push(record)
        }
      }

      if (mode === 'diff' || mode === 'both') {
        const staged = entry.area === 'staged'
        if (entry.conflictStatus === 'unresolved') {
          skipped.push({
            path: entry.path,
            mode: 'diff',
            staged,
            opened: false,
            skipped: true,
            reason: 'unresolved conflict may not have a single diff target'
          })
        } else {
          const record = await openWithFocusOnce(() =>
            openFileDiff(ctx, worktree, entry.path, staged, navigation)
          )
          const records = record.opened ? opened : skipped
          records.push(record)
        }
      }
    }

    printResult(
      {
        ...status,
        result: {
          worktree,
          mode,
          opened,
          skipped,
          totalChanged: status.result.entries.length
        }
      },
      ctx.json,
      formatOpenChangedResult
    )
  }
}