Maestro icon indicating copy to clipboard operation
Maestro copied to clipboard

feat(git): add graph view + branch switcher dropdown

Open feldsys opened this issue 6 months ago • 10 comments

Closes #958

Summary

Two new affordances on the git surface, both plumbed through the existing SSH-remote pathway:

  • Graph view in GitLogViewer — toggleable List/Graph buttons in the modal header. Graph mode renders commits with parent-hash topology via @gitgraph/react, supports clicking commits to drive the existing diff panel, and persists the user's view preference via localStorage. Side-branch commits only visible via git log --all are tracked separately so the right-hand commit detail panel stays in sync regardless of which view is active.
  • Branch switcher dropdown on the header branch chip — single click still opens the git log (debounced ~220 ms to differentiate from a double click); double click opens a filterable branch picker that switches the working tree via git switch <branch>. Failures (e.g. dirty working tree) surface git's stderr inside the dropdown instead of throwing.

Mapping to issue #958

Issue ask This PR
Show the current branch prominently Already shown on the header branch chip; PR makes it interactive
List local (and remote) branches ✅ Filterable list in the new dropdown
Switch/checkout an existing branch from Maestro ✅ Double-click chip → pick branch → git switch
Warn clearly when switching with uncommitted changes ✅ Failure path surfaces git's stderr inline (e.g. dirty working tree) instead of silently failing
Create a new branch from current HEAD / from base ⏳ Out of scope for this PR — happy to follow up

IPC surface

Two new handlers, both honoring the existing sshRemoteId / remoteCwd SSH wrapping:

  • git:graph — returns commits with parent hashes ({ nodes, error }) for lane rendering. Default limit 200, configurable via options.limit.
  • git:switch — returns { success, stdout, stderr } instead of throwing, so the UI can render git's failure message in-place.

Files

  • src/main/ipc/handlers/git.ts, src/main/preload/git.ts, src/renderer/services/git.ts, src/renderer/global.d.ts — IPC + service plumbing
  • src/renderer/components/GitGraphView.tsx (new) — @gitgraph/react wrapper themed via theme.colors
  • src/renderer/components/GitLogViewer.tsx — list/graph toggle + selection sync
  • src/renderer/components/MainPanel/BranchSwitcherDropdown.tsx (new) — filterable picker that calls git:switch
  • src/renderer/components/MainPanel/MainPanelHeader.tsx — single/double-click handling on branch chip
  • src/renderer/constants/modalPriorities.ts — adds BRANCH_SWITCHER: 195
  • src/__tests__/renderer/components/MainPanel.test.tsx — updated SSH-remote click test, new double-click test
  • package.json / package-lock.json — adds @gitgraph/react ^1.6.0

The branch also includes a separate commit (fix(node-pty): patch winpty.gyp paths and harden POSIX spawn errors) that fixes a Windows build issue — happy to split it into its own PR if preferred.

Why

Per #958, currently the only way to inspect history is the linear list, which makes branch topology impossible to read at a glance, and the only way to switch branches inside Maestro is to open a terminal. Both moves keep the user inside the AI surface.

Test plan

  • [x] npm run lint — TypeScript across all three configs
  • [x] npm run lint:eslint — ESLint
  • [x] npm run test -- --run src/__tests__/renderer/components/MainPanel.test.tsx — 137 tests including the new double-click + branch switcher coverage
  • [x] Manual: open a git repo, click the branch chip in the header → git log opens after ~220 ms
  • [x] Manual: double-click the branch chip → branch switcher opens, filter input is focused, pick a branch → working tree switches
  • [x] Manual: in git log, toggle Graph view → commits render with lane topology, clicking a commit (including a side-branch commit) drives the diff panel on the right
  • [ ] Manual (SSH): repeat above with an SSH remote enabled session — both new IPC paths route through getSshRemoteById

Summary by CodeRabbit

  • New Features

    • Visual commit graph with selectable, highlighted commits; graph lazy-loads and can drive commit details/diff loading.
    • Persistent List ↔ Graph view toggle in the commit viewer.
    • Branch switcher dropdown: searchable, keyboard-navigable, shows loading/empty states and success/error feedback.
    • Branch chip: single-click opens log; double-click or Shift+Enter opens branch switcher.
  • Dependency

    • Added @gitgraph/react.
  • Tests

    • Expanded tests for branch-switch interactions and related UI behavior.

