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.

20.7 KB
Raw Blame
import type { WorkingDirGitState } from '@lobechat/types';
import { Icon, toast, Tooltip } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
import { ArrowDownIcon, ArrowUpIcon, TriangleAlertIcon } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';

import RingLoadingIcon from '@/components/RingLoading';
import { gitService, isDeviceGitOutdated } from '@/services/git';
import {
  deviceSelectors,
  useDeviceStore,
  useFetchGitAheadBehind,
  useFetchGitBranch,
  useFetchGitDiffStats,
  useFetchGitWorktrees,
  useReviewPatches,
} from '@/store/device';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';

import BranchSwitcher from './BranchSwitcher';
import { describeGitFailure } from './DraftGit/gitErrors';
import { useDraftBranch } from './DraftGit/useDraftBranch';
import { WorktreeToggle } from './DraftGit/WorktreeToggle';
import { gitChipStyles } from './gitChipStyles';
import StaleGitSnapshot from './StaleGitSnapshot';
import TopicPullRequestChip from './TopicPullRequestChip';

const styles = stylex.create({
  aheadBehindStat: {
    display: 'inline-flex',
    gap: '0',
    alignItems: 'center',
    marginInlineStart: '-2px',
    fontVariantNumeric: 'tabular-nums',
    lineHeight: 1,
  },
  aheadStat: { color: cssVar.colorInfo },
  behindStat: { color: cssVar.colorError },
  branchGroup: { display: 'flex', flex: 'none', gap: '2px', alignItems: 'center' },
  branchLabel: {
    overflow: 'hidden',
    maxWidth: '160px',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  },
  // An existing topic's branch: a label, not a control.
  branchStatic: {
    cursor: 'default',
    backgroundColor: { 'default': null, ':hover': 'transparent' },
    backgroundImage: { 'default': null, ':hover': 'none' },
  },
  outdatedStat: { cursor: 'default', color: cssVar.colorWarning },
  diffStat: {
    display: 'inline-flex',
    flexShrink: 0,
    gap: '4px',
    alignItems: 'center',
    fontVariantNumeric: 'tabular-nums',
  },
  diffStatAdded: { color: cssVar.colorSuccess },
  diffStatDeleted: { color: cssVar.colorError },
  diffStatModified: { color: cssVar.colorWarning },
  syncTrigger: {
    cursor: 'pointer',
    display: 'inline-flex',
    flex: 'none',
    gap: '2px',
    alignItems: 'center',
    paddingBlock: '2px',
    paddingInline: '4px',
    borderRadius: '4px',
    fontSize: '12px',
    fontVariantNumeric: 'tabular-nums',
    lineHeight: 1,
    transition: 'background 0.2s',
    backgroundColor: { 'default': null, ':hover': cssVar.colorFillTertiary },
    backgroundImage: { 'default': null, ':hover': 'none' },
  },
  syncTriggerDisabled: {
    cursor: 'progress',
    opacity: 0.6,
    backgroundColor: { 'default': null, ':hover': 'transparent' },
    backgroundImage: { 'default': null, ':hover': 'none' },
  },
});

interface GitStatusProps {
  /** When set, git status / branch switch / pull / push all run against this
   * remote device via RPC. Omit for the local machine (talks over IPC). */
  agentId: string;
  deviceId?: string;
  /**
   * Git context persisted on the topic. Stands in for the live probe in two
   * cases: while the probe is still pending (no cached branch yet), it paints a
   * read-only branch chip so the cluster doesn't pop in once the read lands;
   * and when the probe finds no branch at `path` — which happens whenever the
   * recorded worktree directory has since been deleted — it keeps the branch /
   * worktree chips visible (read-only) instead of collapsing the whole
   * cluster, so the bar agrees with the topic's meta hover card, which reads
   * this same snapshot and never probes.
   */
  fallbackGit?: WorkingDirGitState;
  isGithub: boolean;
  path: string;
  sourcePath?: string;
  /** The conversation the switch is recorded on; omitted, the global active topic. */
  topicId?: string | null;
}

