Skip to content

The agent that grows with you

10.7 KB
Raw Blame
import { hermesApi, sessionFileOwnerScope } from '@/api/client'
import type {
  HermesConnection,
  HermesReadDirResult,
  HermesReadFileErrorResult,
  HermesReadFileTextResult,
  HermesSelectPathsOptions
} from '@/global'
import { translateNow } from '@/i18n'
import { hostHas } from '@/lib/host-capabilities'
import { $connection } from '@/store/session'

export interface DesktopFsRemotePicker {
  selectPaths: (options?: HermesSelectPathsOptions) => Promise<string[]>
}

let remotePicker: DesktopFsRemotePicker | null = null

export function setDesktopFsRemotePicker(next: DesktopFsRemotePicker | null) {
  remotePicker = next
}

function connectionCacheKey(connection: HermesConnection | null) {
  if (!connection) {
    return 'local:'
  }

  // A profile belongs to a registry connection, not the whole Desktop. The
  // registry id is the isolation boundary, including for SSH connections; the
  // stable host identity below is only the fallback for legacy connections.
  if (connection.connectionId) {
    return `connection:${connection.connectionId}:${connection.profile || ''}`
  }

  const target =
    connection.remoteKind === 'ssh'
      ? connection.remoteIdentity || connection.remoteHost || ''
      : connection.baseUrl || ''

  return `${connection.mode || 'local'}:${connection.remoteKind || ''}:${connection.profile || ''}:${target}`
}

export function desktopFsCacheKey(connection: HermesConnection | null = $connection.get()) {
  return connectionCacheKey(connection)
}

export function isDesktopFsRemoteMode() {
  return $connection.get()?.mode === 'remote' || !hostHas('nativeHostFiles')
}

// Active profile for FS/git REST calls. Without it the Electron api bridge
// hits the primary (local) backend even when the user switched to a remote profile.
export function desktopFsProfile(): string | undefined {
  return $connection.get()?.profile || undefined
}

/** The chat a gateway file belongs to. A Docker agent's `/workspace` is that session's own
 *  sandbox, so a gateway read names it; a local (native) read has no use for it. */
export interface DesktopFsSessionScope {
  sessionId?: null | string
}

interface FsRoute {
  owner: { connectionId?: string; profile?: string }
  sessionId?: string
}

/** Where a gateway file request goes. A session id travels only with the profile (and
 *  connection) that owns it: a Bot or pooled chat's owner can differ from the window's. With
 *  no known owner the request names no session and goes to the window's profile. */
function fsRoute(scope?: DesktopFsSessionScope): FsRoute {
  const sessionId = scope?.sessionId || undefined
  const owner = sessionId ? sessionFileOwnerScope(sessionId) : null

  return owner ? { owner, sessionId } : { owner: { profile: desktopFsProfile() } }
}

function fsPath(endpoint: string, filePath: string, sessionId?: string) {
  const session = sessionId ? `&session_id=${encodeURIComponent(sessionId)}` : ''

  return `/api/fs/${endpoint}?path=${encodeURIComponent(filePath)}${session}`
}

function bridge() {
  const desktop = window.hermesDesktop

  if (!desktop) {
    throw new Error('Hermes Desktop bridge is unavailable')
  }

  return desktop
}

function remoteFsApi<T>(path: string, body?: Record<string, unknown>, owner = fsRoute().owner): Promise<T> {
  return hermesApi<T>(body ? { ...owner, body, method: 'POST', path } : { ...owner, path })
}

/** True when a bridge read returned the main process's structured "file is not
 *  on disk" answer (the main process returns this instead of rejecting, so a
 *  restored preview tab or transcript reference to a deleted/moved file does
 *  not spam Electron's console with a stack trace per probe). Callers that
 *  already try/catch their read get the same behavior as a rejection: throw
 *  with the original message. */
export function isReadFileErrorResult(value: unknown): value is HermesReadFileErrorResult {
  return !!value && typeof value === 'object' && (value as { ok?: unknown }).ok === false
}

function throwForReadErrorResult(result: HermesReadFileErrorResult): never {
  throw new DesktopFileMissingError(result)
}

/** Thrown by the facade when the main process answered that the file is simply
 *  not on disk (the structured `{ ok:false }` result). Callers that need to
 *  tell expected absence apart from real failures check `instanceof`; everyone
 *  else sees an ordinary error whose message matches the old rejection. */
export class DesktopFileMissingError extends Error {
  readonly code: string

  constructor(result: HermesReadFileErrorResult) {
    super(result.message || `File read failed: ${result.error}`)
    this.name = 'DesktopFileMissingError'
    this.code = result.error
  }
}

export async function readDesktopDir(path: string): Promise<HermesReadDirResult> {
  if (!isDesktopFsRemoteMode()) {
    return bridge().readDir(path)
  }

  return remoteFsApi<HermesReadDirResult>(fsPath('list', path))
}

export async function readDesktopFileText(
  path: string,
  scope?: DesktopFsSessionScope
): Promise<HermesReadFileTextResult> {
  if (!isDesktopFsRemoteMode()) {
    const result = await bridge().readFileText(path)

    if (isReadFileErrorResult(result)) {
      throwForReadErrorResult(result)
    }

    return result
  }

  const route = fsRoute(scope)

  return remoteFsApi<HermesReadFileTextResult>(fsPath('read-text', path, route.sessionId), undefined, route.owner)
}