feldsys avatar May 07 '26 13:05 feldsys

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds commit-graph rendering and interactive branch switching: new dependency, main IPC handlers, preload and renderer APIs/types, GitGraphView component, BranchSwitcherDropdown UI, GitLogViewer list/graph toggle, MainPanelHeader click/keyboard wiring, modal priority constant, and tests.

Changes

Git Graph Visualization & Branch Switching Feature

Layer / File(s) Summary
Package Dependency
package.json
Adds @gitgraph/react@^1.6.0 runtime dependency for commit graph rendering.
Data Types & Interfaces
src/main/preload/git.ts, src/renderer/global.d.ts
Declares GitGraphNode and adds preload graph() and switchBranch() signatures exposed in global API.
Modal Priority Constant
src/renderer/constants/modalPriorities.ts
Adds BRANCH_SWITCHER modal priority constant set to 195.
Backend IPC Handlers
src/main/ipc/handlers/git.ts
Implements git:graph handler parsing git log into nodes with parents and metadata; implements git:switch handler validating branch names and running git switch, returning structured success/stderr output.
Preload API Bridge
src/main/preload/git.ts
Adds graph() invoking git:graph IPC (returns { nodes, error }) and switchBranch() invoking git:switch IPC (returns { success, stdout, stderr }).
Renderer Service Methods & Types
src/renderer/services/git.ts
Adds GitGraphNode and GitSwitchResult types; implements gitService.getGraph() (calls preload graph, throws on payload error) and gitService.switchBranch() (calls preload switchBranch and maps result).
Git Graph Component
src/renderer/components/GitGraphView.tsx
New GitGraphView component rendering commit graphs via @gitgraph/react (branch picking from refs, date-sorted construction, merge handling, subject truncation, selection styling, optional onCommitClick).
GitLogViewer Integration
src/renderer/components/GitLogViewer.tsx
Adds persistent List
Branch Switcher Dropdown
src/renderer/components/MainPanel/BranchSwitcherDropdown.tsx
New portal-based dropdown anchored to branch chip: fetches branches, supports search/filter and keyboard navigation, calls gitService.switchBranch, shows success flash or error toast, and closes on outside interactions with modal layering.
Main Panel Header Wiring
src/renderer/components/MainPanel/MainPanelHeader.tsx
Adds debounced single-click vs double-click handling on git chip (single-click opens log after debounce; double-click cancels debounce and opens branch switcher), adds Shift+Enter keyboard shortcut, updates chip titles/tooltips, and conditionally renders BranchSwitcherDropdown.
Tests & Verification
src/__tests__/renderer/components/MainPanel.test.tsx
Adds Vitest no-op useModalLayer mock, extends gitService test mock with getBranches, getGraph, switchBranch, adds tests verifying double-click and Shift+Enter open branch switcher, and updates single-click test to wait for debounced log open.

Sequence Diagram(s)

sequenceDiagram
  participant Renderer
  participant Preload
  participant Main
  participant GitCLI
  Renderer->>Preload: window.maestro.git.graph(cwd, options)
  Preload->>Main: ipc invoke 'git:graph'
  Main->>GitCLI: git log --pretty=GRAPH_START...
  GitCLI-->>Main: stdout (nodes)
  Main-->>Preload: { nodes, error }
  Preload-->>Renderer: { nodes, error }
  Renderer->>Preload: window.maestro.git.switchBranch(cwd, branch)
  Preload->>Main: ipc invoke 'git:switch'
  Main->>GitCLI: git switch <branch>
  GitCLI-->>Main: stdout/stderr (exit code)
  Main-->>Preload: { success, stdout, stderr }
  Preload-->>Renderer: result

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

"🐰
A graph of commits now unfolds so bright,
Branch switcher hops to left and right,
From log to graph with just a click or key,
Maestro guides branches back to me,
Hooray — the rabbit cheers, switch done with glee!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the two main features added: git graph view and branch switcher dropdown.
Linked Issues check ✅ Passed Changes implement core requirements from #958: show current branch, list local branches, switch branches. Create-branch and remote-branch features deferred appropriately. Warning on uncommitted changes and error surfacing addressed.
Out of Scope Changes check ✅ Passed All changes are scoped to git graph/branch-switch functionality per #958. The node-pty Windows fix mentioned is acknowledged as separate.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 07 '26 13:05 coderabbitai[bot]