const GitStatus = memo<GitStatusProps>(
  ({ agentId, path, sourcePath, isGithub, deviceId, fallbackGit, topicId }) => {
    const { t } = useTranslation('device');
    // Transport (Electron IPC vs device RPC) is decided inside the service; the
    // component just reads, identically for local and remote.
    const {
      data: branchData,
      error: branchError,
      isConfirmed: branchConfirmed,
      mutate: mutateBranch,
    } = useFetchGitBranch(deviceId, path);
    const branch = branchData?.branch;
    const detached = branchData?.detached;
    // The persisted snapshot only stands in once the current probe has actually
    // ANSWERED. A hydrated row (`data !== undefined`) is a paint-only stand-in,
    // not an answer: treating it as settled would classify a dead directory
    // from the last session before this session's read returns.
    // `getGitBranch` resolves to `{}` for a path it can't read, so a settled
    // probe is a confirmed read (or an errored one) — keying off `!branch` alone
    // would flash the snapshot cluster on every mount while loading.
    const probeSettled = branchConfirmed || !!branchError;
    // …and only when the probe could reach the directory at all. A remote read
    // whose device is offline (or whose RPC failed) comes back `undefined`, which
    // the service normalizes into the SAME empty shape a deleted path produces —
    // so an unreachable device would otherwise be reported as a missing directory,
    // offering to drop a worktree override that is perfectly alive. A local read
    // talks to this filesystem directly and has no such ambiguity.
    const deviceOnline = useDeviceStore(
      (s) => !!deviceSelectors.getDeviceById(deviceId)(s)?.online,
    );
    const probeReachedDirectory = !deviceId || deviceOnline;
    // Only a CONFIRMED empty probe may declare the directory gone. A hydrated
    // empty row (`{}`) means the last session couldn't read it, not that it is
    // gone now.
    const probeFoundNothing = !branch && branchConfirmed && probeReachedDirectory;
    // Worktrees picked from the bar were persisted without a branch, so the
    // recorded worktree is all such a snapshot has. An empty probe alone can't
    // condemn it: a remote read that fails in transit on a device still marked
    // online comes back just as empty. Ask the source repo instead — the worktree
    // is gone only when the source answers (a real listing always includes the
    // source itself; a failed RPC is `[]`) and no longer lists it as live.
    const recordedWorktree =
      !fallbackGit?.branch && sourcePath && sourcePath !== path
        ? fallbackGit?.activeWorktree
        : undefined;
    const { data: sourceWorktrees, isConfirmed: sourceWorktreesConfirmed } = useFetchGitWorktrees(
      deviceId,
      probeFoundNothing && recordedWorktree ? sourcePath : undefined,
    );
    // Only this session's answer may condemn the recorded worktree; a hydrated
    // listing from the previous session is a paint-only stand-in.
    const recordedWorktreeGone =
      sourceWorktreesConfirmed &&
      !!sourceWorktrees?.length &&
      !sourceWorktrees.some((worktree) => worktree.path === path && !worktree.prunable);
    const isStale =
      probeFoundNothing && (!!fallbackGit?.branch || (!!recordedWorktree && recordedWorktreeGone));
    // Before a topic's first send the branch is only picked (the send switches
    // or forks a worktree); an existing topic's branch is shown but not
    // switched from here.
    const isDraft = !topicId;
    const draft = useDraftBranch({
      agentId,
      currentBranch: detached ? undefined : branch,
      deviceId,
      enabled: isDraft && !isStale,
      isGithub,
      path,
      sourcePath: sourcePath ?? path,
    });
    // The picked branch when it is not HEAD's: counts, pull and push follow it.
    // When it is HEAD's they read HEAD.
    const syncBranch =
      isDraft && draft.selectedBranch && draft.selectedBranch !== branch
        ? draft.selectedBranch
        : undefined;
    // The remaining reads are all disabled once the directory is gone: nothing
    // below renders from them in that state, and the diff poll alone would keep
    // shelling out to git every 10s — one RPC round-trip per tick on a remote
    // device — against a path we already know cannot be read.
    const { data: reviewPatches, mutate: mutateReviewPatches } = useReviewPatches(
      path,
      'unstaged',
      undefined,
      deviceId,
      !isStale,
    );
    // The `+N −M` chip is derived from the review patches (a separate read), so
    // persist only its compact counts. That lets a reload paint the previous
    // session's chip instead of growing the cluster after the diff arrives.
    const { data: cachedDiffStats, set: setDiffStats } = useFetchGitDiffStats(deviceId, path);
    const livePath = isStale ? undefined : path;
    const {
      data: aheadBehind,
      error: aheadBehindError,
      isConfirmed: aheadBehindConfirmed,
      mutate: mutateAheadBehind,
    } = useFetchGitAheadBehind(deviceId, livePath, syncBranch);
    const deviceOutdated = !!syncBranch && isDeviceGitOutdated(aheadBehindError);
    const {
      data: worktrees = [],
      isConfirmed: worktreesConfirmed,
      mutate: mutateWorktrees,
    } = useFetchGitWorktrees(deviceId, livePath);
    const [switcherOpen, setSwitcherOpen] = useState(false);
    const [pulling, setPulling] = useState(false);
    const [pushing, setPushing] = useState(false);
    const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
    const openWorkingSidebar = useGlobalStore((s) => s.openWorkingSidebar);
    const showRightPanel = useGlobalStore(systemStatusSelectors.showRightPanel);
    const workingSidebarTab = useGlobalStore((s) => s.status.workingSidebarTab);

    const handleToggleReview = useCallback(() => {
      if (showRightPanel && workingSidebarTab === 'review') {
        toggleRightPanel(false);
        return;
      }
      openWorkingSidebar('review');
    }, [openWorkingSidebar, showRightPanel, workingSidebarTab, toggleRightPanel]);

    const refreshAfterSync = useCallback(async () => {
      await Promise.all([
        mutateBranch(),
        mutateReviewPatches(),
        mutateAheadBehind(),
        mutateWorktrees(),
      ]);
    }, [mutateBranch, mutateReviewPatches, mutateAheadBehind, mutateWorktrees]);

    const syncBusy = pulling || pushing;
    // Stale-first paints the last branch and its counts immediately, but
    // checkout / pull / push assume both still describe the live branch. When
    // the repo was switched externally, the faster branch probe can confirm the
    // NEW branch while the ahead/behind snapshot still belongs to the OLD one —
    // acting then would pull/push the actual branch while the label and counts
    // describe another. Keep them inert until BOTH reads answer; the chips stay
    // visible either way.
    const actionsBlocked = syncBusy || !branchConfirmed || !aheadBehindConfirmed;
    // Both pickers consume the worktree list (the branch picker routes to the
    // worktree that already holds the branch), so it must be this session's
    // listing too — a stale one can point at a removed worktree.
    const pickersReady = branchConfirmed && worktreesConfirmed;

    const handlePull = useCallback(async () => {
      if (pulling || pushing) return;
      setPulling(true);
      try {
        const result = await gitService.pullGitBranch({
          deviceId,
          path,
          ...(syncBranch ? { branch: syncBranch } : {}),
        });
        if (result.success) {
          if (result.noop) {
            toast.info(t('workingDirectory.pullNoop'));
          } else {
            toast.success(t('workingDirectory.pullSuccess'));
          }
          await refreshAfterSync();
        } else {
          toast.error(describeGitFailure(result, t, t('workingDirectory.pullFailed')));
        }
      } finally {
        setPulling(false);
      }
    }, [deviceId, path, pulling, pushing, refreshAfterSync, syncBranch, t]);

    const handlePush = useCallback(async () => {
      if (pulling || pushing) return;
      setPushing(true);
      try {
        const result = await gitService.pushGitBranch({
          deviceId,
          path,
          ...(syncBranch ? { branch: syncBranch } : {}),
        });
        if (result.success) {
          if (result.noop) {
            toast.info(t('workingDirectory.pushNoop'));
          } else {
            toast.success(t('workingDirectory.pushSuccess'));
          }
          await refreshAfterSync();
        } else {
          toast.error(describeGitFailure(result, t, t('workingDirectory.pushFailed')));
        }
      } finally {
        setPushing(false);
      }
    }, [deviceId, path, pulling, pushing, refreshAfterSync, syncBranch, t]);

    const liveDiffStats = useMemo(() => {
      const patches = [
        ...(reviewPatches?.patches ?? []),
        ...(reviewPatches?.submodules ?? []).flatMap((submodule) => submodule.patches),
      ];
      return patches.reduce(
        (acc, patch) => {
          acc.additions += patch.additions ?? 0;
          acc.deletions += patch.deletions ?? 0;
          acc.files += 1;
          return acc;
        },
        { additions: 0, deletions: 0, files: 0 },
      );
    }, [reviewPatches?.patches, reviewPatches?.submodules]);
    // Persist the confirmed counts; an empty answer (no patches) also replaces
    // the stale chip.
    useEffect(() => {
      if (reviewPatches !== undefined) setDiffStats(liveDiffStats);
    }, [reviewPatches, liveDiffStats, setDiffStats]);
    const diffStats =
      reviewPatches !== undefined ? liveDiffStats : (cachedDiffStats ?? liveDiffStats);
    const hasChanges = diffStats.files > 0;

    // The topic's linked PRs are server records, so they stay in the bar (with
    // their last known state) even when the working directory cannot be read —
    // an offline device, a deleted worktree.
    const topicPullRequestChip = topicId ? (
      <TopicPullRequestChip deviceId={deviceId} path={path} topicId={topicId} />
    ) : null;

    // Dead directory: the whole live cluster is unreachable, so hand off to the
    // snapshot renderer — it shows what the topic recorded and offers the one
    // action that can still work (drop the worktree override).
    if (isStale) {
      return (
        <>
          <StaleGitSnapshot
            agentId={agentId}
            git={fallbackGit!}
            isGithub={isGithub}
            path={path}
            sourcePath={sourcePath}
            topicId={topicId}
          />
          {topicPullRequestChip}
        </>
      );
    }

    if (!branch) {
      // Probe still pending: paint the topic's recorded branch read-only
      // (not the dead-directory snapshot — nothing is known to be gone yet).
      if (!probeSettled && fallbackGit?.branch) {
        return (
          <>
            <div {...stylex.props(gitChipStyles.separator)} />
            <div aria-busy {...stylex.props(styles.branchGroup)}>
              <div {...stylex.props(gitChipStyles.trigger)}>
                <span {...stylex.props(styles.branchLabel)}>{fallbackGit.branch}</span>
              </div>
            </div>
            {topicPullRequestChip}
          </>
        );
      }
      return topicPullRequestChip;
    }

    const branchTooltip = detached ? t('workingDirectory.detachedHead', { sha: branch }) : branch;

    const diffStatTooltip = hasChanges
      ? t('workingDirectory.diffLineStatTooltip', {
          added: diffStats.additions,
          deleted: diffStats.deletions,
          files: diffStats.files,
        })
      : undefined;

    const showAhead = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.ahead > 0;
    const showBehind = !!aheadBehind && aheadBehind.hasUpstream && aheadBehind.behind > 0;
    const upstreamName = aheadBehind?.upstream ?? '';
    const pushTargetName = aheadBehind?.pushTarget ?? '';
    const pushTargetExists = !!aheadBehind?.pushTargetExists;

    const branchTrigger = (
      <div {...stylex.props(gitChipStyles.trigger, !isDraft && styles.branchStatic)}>
        <span {...stylex.props(styles.branchLabel)}>
          {(isDraft && draft.selectedBranch) || branch}
        </span>
      </div>
    );

    // No worktree menu: a new topic forks its worktree on send instead (the
    // toggle below), and an existing one keeps its own.
    const branchNode = !isDraft ? (
      // An existing topic stays on its branch; start a new topic to move.
      <Tooltip title={branchTooltip}>{branchTrigger}</Tooltip>
    ) : !pickersReady ? (
      // Hydrated from the last session: hold the checkout entry until this
      // session's branch AND worktree probes answer, so the switcher's "current"
      // branch and its worktree routing are not stale guesses.
      <Tooltip title={t('workingDirectory.branchConfirming')}>{branchTrigger}</Tooltip>
    ) : (
      // Local switches over IPC; a remote device switches over RPC (deviceId set).
      <BranchSwitcher
        agentId={agentId}
        currentBranch={branch}
        deviceId={deviceId}
        isGithub={isGithub}
        open={switcherOpen}
        path={path}
        selection={{ branch: draft.selectedBranch, onSelect: draft.select }}
        sourcePath={sourcePath ?? path}
        topicId={topicId}
        worktrees={worktrees}
        onExternalRefresh={refreshAfterSync}
        onOpenChange={setSwitcherOpen}
      >
        <Tooltip title={draft.selectedBranch || branchTooltip}>{branchTrigger}</Tooltip>
      </BranchSwitcher>
    );

    const pullTooltip = pulling
      ? t('workingDirectory.pullInProgress')
      : t('workingDirectory.pullAction', {
          count: aheadBehind?.behind ?? 0,
          upstream: upstreamName,
        });

    const pushTooltip = pushing
      ? t('workingDirectory.pushInProgress')
      : t(pushTargetExists ? 'workingDirectory.pushAction' : 'workingDirectory.pushActionNew', {
          count: aheadBehind?.ahead ?? 0,
          target: pushTargetName || upstreamName,
        });

    const pullNode = showBehind && (
      <Tooltip title={pullTooltip}>
        <div
          aria-busy={pulling}
          aria-disabled={actionsBlocked}
          {...stylex.props(
            styles.syncTrigger,
            styles.behindStat,
            actionsBlocked && styles.syncTriggerDisabled,
          )}
          role="button"
          onClick={actionsBlocked ? undefined : handlePull}
        >
          <span {...stylex.props(styles.aheadBehindStat)}>
            {pulling ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowDownIcon} size={10} />}
            {aheadBehind!.behind}
          </span>
        </div>
      </Tooltip>
    );

    const pushNode = showAhead && (
      <Tooltip title={pushTooltip}>
        <div
          aria-busy={pushing}
          aria-disabled={actionsBlocked}
          {...stylex.props(
            styles.syncTrigger,
            styles.aheadStat,
            actionsBlocked && styles.syncTriggerDisabled,
          )}
          role="button"
          onClick={actionsBlocked ? undefined : handlePush}
        >
          <span {...stylex.props(styles.aheadBehindStat)}>
            {pushing ? <RingLoadingIcon size={10} /> : <Icon icon={ArrowUpIcon} size={10} />}
            {aheadBehind!.ahead}
          </span>
        </div>
      </Tooltip>
    );

    const outdatedNode = deviceOutdated && (
      <Tooltip title={t('workingDirectory.deviceOutdated')}>
        <div {...stylex.props(styles.syncTrigger, styles.outdatedStat)}>
          <Icon icon={TriangleAlertIcon} size={11} />
        </div>
      </Tooltip>
    );

    const worktreeToggleNode = isDraft && (
      <WorktreeToggle
        baseBranch={draft.selectedBranch}
        keyDeviceId={draft.keyDeviceId}
        path={path}
      />
    );

    const diffNode = (() => {
      if (!hasChanges) return null;
      const diffButton = (
        <div {...stylex.props(gitChipStyles.trigger)} role="button" onClick={handleToggleReview}>
          <span {...stylex.props(styles.diffStat)}>
            {diffStats.additions > 0 && (
              <span {...stylex.props(styles.diffStatAdded)}>+{diffStats.additions}</span>
            )}
            {diffStats.deletions > 0 && (
              <span {...stylex.props(styles.diffStatDeleted)}>-{diffStats.deletions}</span>
            )}
            {diffStats.additions === 0 && diffStats.deletions === 0 && diffStats.files > 0 && (
              <span {...stylex.props(styles.diffStatModified)}>±{diffStats.files}</span>
            )}
          </span>
        </div>
      );
      return <Tooltip title={diffStatTooltip}>{diffButton}</Tooltip>;
    })();

    return (
      <>
        <div {...stylex.props(gitChipStyles.separator)} />
        <div {...stylex.props(styles.branchGroup)}>{branchNode}</div>
        {pullNode}
        {pushNode}
        {outdatedNode}
        {worktreeToggleNode}
        {diffNode}
        {topicPullRequestChip}
      </>
    );
  },
);

GitStatus.displayName = 'GitStatus';

export default GitStatus;