// Save UTF-8 text back to a file. Local writes go through the hardened Electron
// IPC; remote writes hit the dashboard's POST /api/fs/write-text (same path
// hardening, parent-must-exist, size cap) so the editor behaves identically in
// both modes. Stale-on-disk detection is the caller's job (re-read before save).
// A gateway save names the session the file was read for, so it lands where that read did.
export async function writeDesktopFileText(
  path: string,
  content: string,
  scope?: DesktopFsSessionScope
): Promise<{ path: string }> {
  const desktop = bridge()

  if (!isDesktopFsRemoteMode()) {
    if (!desktop.writeTextFile) {
      throw new Error('Saving is not available')
    }

    return desktop.writeTextFile(path, content)
  }

  const route = fsRoute(scope)

  const result = await remoteFsApi<{ ok?: boolean; path?: string }>(
    '/api/fs/write-text',
    { content, path, ...(route.sessionId ? { session_id: route.sessionId } : {}) },
    route.owner
  )

  return { path: result.path || path }
}

// Create a folder on the connected backend (POST /api/files/mkdir). Remote-only:
// in local mode the picker is the native dialog, which creates folders itself.
export async function createRemoteDir(path: string): Promise<string> {
  const result = await remoteFsApi<{ path?: string }>('/api/files/mkdir', { path })

  return result.path || path
}

export async function readDesktopFileDataUrl(path: string, scope?: DesktopFsSessionScope): Promise<string> {
  if (!isDesktopFsRemoteMode()) {
    const result = await bridge().readFileDataUrl(path)

    if (isReadFileErrorResult(result)) {
      throwForReadErrorResult(result)
    }

    return result
  }

  const route = fsRoute(scope)

  const result = await remoteFsApi<string | { dataUrl?: string }>(
    fsPath('read-data-url', path, route.sessionId),
    undefined,
    route.owner
  )

  return typeof result === 'string' ? result : result.dataUrl || ''
}

/**
 * Read a composer image local-shell first, even when the active agent is
 * remote. Picker, clipboard, and OS-drop paths belong to this machine; in-app
 * project-tree paths may belong only to the gateway and fall back there.
 */
export async function readDesktopFileDataUrlLocalFirst(path: string): Promise<string> {
  try {
    const local = await window.hermesDesktop?.readFileDataUrl?.(path)

    if (local && !isReadFileErrorResult(local)) {
      return local
    }

    // A structured missing-file result from local is the same outcome as a
    // rejection: fall through to the remote fallback below (or throw in local
    // mode via readDesktopFileDataUrl's own guard).
  } catch (error) {
    if (!isDesktopFsRemoteMode()) {
      throw error
    }

    // Not on this machine (or unreadable locally) — try the active gateway.
  }

  return readDesktopFileDataUrl(path)
}

export async function desktopGitRoot(path: string): Promise<string | null> {
  const desktop = bridge()

  if (!isDesktopFsRemoteMode()) {
    return desktop.gitRoot ? desktop.gitRoot(path) : null
  }

  return (await remoteFsApi<{ root: string | null }>(fsPath('git-root', path))).root
}

export async function desktopDefaultCwd(): Promise<{ branch: string; cwd: string } | null> {
  if (!isDesktopFsRemoteMode()) {
    return null
  }

  return remoteFsApi<{ branch: string; cwd: string }>('/api/fs/default-cwd')
}

// Reveal a path in the OS file manager (Finder / Explorer / Files). Local only.
// The bridge answers `false` when the path is not on this computer (a remote
// backend's workspace) — surface it instead of a silent no-op.
export async function revealDesktopPath(path: string): Promise<void> {
  const revealed = await bridge().revealPath?.(path)

  if (revealed === false) {
    throw new Error(translateNow('fileMenu.revealMissing'))
  }
}

// Rename a file/folder in place; returns the new absolute path. Local only.
export async function renameDesktopPath(path: string, newName: string): Promise<string> {
  const desktop = bridge()

  if (!desktop.renamePath) {
    throw new Error('Rename is not available')
  }

  const result = await desktop.renamePath(path, newName)

  return result.path
}

// Move a file/folder to the OS trash (recoverable). Local only.
export async function trashDesktopPath(path: string): Promise<void> {
  const desktop = bridge()

  if (!desktop.trashPath) {
    throw new Error('Delete is not available')
  }

  await desktop.trashPath(path)
}

export async function copyTextToClipboard(text: string): Promise<void> {
  await bridge().writeClipboard(text)
}

// Working-tree-vs-HEAD diff for one file. Empty when unchanged / not a repo.
// Remote gateway → backend git (/api/git/file-diff); local → Electron git.
export async function desktopFileDiff(repoRoot: string, filePath: string): Promise<string> {
  if (isDesktopFsRemoteMode()) {
    const result = await remoteFsApi<{ diff: string }>(
      `/api/git/file-diff?path=${encodeURIComponent(repoRoot)}&file=${encodeURIComponent(filePath)}`
    )

    return result.diff || ''
  }

  const git = bridge().git

  return git?.fileDiff ? git.fileDiff(repoRoot, filePath) : ''
}

export async function selectDesktopPaths(options?: HermesSelectPathsOptions): Promise<string[]> {
  const desktop = bridge()
  const profile = desktopFsProfile()
  const localOptions = profile ? { ...options, profile } : options

  if (!isDesktopFsRemoteMode()) {
    return desktop.selectPaths(localOptions)
  }

  if (!options?.directories) {
    return desktop.selectPaths(localOptions)
  }

  return remotePicker ? remotePicker.selectPaths({ ...options, multiple: false }) : []
}