# Patchpal GUI Usage Guide

This guide provides a detailed walkthrough of using the Patchpal GUI for AI-assisted patch backporting.

## Table of Contents

- [Getting Started](#getting-started)
  - [Launching Patchpal](#launching-patchpal)
  - [Resolving Git Merge Conflicts](#resolving-git-merge-conflicts)
- [Understanding the Main Window](#understanding-the-main-window)
- [Working with Hunks](#working-with-hunks)
  - [Understanding Hunk States](#understanding-hunk-states)
  - [Hunk Command Buttons](#hunk-command-buttons)
  - [Accepting Hunks](#accepting-hunks)
  - [Expanding and Collapsing Context](#expanding-and-collapsing-context)
- [Committing Changes](#committing-changes)
  - [Ready to Commit](#ready-to-commit)
  - [Finalizing](#finalizing)
- [AI-Assisted Conflict Resolution](#ai-assisted-conflict-resolution)
- [Dependency Detection](#dependency-detection)
- [Keyboard Navigation](#keyboard-navigation)
- [External Editor Integration](#external-editor-integration)
- [Advanced Usage](#advanced-usage)
  - [Usage With RPM (dist-git)](#usage-with-rpm-dist-git)
  - [Other Usage](#other-usage)
- [Getting Help](#getting-help)

## Getting Started

### Launching Patchpal

To backport an upstream commit to your current downstream repository:

```bash
cd ~/your/project
patchpal <upstream_commit_id>
```

If upstream objects are in a separate repository:

```bash
patchpal -g ~/upstream_project <upstream_commit_id>
```

With JIRA integration:

```bash
patchpal -j PROJECT-1234 <upstream_commit_id>
```

Auto-commit clean cherry-picks without opening the GUI:

```bash
patchpal -c <upstream_commit_id>
```

### Resolving Git Merge Conflicts

Patchpal can also resolve merge conflicts. When you're inside a git repository
with a merge conflict, just run:

```bash
patchpal
```

## Understanding the Main Window

When Patchpal opens, you'll see a two-panel interface showing the differences between upstream and backported code.

![Main Patchpal Window Overview](resources/img/MainView.png)

### Top Control Bar

The top bar contains your primary controls:

![Top Bar](resources/img/TopBar.png)

**Left Section:**
- **File count** - Total number of files affected by the patch
- **Hunks to review** - Number of unaccepted hunks remaining
- **Next (🮶)** - Jump to the next hunk requiring review
- **Accept clean button (🧹)** - Accept all conflict-free hunks at once


**Center Section:**
- **File selector dropdown** - Switch between files
  - Red number badge = unaccepted hunks in that file
  - Green checkmark (✓) = all hunks accepted

![File Viewer](resources/img/Files.png)

**Right Section:**
- **Commit button (🏃)** - Appears when all hunks are accepted
- **Keyboard help (⌨❓)** - View all keyboard shortcuts
- **Settings (⚙)** - Configure editor and preferences

### The Diff View

- **Backported Code** (Left) - Your downstream version with changes applied
- **Upstream Code** (Right) - The original upstream patch

**Color Coding:**
- **Red lines** - Deletions (lines being removed)
- **Green lines** - Insertions (lines being added)
- **White/Default** - Context lines (unchanged)
- **Gray** - Headers and metadata

## Working with Hunks

### Understanding Hunk States

Each hunk (a section of changes) can be in one of several states:

**Clean States:**
- **Clean** - Patch applied perfectly, no conflicts
- **Context Fuzz** - Applied with minor context differences
- **Fuzzy** - Applied using fuzzy matching algorithm

**Action Required States:**
- **Missing** - Couldn't apply, may need dependencies
- **Failed** - AI or application attempt failed
- **Edited** - You've manually modified this hunk

**Processing States:**
- **Interim** - AI is processing (animated spinner)
- **Editing** - External editor is open (sync icon)

**AI States:**
- **AI(1)**, **AI(2)**, etc. - Viewing AI suggestion #N

### Hunk Command Buttons

Below each hunk's status, you'll see relevant action buttons:

![HunkControls](resources/img/Conflict.png)

- **✔ accept** - Accept this hunk as-is
- **use AI** - Request AI assistance for conflict resolution
- **retry** - Retry a failed AI operation
- **◀ prev** - View previous AI suggestion
- **next ▶** - View next AI suggestion
- **✎ edit** - Open in external editor
- **🗙 remove** - Unapply this hunk (mark as not applied)

### Accepting Hunks

**Individual Acceptance:**
1. Review the hunk changes in both columns
2. Click **✔ accept** or press `a`
3. The hunk is marked as accepted, file badge updates

**Bulk Acceptance:**
1. Click **🧹 accept clean** in the top bar (or press `Ctrl+A`)
2. All clean hunks across all files are accepted instantly
3. Only conflicted hunks remain for review

### Expanding and Collapsing Context

Large unchanged sections are automatically folded:


- **Folded sections** show `✀` and display `[...]`
- Press `Enter` or click to toggle expansion
- Use `+` to expand, `-` to collapse when focused
- Helps focus on actual changes

## Committing Changes

### Ready to Commit

Once all hunks are accepted:

1. The "hunks to review" count reaches 0
2. All file badges show green checkmarks (✓)
3. The **🏃 commit** button appears (or **💾 save** in merge conflict resolution mode)

### Finalizing

**To commit:**
1. Click **🏃 commit** or press `Ctrl+Enter`
2. Patchpal writes changes to disk
3. Creates a git commit with:
   - Original commit message
   - Author information
   - JIRA reference (if provided with `-j`)
   - Conflict markers (if any)
   - AI usage note (if AI was used)
4. Application closes with exit code 0 (success)

**In merge conflict resoluction mode:**
1. Click **💾 save** to write and stage the merged result
2. Then you can continue with the merge process (`git merge --continue` etc.)

## AI-Assisted Conflict Resolution

When a hunk has conflicts or applies with fuzz, use AI to generate intelligent suggestions.

### Requesting AI Help

<!-- IMAGE: ai-request.png -->
*Screenshot before and during AI processing*

1. Focus on a hunk that needs resolution
2. Click **use AI** or press `u`
3. Status changes to **Interim** with a spinner
4. Wait for AI to generate suggestions (usually a few seconds)

### Reviewing AI Suggestions

<!-- IMAGE: ai-suggestions.png -->
*Screenshot showing AI suggestion*

Once complete:
- Status shows **AI(1)** indicating first suggestion
- The backported column shows AI's proposed resolution
- Both columns highlight differences

**Navigate through suggestions:**
- Press `n` or click **next ▶** for the next suggestion
- Press `p` or click **◀ prev** for the previous suggestion
- Each suggestion is numbered: AI(1), AI(2), AI(3), etc.

**Choose an option:**
- Press `a` or click **✔ accept** to use the current suggestion
- Press `e` or click **✎ edit** to manually refine it
- Press `r` or click **retry** if AI failed
- Press `x` or click **🗙 remove** to unapply the hunk

### When AI Fails

If AI returns an error:
- Error message appears in the status area
- Click **retry** or press `r` to try again
- Consider using **✎ edit** to resolve manually
- Check your network connection and server configuration

## Dependency Detection

Patchpal automatically detects when a hunk can't be applied due to missing prerequisite commits.

### Viewing Suggestions

![CommitViewer](resources/img/Suggestions.png)

When dependencies are detected:
1. A **Suggested dependencies** section appears below the hunk
2. Shows up to 3 missing commits with:
   - Commit ID (short hash)
   - Commit message
   - Author and date information
3. "and X more" appears if more dependencies exist

**During Search:**
- Shows "Looking for missing dependencies…"
- Animated striped background indicates progress
- Updates in real-time as dependencies are found

### Opening the Commit List Window

![CommitViewer](resources/img/CommitViewer.png)

1. Click the **open** link in the suggestions section
2. Press `Enter` when focused on the suggestions line
3. A new window opens showing detailed commit information

**In the Commit List Window:**
- Expand commits by clicking or pressing `Enter`
- View full commit details (author, date, message)
- Expand the **diff** entry to see the full patch
- Click the copy button (📋) or press `Ctrl+C` to copy the commit ID
- Press `Ctrl+W` or `Escape` to close the window

**Using the Information:**
1. Copy prerequisite commit IDs
2. Backport those commits first (in order)
3. Return to your original commit
4. The hunk should now apply cleanly

## Keyboard Navigation

Patchpal is designed for efficient keyboard-driven workflow.

Press the **⌨❓** button or view the keyboard help window anytime for a complete reference.

![Main Patchpal Window Overview](resources/img/Shortcuts.png)


## External Editor Integration

For complex conflicts, you can edit hunks in your preferred text editor.

### First-Time Setup

1. Press `e` on any hunk
2. If no editor is configured, a dialog appears
3. Enter your editor command, e.g.:
   - `gvim -f %f` (for GVim)
   - `gedit %f` (for gedit)
   - `code --wait %f` (for VS Code)
   - `emacs %f` (for Emacs)
4. `%f` is replaced with the temporary file path
5. Click **Set** to save

**Or configure via Settings:**
1. Click the **⚙** settings button
2. Update the "External editor" field
3. Click **OK**

### Editing a Hunk

1. Focus on the hunk you want to edit
2. Press `e` or click **✎ edit**
3. Status changes to **Editing** with a sync icon
4. Your configured editor opens with the hunk content
5. Make your changes and save
6. Close the editor

## Advanced Usage

### Usage With RPM (dist-git)

Patchpal may also be used to backport RPM (dist-git) changes. This is
implemented via wrapper tool `./tools/patchpal-rpm`. It will backport
the spec file changes and patches. `patchpal` must be installed and in
your `PATH`.

```
$ patchpal-rpm -h
Description:
patchpal-rpm is a tool for backporting dist-git commits to older
releases. It is a wrapper around patchpal. It MUST be called from a
dist-git checkout branch to which a given git hash is to be backported.

Usage: patchpal-rpm [<options>] -s <spec file> <commit hash>

<commit hash>   The dist-git hash to backport to the currently checkout branch.

Options:
-h      Help output, i.e. what you're reading now.
-c      Commit changes automatically after successful backport.
-s      RPM spec file. Required. Path is relative to CWD (dist-git checkout).
```

**Note**: The `patchpal-rpm` tool requires `rhpkg` to be installed for working with dist-git repositories.

This examples backports a CentOS Stream 9 package update to CentOS
Stream 8. Patchpal will be invoked for each patch added in the commit.

```
$ git clone https://gitlab.com/redhat/centos-stream/rpms/firewalld.git firewalld_rpm
$ cd firewalld_rpm
$ git checkout c8s
$ patchpal-rpm -s firewalld.spec c440185bad
```

### Other Usage

Patchpal also supports [`git mergetool` workflow](Usage-advanced.md).

---

## Getting Help

- **Keyboard shortcuts**: Press **⌨❓** in the application
- **Command-line help**: Run `patchpal --help`
- **Backend information**: https://gitlab.com/patchpal-ai/patchpal-backend
- **Report issues**: https://gitlab.com/patchpal-ai/patchpal-gui/issues

