Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

16.9 KB
Raw Blame
import type {
  GitBranchDiffPatches,
  GitFileRevertResult,
  GitRemoteBranchListItem,
  GitWorkingTreeFiles,
  GitWorkingTreePatches,
} from '@lobechat/electron-client-ipc';
import type {
  DeviceGitAddWorktreeResult,
  DeviceGitAheadBehind,
  DeviceGitBranchListItem,
  DeviceGitCheckoutResult,
  DeviceGitDeleteBranchResult,
  DeviceGitLinkedPullRequest,
  DeviceGitLinkedPullRequestLookupStatus,
  DeviceGitPullRequestAction,
  DeviceGitPullRequestActionResult,
  DeviceGitPullRequestActivity,
  DeviceGitPullRequestDetailResult,
  DeviceGitPullRequestMergeContext,
  DeviceGitRemoveWorktreeResult,
  DeviceGitRenameBranchResult,
  DeviceGitSyncResult,
  DeviceGitUpstreamRef,
  DeviceGitWorkingTreeStatus,
  DeviceGitWorktreeListItem,
} from '@lobechat/types';
import { DEVICE_GIT_OUTDATED } from '@lobechat/types';

import { lambdaClient } from '@/libs/trpc/client';
import { electronGitService } from '@/services/electron/git';

/**
 * The device answered without honouring a newer parameter. Device RPCs carry no
 * version negotiation, so an older `lh connect` / desktop build ignores
 * `startPoint` / `branch` and acts on HEAD — every caller that passes one checks
 * the echo and refuses to treat such an answer as success.
 */
export class DeviceGitOutdatedError extends Error {
  readonly reason = DEVICE_GIT_OUTDATED;
  constructor(what: string) {
    super(`The device did not honour ${what}; update the LobeHub app or lh CLI on it.`);
    this.name = 'DeviceGitOutdatedError';
  }
}

export const isDeviceGitOutdated = (value: unknown): boolean =>
  value instanceof DeviceGitOutdatedError ||
  (!!value &&
    typeof value === 'object' &&
    (value as { reason?: string }).reason === DEVICE_GIT_OUTDATED);

/**
 * Reject a successful result whose echo does not match what was asked for. A
 * failed result is passed through: git's own error is the better message.
 */
const verifyEcho = <T extends { error?: string; reason?: string; success: boolean }>(
  result: T,
  field: 'branch' | 'startPoint',
  requested: string | undefined,
): T => {
  if (requested === undefined || !result.success) return result;
  const echoed = (result as Record<string, unknown>)[field];
  if (echoed === requested) return result;
  return {
    ...result,
    error: new DeviceGitOutdatedError(`"${field}"`).message,
    reason: DEVICE_GIT_OUTDATED,
    success: false,
  };
};

/** Current branch + detached-HEAD state for a working directory (cheap read). */
export interface GitBranchSummary {
  branch?: string;
  detached?: boolean;
  upstream?: DeviceGitUpstreamRef;
}

/** Linked-PR summary for a branch — the result of the expensive `gh` leg. */
export interface GitLinkedPRSummary {
  extraCount?: number;
  ghMissing?: boolean;
  pullRequest?: DeviceGitLinkedPullRequest | null;
  pullRequestStatus?: DeviceGitLinkedPullRequestLookupStatus;
  /** `owner/repo` of the GitHub remote the branch publishes to. */
  remoteRepoFullName?: string;
  upstream?: DeviceGitUpstreamRef;
}

/**
 * Git operations chokepoint. Each call picks its own transport from `deviceId`:
 * a remote / web target (deviceId set) goes through the `device.*` TRPC RPCs;
 * the local desktop talks to Electron over IPC. UI / store / hooks only see this
 * service — the electron-vs-lambda decision never leaks up. Reads and writes are
 * symmetric: both transports expose the same granular git operations.
 */