Greptile Summary

This PR adds two interactive git features to the Maestro header: a toggleable list/graph commit view in GitLogViewer (using @gitgraph/react) and a filterable branch-switcher dropdown triggered by double-clicking the branch chip. Both features are wired through the existing SSH-remote IPC pathway via two new handlers (git:graph, git:switch).

  • git:graph adopts the ASCII Unit Separator (%x1f) delimiter — correctly avoiding the author-name pipe-corruption present in the pre-existing git:log handler — and returns parent hashes for lane topology.
  • git:switch validates against flag-injection and returns a structured { success, stderr } object so the UI can render git's error message inline instead of throwing.
  • GitGraphView builds a GitgraphCore imperatively inside useMemo to avoid React 18 StrictMode double-mount issues; BranchSwitcherDropdown is portal-positioned with correct click-outside handling and modal-layer registration.

Confidence Score: 4/5

Safe to merge; the new features work correctly for the common case and failures surface gracefully.

The IPC plumbing, branch-switcher, and single/double-click debounce are solid. The graph view has two edge cases worth tracking: date-based sort may render incorrect topology for repos with backdated or rebased commits, and full GitgraphCore reconstruction on every commit click could cause jank at the 200-commit limit. Neither blocks shipping, but the graph topology issue is a silent correctness gap for non-trivial histories.

src/renderer/components/GitGraphView.tsx — commit ordering and per-click rebuild strategy.

Important Files Changed

Filename Overview
src/renderer/components/GitGraphView.tsx New component wrapping @gitgraph/react; date-based commit sort may produce wrong topology for non-linear histories; full graph rebuild on every selection change is expensive.
src/renderer/components/GitLogViewer.tsx List/graph toggle, graph data loading, and selection-sync logic added; graphLoading initialised to true (fixes flash); loadCommitDiff missing sshRemoteId dep; footer counter misleading in graph view.
src/main/ipc/handlers/git.ts Adds git:graph (uses %x1f separator) and git:switch (validates flag-injection, returns structured result); both handlers handle sshRemote/remoteCwd correctly.
src/renderer/components/MainPanel/BranchSwitcherDropdown.tsx New filterable branch picker; portal-positioned with correct click-outside handling and modal layer registration; switch failure surfaces stderr in a toast; no correctness issues found.
src/renderer/components/MainPanel/MainPanelHeader.tsx Single/double-click disambiguation with 220ms debounce; unmount cleanup for timer added; Shift+Enter keyboard affordance for branch switcher; looks correct.
src/renderer/services/git.ts getGraph and switchBranch service methods added; remoteCwd accepted but callers don't forward it (consistent with pre-existing service methods).

Sequence Diagram

sequenceDiagram
    participant U as User
    participant MH as MainPanelHeader
    participant BSD as BranchSwitcherDropdown
    participant GLV as GitLogViewer
    participant GGV as GitGraphView
    participant SVC as gitService
    participant IPC as git IPC handlers

    U->>MH: single click branch chip (220ms)
    MH->>GLV: setGitLogOpen(true)
    GLV->>IPC: git:log + git:commitCount

    U->>MH: double click branch chip
    MH->>BSD: open BranchSwitcherDropdown
    BSD->>SVC: getBranches(cwd, sshRemoteId)
    SVC->>IPC: git:branches
    IPC-->>BSD: string[]

    U->>BSD: select branch
    BSD->>SVC: switchBranch(cwd, branch, sshRemoteId)
    SVC->>IPC: git:switch
    IPC-->>SVC: "{ success, stdout, stderr }"
    alt success
        BSD->>MH: onSwitched → refreshGitStatus()
        BSD->>BSD: onClose()
    else failure
        BSD-->>U: notifyToast(stderr)
    end

    U->>GLV: click Graph toggle
    GLV->>SVC: "getGraph(cwd, {limit:200}, sshRemoteId)"
    SVC->>IPC: git:graph (--all)
    IPC-->>GGV: GitGraphNode[]
    GGV-->>U: SVG commit graph

    U->>GGV: click commit node
    GGV->>GLV: onCommitClick(hash)
    GLV->>IPC: git:show (load diff)

Reviews (4): Last reviewed commit: "fix(git): handle refreshGitStatus + getB..." | Re-trigger Greptile

greptile-apps avatar May 07 '26 14:05 greptile-apps