class GitService {
  /**
   * Local branches of a working directory. A remote device that cannot answer
   * rejects; `[]` is a real answer (an unborn repo).
   */
  listGitBranches({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitBranchListItem[]> {
    return deviceId
      ? lambdaClient.device.listGitBranches.query({ deviceId, path })
      : electronGitService.listGitBranches(path);
  }

  /**
   * Checkout (or create) a branch in a working directory. With `startPoint`
   * (and `create`) the new branch is cut from that branch instead of HEAD; the
   * device's echo is verified, see {@link DeviceGitOutdatedError}.
   */
  async checkoutGitBranch({
    branch,
    create,
    deviceId,
    path,
    startPoint,
  }: {
    branch: string;
    create?: boolean;
    deviceId?: string;
    path: string;
    startPoint?: string;
  }): Promise<DeviceGitCheckoutResult> {
    const params = { branch, create, path, ...(startPoint ? { startPoint } : {}) };
    const result = deviceId
      ? await lambdaClient.device.checkoutGitBranch.mutate({ ...params, deviceId })
      : await electronGitService.checkoutGitBranch(params);
    return verifyEcho(result, 'startPoint', startPoint);
  }

  /** Rename a branch in a working directory. */
  renameGitBranch({
    deviceId,
    from,
    path,
    to,
  }: {
    deviceId?: string;
    from: string;
    path: string;
    to: string;
  }): Promise<DeviceGitRenameBranchResult> {
    return deviceId
      ? lambdaClient.device.renameGitBranch.mutate({ deviceId, from, path, to })
      : electronGitService.renameGitBranch({ from, path, to });
  }

  /** Delete a branch in a working directory. */
  deleteGitBranch({
    branch,
    deviceId,
    path,
  }: {
    branch: string;
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitDeleteBranchResult> {
    return deviceId
      ? lambdaClient.device.deleteGitBranch.mutate({ branch, deviceId, path })
      : electronGitService.deleteGitBranch({ branch, path });
  }

  /** Remove a worktree from a working directory's repository. */
  removeGitWorktree({
    deviceId,
    path,
    worktreePath,
  }: {
    deviceId?: string;
    path: string;
    worktreePath: string;
  }): Promise<DeviceGitRemoveWorktreeResult> {
    return deviceId
      ? lambdaClient.device.removeGitWorktree.mutate({ deviceId, path, worktreePath })
      : electronGitService.removeGitWorktree({ path, worktreePath });
  }

  /**
   * Add a linked worktree on a fresh branch to a working directory's repository.
   * A remote device derives the target path server-side from `path` + `branch`
   * (never trusting a client-supplied absolute path), so `worktreePath` is only
   * forwarded on the local IPC route where this machine owns the filesystem.
   */
  async addGitWorktree({
    branch,
    deviceId,
    ownerToken,
    path,
    sourcePath,
    startPoint,
    stripBranchPrefix,
    worktreePath,
  }: {
    branch: string;
    deviceId?: string;
    /** Creation receipt for a worktree the app makes for a conversation; echoed when recorded. */
    ownerToken?: string;
    path: string;
    /** The repo's main checkout; the server keys the target folder on it. */
    sourcePath?: string;
    /** Fork the new branch from this branch instead of HEAD; the echo is verified. */
    startPoint?: string;
    /**
     * Remote only: have the server drop the app's branch namespace from the
     * folder it derives. The local route already passes the final `worktreePath`.
     */
    stripBranchPrefix?: boolean;
    worktreePath: string;
  }): Promise<DeviceGitAddWorktreeResult> {
    const start = {
      ...(startPoint ? { startPoint } : {}),
      ...(ownerToken ? { ownerToken } : {}),
    };
    const result = deviceId
      ? await lambdaClient.device.addGitWorktree.mutate({
          branch,
          deviceId,
          path,
          sourcePath,
          ...start,
          ...(stripBranchPrefix ? { stripBranchPrefix } : {}),
        })
      : await electronGitService.addGitWorktree({ branch, path, worktreePath, ...start });
    return verifyEcho(result, 'startPoint', startPoint);
  }

  /**
   * Fast-forward the current branch of a working directory, or `branch` without
   * switching to it (the device's echo is verified).
   */
  async pullGitBranch({
    branch,
    deviceId,
    path,
  }: {
    branch?: string;
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitSyncResult> {
    const params = { path, ...(branch ? { branch } : {}) };
    const result = deviceId
      ? await lambdaClient.device.pullGitBranch.mutate({ ...params, deviceId })
      : await electronGitService.pullGitBranch(params);
    return verifyEcho(result, 'branch', branch);
  }

  /** Push the current branch of a working directory, or `branch` (echo verified). */
  async pushGitBranch({
    branch,
    deviceId,
    path,
  }: {
    branch?: string;
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitSyncResult> {
    const params = { path, ...(branch ? { branch } : {}) };
    const result = deviceId
      ? await lambdaClient.device.pushGitBranch.mutate({ ...params, deviceId })
      : await electronGitService.pushGitBranch(params);
    return verifyEcho(result, 'branch', branch);
  }

  /**
   * Current branch + detached-HEAD state. A cheap local git read, deliberately
   * split from the linked-PR lookup so the branch label can revalidate promptly
   * on a working-directory switch without re-triggering the expensive `gh` call.
   * Dispatches per `deviceId` like every other leg.
   */
  async getGitBranch({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<GitBranchSummary> {
    const info = deviceId
      ? await lambdaClient.device.gitBranch.query({ deviceId, path })
      : await electronGitService.getGitBranch(path);
    return { branch: info?.branch, detached: info?.detached, upstream: info?.upstream };
  }

  /**
   * PR linked to `branch` on a GitHub repo. Shells out to `gh` (8s timeout), so
   * callers throttle this far more aggressively than the branch read. Includes
   * merged/closed PRs so persisted snapshots can refresh after GitHub changes
   * outside the app.
   *
   * `branch` is the LOCAL branch; the device resolves the remote ref it publishes
   * to and queries GitHub under that, falling back to a commit→PR lookup. It
   * reports the ref it landed on as `upstream` — persist that, not the local name.
   */
  async getLinkedPullRequest({
    branch,
    deviceId,
    path,
    pullRequestNumber,
    state,
  }: {
    branch: string;
    deviceId?: string;
    path: string;
    pullRequestNumber?: number;
    /** `open`: discovery of a branch's open PR; default lists every state. */
    state?: 'all' | 'open';
  }): Promise<GitLinkedPRSummary | undefined> {
    const pr = deviceId
      ? await lambdaClient.device.gitLinkedPullRequest.query({
          branch,
          deviceId,
          path,
          pullRequestNumber,
          ...(state ? { state } : {}),
        })
      : await electronGitService.getLinkedPullRequest({
          branch,
          path,
          pullRequestNumber,
          ...(state ? { state } : {}),
        });
    if (!pr) return undefined;
    return {
      extraCount: pr.extraCount,
      ghMissing: pr.status === 'gh-missing',
      pullRequest: pr.pullRequest,
      pullRequestStatus: pr.status,
      remoteRepoFullName: pr.remoteRepoFullName,
      upstream: pr.upstream,
    };
  }

  /** Full detail of a pull request in a working directory. */
  async getPullRequestDetail({
    coreOnly,
    deviceId,
    number,
    path,
  }: {
    coreOnly?: boolean;
    deviceId?: string;
    number: number;
    path: string;
  }): Promise<DeviceGitPullRequestDetailResult> {
    return deviceId
      ? ((await lambdaClient.device.gitPullRequestDetail.query({
          coreOnly,
          deviceId,
          number,
          path,
        })) ?? {
          detail: null,
          status: 'error',
        })
      : electronGitService.getPullRequestDetail({ coreOnly, number, path });
  }

  async getPullRequestActivity(params: {
    deviceId?: string;
    number: number;
    path: string;
  }): Promise<DeviceGitPullRequestActivity> {
    if (!params.deviceId) return electronGitService.getPullRequestActivity(params);
    const result = await lambdaClient.device.gitPullRequestActivity.query({
      ...params,
      deviceId: params.deviceId,
    });
    if (!result) throw new Error('Unable to load pull request activity');
    return result;
  }

  /** Branch protection, viewer permission and base drift for a pull request. */
  async getPullRequestMergeContext({
    deviceId,
    ...params
  }: {
    baseRefName: string;
    deviceId?: string;
    headRefOid: string;
    number: number;
    path: string;
    repo: { name: string; owner: string };
  }): Promise<DeviceGitPullRequestMergeContext | null> {
    return deviceId
      ? ((await lambdaClient.device.gitPullRequestMergeContext.query({ deviceId, ...params })) ??
          null)
      : electronGitService.getPullRequestMergeContext(params);
  }

  /** Run a `gh pr` mutation (merge, auto-merge, ready, comment, close, ...) on a pull request. */
  async runPullRequestAction({
    action,
    deviceId,
    number,
    path,
    repository,
  }: {
    action: DeviceGitPullRequestAction;
    deviceId?: string;
    number: number;
    path: string;
    repository?: { path: string; url: string };
  }): Promise<DeviceGitPullRequestActionResult> {
    if (deviceId) {
      return lambdaClient.device.runGitPullRequestAction.mutate({
        action,
        deviceId,
        number,
        path,
        repository,
      });
    }

    const target = action.type === 'merge' && action.deleteBranch ? undefined : repository;
    return electronGitService.runPullRequestAction({
      action,
      number,
      path: target?.path ?? path,
      url: target?.url,
    });
  }

  /** Working-tree dirty-file counts for a working directory. */
  async getGitWorkingTreeStatus({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitWorkingTreeStatus | undefined> {
    return deviceId
      ? ((await lambdaClient.device.gitWorkingTreeStatus.query({ deviceId, path })) ?? undefined)
      : electronGitService.getGitWorkingTreeStatus(path);
  }

  /**
   * Ahead/behind commit counts for the current branch vs its upstream — or for
   * `branch`, wherever HEAD is. A named-branch answer without the matching echo
   * came from a device that counted HEAD instead and throws
   * {@link DeviceGitOutdatedError}; an unreachable device still resolves
   * `undefined`.
   */
  async getGitAheadBehind({
    branch,
    deviceId,
    path,
  }: {
    branch?: string;
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitAheadBehind | undefined> {
    const result = deviceId
      ? ((await lambdaClient.device.gitAheadBehind.query({
          ...(branch ? { branch } : {}),
          deviceId,
          path,
        })) ?? undefined)
      : await electronGitService.getGitAheadBehind(path, branch);
    if (branch !== undefined && result && result.branch !== branch)
      throw new DeviceGitOutdatedError('"branch"');
    return result;
  }

  /** Working-tree (unstaged) per-file patches for a working directory. */
  async getGitWorkingTreePatches({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<GitWorkingTreePatches | undefined> {
    return deviceId
      ? ((await lambdaClient.device.getGitWorkingTreePatches.query({ deviceId, path })) ??
          undefined)
      : electronGitService.getGitWorkingTreePatches(path);
  }

  /** Repo-relative paths of dirty working-tree files (the Files tab git overlay). */
  async getGitWorkingTreeFiles({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<GitWorkingTreeFiles | undefined> {
    return deviceId
      ? ((await lambdaClient.device.getGitWorkingTreeFiles.query({ deviceId, path })) ?? undefined)
      : electronGitService.getGitWorkingTreeFiles(path);
  }

  /** Branch diff (current branch vs base ref) per-file patches for a working directory. */
  async getGitBranchDiff({
    baseRef,
    deviceId,
    path,
  }: {
    baseRef?: string;
    deviceId?: string;
    path: string;
  }): Promise<GitBranchDiffPatches | undefined> {
    return deviceId
      ? ((await lambdaClient.device.getGitBranchDiff.query({ baseRef, deviceId, path })) ??
          undefined)
      : electronGitService.getGitBranchDiff({ baseRef, path });
  }

  /**
   * Remote branches (`refs/remotes/origin/*`) of a working directory. A remote
   * device that cannot answer rejects; `[]` is a real answer (no `origin`).
   */
  listGitRemoteBranches({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<GitRemoteBranchListItem[]> {
    return deviceId
      ? lambdaClient.device.listGitRemoteBranches.query({ deviceId, path })
      : electronGitService.listGitRemoteBranches(path);
  }

  /** Git worktrees attached to the same repository as a working directory. */
  listGitWorktrees({
    deviceId,
    path,
  }: {
    deviceId?: string;
    path: string;
  }): Promise<DeviceGitWorktreeListItem[]> {
    return deviceId
      ? lambdaClient.device.listGitWorktrees.query({ deviceId, path })
      : electronGitService.listGitWorktrees(path);
  }

  /** Revert (discard working-tree changes to) a single file in a working directory. */
  revertGitFile({
    deviceId,
    filePath,
    path,
  }: {
    deviceId?: string;
    filePath: string;
    path: string;
  }): Promise<GitFileRevertResult> {
    return deviceId
      ? lambdaClient.device.revertGitFile.mutate({ deviceId, filePath, path })
      : electronGitService.revertGitFile({ filePath, path });
  }
}

export const gitService = new GitService();