@feldsys — thanks a lot for this contribution! Nice piece of work threading both new affordances cleanly through the existing SSH-remote pathway, and the issue→PR mapping in the description is super helpful.

A few things to address before this can land. CodeRabbit caught most of these and I agree with them; flagging here so they don't get lost:

Bugs / correctness

  1. switching state can stick forever in BranchSwitcherDropdown.tsx (doSwitch, ~line 110–133). setSwitching(null) only runs on the happy path — if gitService.switchBranch rejects (IPC channel error, etc.), every branch button stays disabled and the spinner never stops. Wrap the await in try/finally and clear switching in the finally.

  2. Graph fetches 100 commits but list fetches 200 (GitLogViewer.tsx, ~line 120). Toggle to graph after selecting entries[100..199] and the right-side detail pane points at a commit the graph can't render or highlight. Use the same limit (extract a shared constant so they can't drift again).

  3. gitService.getGraph swallows main-process error (src/renderer/services/git.ts, ~line 188–195). The IPC returns { nodes, error } but the wrapper drops error and returns [], so the viewer can't tell "git command failed" from "no commits" — the empty-state message will be wrong. Surface the error (or return the whole { nodes, error }).

  4. Initial localStorage.getItem read isn't guarded (GitLogViewer.tsx, view-mode useState initializer). The setItem call already has try/catch but the read does not — if it throws during render the whole modal fails to open instead of falling back to 'list'.

  5. @gitgraph/react doesn't re-run the children function on prop changes (GitGraphView.tsx). The selected-commit dot styling at lines ~129–132 is baked in at mount and won't update when selectedHash changes. Easiest fix is <Gitgraph key={selectedHash ?? ''} options={...}> to force remount on selection change. (Heads up that this rebuilds the whole graph each click — fine for ~200 commits, may want the external CSS-overlay approach later if you push the limit higher.)

Defense-in-depth nit

  1. Validate branchName in the git:switch IPC handler. execGit(['switch', branchName], ...) uses execFile so no shell injection is possible, but a branch name starting with - would be interpreted as a git flag (git switch -c creates a branch, etc.). Branches from git branch --list never start with -, but the handler is reachable from any renderer code path — a one-line if (branchName.startsWith('-')) reject keeps it safe regardless of caller.

Scope

  1. The fix(node-pty): patch winpty.gyp paths and harden POSIX spawn errors commit is unrelated to the git graph/branch-switcher feature. You already offered to split it — yes please, that'd be much easier to review and revert independently.

Minor / discussion

  1. The 220ms single-click delay on the branch chip adds latency to a primary action (open git log). Worth confirming with the team that this UX cost is acceptable vs. e.g. moving "switch branch" to a separate affordance.

Once the items above are addressed, happy to take another pass.

pedramamini avatar May 07 '26 14:05 pedramamini

@greptile re-review this pr please

jSydorowicz21 avatar May 07 '26 22:05 jSydorowicz21

@feldsys please address the orphan issue in the latest greptile feedback

jSydorowicz21 avatar May 08 '26 01:05 jSydorowicz21

@jSydorowicz21 i did :)

feldsys avatar May 09 '26 06:05 feldsys

@chr1syy sorry for the late response, i did the rebase now :) thank you, for your review

feldsys avatar Jun 08 '26 12:06 feldsys

@greptile @coderabbit new review pass please

jSydorowicz21 avatar Jun 08 '26 14:06 jSydorowicz21

While those are going we do have a short freeze for merging new features in so we can cut a new mainline release but if this ones in good shape we'll get it merged into the next rc!

jSydorowicz21 avatar Jun 08 '26 14:06 jSydorowicz21

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read all key changed files
echo "=== BranchSwitcherDropdown.tsx ==="
cat src/renderer/components/MainPanel/BranchSwitcherDropdown.tsx

echo ""
echo "=== GitLogViewer.tsx ==="
cat src/renderer/components/GitLogViewer.tsx

echo ""
echo "=== GitGraphView.tsx ==="
cat src/renderer/components/GitGraphView.tsx

echo ""
echo "=== renderer/services/git.ts ==="
cat src/renderer/services/git.ts

echo ""
echo "=== main/ipc/handlers/git.ts ==="
cat src/main/ipc/handlers/git.ts

echo ""
echo "=== MainPanelHeader.tsx ==="
cat src/renderer/components/MainPanel/MainPanelHeader.tsx

echo ""
echo "=== MainPanel.test.tsx ==="
cat src/__tests__/renderer/components/MainPanel.test.tsx

Length of output: 252691



@jSydorowicz21 Here is the updated review pass. Good news: all six correctness issues from @pedramamini's original review have been addressed. Details below.


Review Pass — PR #962

✅ Previously flagged issues — all resolved

# Issue Status
1 switching state can stick forever Fixed — doSwitch has a finally { setSwitching(null) } block
2 Graph fetches 100, list fetches 200 Fixed — shared const COMMIT_FETCH_LIMIT = 200 used for both
3 getGraph swallows main-process error Fixed — rethrow: true + throws on result.error, caller has try/catch
4 localStorage.getItem unguarded Fixed — useState initializer wrapped in try/catch, falls back to 'list'
5 @gitgraph/react children not re-run on prop change Fixed — <Gitgraph key={selectedHash ?? 'none'}> forces remount on selection change
6 branchName flag-injection risk in git:switch Fixed — validates typeof === 'string', non-empty, and !startsWith('-')

🐛 New finding — stale sshRemoteId closure in GitLogViewer.tsx

File: src/renderer/components/GitLogViewer.tsx

loadCommitDiff closes over the sshRemoteId prop but only lists cwd in its dependency array. If sshRemoteId ever changes (e.g., a session is re-configured), diffs will silently be fetched via the stale remote.

// Current — sshRemoteId is stale after remount if it changes
const loadCommitDiff = useCallback(
    async (hash: string) => {
        const result = await window.maestro.git.show(cwd, hash, sshRemoteId);
        // ...
    },
    [cwd] // ← sshRemoteId missing
);

Fix:

const loadCommitDiff = useCallback(
    async (hash: string) => {
        const result = await window.maestro.git.show(cwd, hash, sshRemoteId);
        // ...
    },
    [cwd, sshRemoteId] // ← add sshRemoteId
);

ℹ️ Minor inconsistency — git:log IPC default limit

git:log handler defaults to 100 while git:graph defaults to 200. There is no user-visible impact today because the renderer always passes COMMIT_FETCH_LIMIT, but it's a silent footgun if the handler is ever called without options:

// src/main/ipc/handlers/git.ts
const limit = options?.limit || 100; // git:log
const limit = options?.limit || 200; // git:graph ← inconsistent

Worth aligning these to the same value (200).


🔖 Process item (still outstanding)

Issue #7 (separate node-pty Windows fix commit) cannot be confirmed from code alone — please verify with @feldsys whether this commit has been moved to its own PR before merging.


Summary

The PR is in good shape. The one functional bug (stale sshRemoteId in loadCommitDiff) should be fixed before merge. The limit inconsistency and process item are lower priority but worth addressing.


✏️ Learnings added
Learnt from: jSydorowicz21
URL: https://github.com/RunMaestro/Maestro/pull/962

Timestamp: 2026-06-08T14:04:41.752Z
Learning: In RunMaestro/Maestro PR `#962`, `gitService.getGraph` in `src/renderer/services/git.ts` intentionally uses `rethrow: true` (unlike most other gitService methods) so the graph viewer can distinguish a git command failure from a legitimately empty commit list. This is a deliberate exception to the codebase's general pattern of swallowing IPC errors via `defaultValue` without `rethrow`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: ksylvan
Repo: RunMaestro/Maestro PR: 925
File: src/renderer/hooks/remote/useAppRemoteEventListeners.ts:518-520
Timestamp: 2026-04-29T04:26:49.067Z
Learning: In RunMaestro/Maestro, `gitService` methods (`isRepo`, `getBranches`, `getTags`, `getStatus`, `getDiff`, etc.) in `src/renderer/services/git.ts` all use `createIpcMethod` with a `defaultValue` and no `rethrow: true`. This means they NEVER throw — IPC failures are swallowed internally. `createIpcMethod` in `src/renderer/services/ipcWrapper.ts` already calls `captureException` on the swallow path. Therefore, wrapping calls to these gitService methods in try/catch and adding `captureException` is unnecessary (dead code) and would duplicate Sentry reports. The correct pattern (as in `useSessionCrud.ts`) is to call gitService methods directly without a surrounding try/catch.

coderabbitai[bot] avatar Jun 08 '26 14:06 coderabbitai[bot]