From aecd3f92bf4b6db1462b2aff9ad97a36a939f9a0 Mon Sep 17 00:00:00 2001
From: Grok Bot
Date: Mon, 19 Oct 2026 17:03:28 +0200
Subject: [PATCH] feat(ui): drag and drop git actions in the graph and sidebar
(DAN-90)
Squashed for the rebase onto #155, #154 and #156. Drag-rebase now opens the
same RebaseOntoDialog as the Rebase menu (with the --update-refs choice).
---
README.md | 11 +-
ROADMAP.md | 13 +
TASKS.md | 10 +
ui/fixtures/gitDrag.fixture.test.ts | 294 ++++++++++++++++
ui/src/App.tsx | 22 +-
ui/src/components/GitDragHost.tsx | 494 +++++++++++++++++++++++++++
ui/src/components/Sidebar.tsx | 58 +++-
ui/src/lib/gitDrag.test.ts | 442 +++++++++++++++++++++++++
ui/src/lib/gitDrag.ts | 497 ++++++++++++++++++++++++++++
ui/src/lib/i18n.ts | 33 ++
ui/src/lib/rebase.test.ts | 27 +-
ui/src/lib/rebase.ts | 36 ++
ui/src/styles/features.css | 13 +
ui/src/views/Commits.tsx | 28 ++
ui/src/views/MainlineDialog.tsx | 10 +-
ui/src/views/MergeDialog.tsx | 7 +-
ui/src/views/RebaseEditor.tsx | 36 +-
ui/src/views/RebaseOntoDialog.tsx | 23 +-
website/docs/commits-and-history.md | 12 +-
website/docs/everyday-git.md | 5 +-
20 files changed, 2043 insertions(+), 28 deletions(-)
create mode 100644 ui/fixtures/gitDrag.fixture.test.ts
create mode 100644 ui/src/components/GitDragHost.tsx
create mode 100644 ui/src/lib/gitDrag.test.ts
create mode 100644 ui/src/lib/gitDrag.ts
diff --git a/README.md b/README.md
index 4d166c9..c7e4756 100644
--- a/README.md
+++ b/README.md
@@ -318,9 +318,14 @@ the resolved app appearance automatically.
tags, stashes, remotes, ordered multi-commit
cherry-pick, merge-mainline cherry-pick/revert, branch/tag/commit comparison,
merge, plain rebase onto a branch (with a per-repo `--update-refs` choice),
- and a fully keyboard-operable interactive rebase (reorder, reword,
- edit/pause-to-amend, squash, fixup, drop, merge preservation, and moving
- other local branches in the range) with pause/conflict Continue / Abort.
+ drag-and-drop merge/rebase of sidebar branches (including remote-tracking
+ branches), drag-to-push onto a remote, drag-to-cherry-pick graph commits
+ onto a local branch, and drag-to-reorder or squash commits on the current
+ branch (the interactive rebase editor opens prefilled), always behind a
+ confirmation, and a fully keyboard-operable interactive rebase (reorder,
+ reword, edit/pause-to-amend, squash, fixup, drop, merge preservation, and
+ moving other local branches in the range) with pause/conflict Continue /
+ Abort.
**Amend staged changes into this commit** folds the index into an older
commit on the branch in one confirmed rewrite.
The merge editor can suggest a per-hunk AI resolution (explanation and
diff --git a/ROADMAP.md b/ROADMAP.md
index 0dce14f..096068c 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -3299,6 +3299,19 @@ in place. Git older than 2.38 disables the toggle instead of failing
mid-rebase. Later stack slices (parent branch, sidebar grouping, restack,
stacked PRs) stay open.
+**Drag-and-drop branch merge/rebase (2026-10-19, DAN-90):** Dropping a sidebar
+branch on another branch opens a confirmation that names both refs and offers
+Merge or Rebase. Those verbs call the existing merge dialog and `Repo::rebase`,
+including remote-tracking branches in either direction. A branch dropped on
+itself, on a tag, or during a paused merge/rebase shows a no-drop cursor.
+Escape cancels with no checkout and no Git write. Dropping a local branch on
+a remote confirms `Repo::push_branch` and offers to create a missing upstream.
+Dropping graph commits on a local branch confirms the same cherry-pick as the
+graph menu, including the mainline parent dialog for a single merge commit.
+Dragging those commits onto another commit on the linear tip opens the
+interactive rebase editor with that reorder or squash already filled in.
+Escape closes the editor before Start, so Git does not run.
+
**Worktrees UI revision (2026-09-04):** Reworked PR 113's cramped table into
readable two-line rows: branch and directory together, working changes and
latest commit in separate columns, explicit current/locked indicators, and
diff --git a/TASKS.md b/TASKS.md
index ee2a0dd..3430f7a 100644
--- a/TASKS.md
+++ b/TASKS.md
@@ -398,6 +398,16 @@ community plugins, performance and platform certification from Git feature gaps.
`git rebase [--update-refs|--no-update-refs] `, any revspec; sidebar
branch menu "Rebase onto this" opens `RebaseOntoDialog`. The
choice is remembered as local `strand.rebaseUpdateRefs` when a rebase starts.)
+- ☑ Drag-and-drop Git actions (DAN-90). Branch onto branch: `GitDragHost` +
+ `resolveBranchDrop` confirm **Merge** / **Rebase** through `MergeDialog` and
+ `RebaseOntoDialog` (`Repo::rebase(onto, update_refs)`), including remote-tracking branches (sidebar remote menu
+ items too). Local branch onto a remote folder confirms `Repo::push_branch`
+ and offers to create a missing upstream. Graph commits dropped on a local
+ branch confirm `Repo::cherry_pick` (oldest first; a single merge opens
+ `MainlineDialog`; a mixed selection is refused). Dragging commits on the
+ linear tip of the current branch opens `RebaseEditor` prefilled
+ (`applyRebaseSeed`) to reorder or squash; Start is the only Git write.
+ Escape and no-drop targets do not run Git.
- ☑ Abort in-progress op (`Repo::abort_operation` — detects rebase / cherry-pick
/ revert / merge from `.git/` markers and runs the matching `--abort`; surfaced
by `RepoMeta.operation` + the in-progress banner and a ⌘K "Abort " action.)
diff --git a/ui/fixtures/gitDrag.fixture.test.ts b/ui/fixtures/gitDrag.fixture.test.ts
new file mode 100644
index 0000000..acf97a8
--- /dev/null
+++ b/ui/fixtures/gitDrag.fixture.test.ts
@@ -0,0 +1,294 @@
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ cherryPickGitArgs,
+ commitDragFromRows,
+ dragMergeArgs,
+ dragRebaseArgs,
+ pushGitArgs,
+ resolveBranchDrop,
+ resolveCherryPick,
+ resolvePushDrop,
+ resolveRebaseDrop,
+ type BranchHit,
+ type DragBranch,
+} from '../src/lib/gitDrag';
+import { applyRebaseSeed } from '../src/lib/rebase';
+
+const env = {
+ ...process.env,
+ GIT_AUTHOR_NAME: 'Drag',
+ GIT_AUTHOR_EMAIL: 'drag@example.com',
+ GIT_COMMITTER_NAME: 'Drag',
+ GIT_COMMITTER_EMAIL: 'drag@example.com',
+ GIT_EDITOR: 'true',
+ GIT_SEQUENCE_EDITOR: 'true',
+ GIT_AUTHOR_DATE: '2020-01-01T00:00:00Z',
+ GIT_COMMITTER_DATE: '2020-01-01T00:00:00Z',
+};
+
+const roots: string[] = [];
+
+function git(cwd: string, args: string[]): string {
+ return execFileSync('git', ['-c', 'commit.gpgsign=false', ...args], { cwd, encoding: 'utf8', env }).trim();
+}
+
+function fixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'strand-drag-'));
+ roots.push(dir);
+ git(dir, ['init', '-b', 'main']);
+ git(dir, ['commit', '--allow-empty', '-m', 'root']);
+ git(dir, ['switch', '-c', 'feature']);
+ git(dir, ['commit', '--allow-empty', '-m', 'feature change']);
+ git(dir, ['switch', 'main']);
+ git(dir, ['commit', '--allow-empty', '-m', 'main change']);
+ return dir;
+}
+
+function signature(dir: string): string {
+ return [
+ git(dir, ['rev-parse', '--abbrev-ref', 'HEAD']),
+ git(dir, ['log', '--format=%s', '--topo-order']),
+ git(dir, ['rev-parse', 'HEAD^{tree}']),
+ ].join('\n');
+}
+
+const feature: DragBranch = {
+ kind: 'local-branch',
+ ref: 'feature',
+ label: 'feature',
+ isHead: false,
+ upstreamRemote: null,
+ upstreamBranch: null,
+};
+const mainBranch: DragBranch = { ...feature, ref: 'main', label: 'main', isHead: true };
+const mainHit: BranchHit = { kind: 'local-branch', ref: 'main', label: 'main', isHead: true };
+const featureHit: BranchHit = { kind: 'local-branch', ref: 'feature', label: 'feature', isHead: false };
+
+afterEach(() => {
+ for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe('drag branch actions match the menu git commands', () => {
+ it('merging feature onto main matches Merge into main', () => {
+ const intent = resolveBranchDrop(feature, mainHit, null);
+ expect(intent?.checkout).toBeNull();
+ const menu = ['merge', '--no-edit', '--', 'feature'];
+ expect(dragMergeArgs(intent!)).toEqual(menu);
+
+ const viaMenu = fixture();
+ const viaDrag = fixture();
+ git(viaMenu, menu);
+ git(viaDrag, dragMergeArgs(intent!));
+ expect(signature(viaDrag)).toBe(signature(viaMenu));
+ expect(git(viaDrag, ['log', '-1', '--format=%s'])).toBe("Merge branch 'feature'");
+ });
+
+ it('rebasing feature onto main matches Rebase main onto this', () => {
+ const intent = resolveBranchDrop(feature, mainHit, null);
+ const menu = ['rebase', '--', 'feature'];
+ expect(dragRebaseArgs(intent!)).toEqual(menu);
+
+ const viaMenu = fixture();
+ const viaDrag = fixture();
+ git(viaMenu, menu);
+ git(viaDrag, dragRebaseArgs(intent!));
+ expect(signature(viaDrag)).toBe(signature(viaMenu));
+ expect(git(viaDrag, ['log', '--format=%s'])).toBe('main change\nfeature change\nroot');
+ });
+
+ it('dropping main onto feature matches checkout then the feature menu', () => {
+ const intent = resolveBranchDrop(mainBranch, featureHit, null);
+ expect(intent).toMatchObject({ checkout: 'feature', mergeRef: 'main', rebaseOnto: 'main' });
+
+ const mergeMenu = fixture();
+ const mergeDrag = fixture();
+ for (const dir of [mergeMenu, mergeDrag]) git(dir, ['switch', '--', 'feature']);
+ git(mergeMenu, ['merge', '--no-edit', '--', 'main']);
+ git(mergeDrag, dragMergeArgs(intent!));
+ expect(signature(mergeDrag)).toBe(signature(mergeMenu));
+
+ const rebaseMenu = fixture();
+ const rebaseDrag = fixture();
+ for (const dir of [rebaseMenu, rebaseDrag]) git(dir, ['switch', '--', 'feature']);
+ git(rebaseMenu, ['rebase', '--', 'main']);
+ git(rebaseDrag, dragRebaseArgs(intent!));
+ expect(signature(rebaseDrag)).toBe(signature(rebaseMenu));
+ });
+
+ it('pushing feature onto origin sets the upstream the menu push would', () => {
+ const intent = resolvePushDrop(feature, { kind: 'remote', ref: 'origin', label: 'origin', isHead: false }, null);
+ expect(intent).toMatchObject({ branch: 'feature', remote: 'origin', remoteBranch: 'feature', offerUpstream: true });
+ const menu = ['push', '--progress', '--set-upstream', '--', 'origin', 'refs/heads/feature:refs/heads/feature'];
+ expect(pushGitArgs(intent!, true)).toEqual(menu);
+
+ const viaMenu = pushFixture();
+ const viaDrag = pushFixture();
+ git(viaMenu.local, menu);
+ git(viaDrag.local, pushGitArgs(intent!, true));
+ expect(pushed(viaDrag.local)).toBe(pushed(viaMenu.local));
+ expect(git(viaDrag.local, ['rev-parse', 'feature'])).toBe(git(viaDrag.local, ['rev-parse', 'refs/remotes/origin/feature']));
+ expect(git(viaDrag.local, ['config', '--get', 'branch.feature.remote'])).toBe('origin');
+ expect(git(viaDrag.local, ['config', '--get', 'branch.feature.merge'])).toBe('refs/heads/feature');
+ });
+
+ it('cherry-picking onto main matches the graph menu command', () => {
+ const sample = fileFeature();
+ const hash = git(sample, ['rev-parse', 'feature']);
+ const source = commitDragFromRows([{ hash, short: hash.slice(0, 7), parents: [], index: 0, rewrite: true }]);
+ const intent = resolveCherryPick(source!, mainHit, null);
+ expect(cherryPickGitArgs(intent!.hashes)).toEqual(['cherry-pick', '--', hash]);
+
+ const viaMenu = fileFeature();
+ const viaDrag = fileFeature();
+ git(viaMenu, ['cherry-pick', '--', git(viaMenu, ['rev-parse', 'feature'])]);
+ git(viaDrag, cherryPickGitArgs([git(viaDrag, ['rev-parse', 'feature'])]));
+ expect(git(viaDrag, ['log', '--format=%s'])).toBe(git(viaMenu, ['log', '--format=%s']));
+ expect(git(viaDrag, ['rev-parse', 'HEAD^{tree}'])).toBe(git(viaMenu, ['rev-parse', 'HEAD^{tree}']));
+ expect(git(viaDrag, ['log', '-1', '--format=%s'])).toBe('add note');
+ });
+
+ it('reordering onto an older commit matches a hand-edited rebase todo', () => {
+ const viaDrag = linearFixture();
+ const viaMenu = linearFixture();
+ const drag = rebasePlan(viaDrag, 'reorder');
+ const menu = handPlan(viaMenu, 'reorder');
+ expect(drag.steps.map((step) => step.action)).toEqual(menu.steps.map((step) => step.action));
+ runRebase(viaDrag, drag.base, drag.steps);
+ runRebase(viaMenu, menu.base, menu.steps);
+ expect(git(viaDrag, ['log', '--format=%s'])).toBe(git(viaMenu, ['log', '--format=%s']));
+ expect(git(viaDrag, ['log', '--format=%s'])).toBe('B\nC\nA');
+ });
+
+ it('squashing into a commit matches a hand-edited rebase todo and does not run before the plan exists', () => {
+ const sample = linearFixture();
+ const intent = rebaseIntent(sample, 'squash');
+ expect(intent.seed.mode).toBe('squash');
+ expect(intent.seed.place).toBe('after');
+
+ const viaDrag = linearFixture();
+ const viaMenu = linearFixture();
+ const drag = rebasePlan(viaDrag, 'squash');
+ const menu = handPlan(viaMenu, 'squash');
+ expect(drag.steps.map((step) => step.action)).toEqual(['pick', 'squash']);
+ expect(drag.steps.map((step) => step.action)).toEqual(menu.steps.map((step) => step.action));
+ runRebase(viaDrag, drag.base, drag.steps);
+ runRebase(viaMenu, menu.base, menu.steps);
+ expect(git(viaDrag, ['log', '--format=%s'])).toBe(git(viaMenu, ['log', '--format=%s']));
+ expect(git(viaDrag, ['log', '--format=%s'])).toBe('B\nA');
+ expect(git(viaDrag, ['show', 'HEAD:c.txt'])).toBe('C');
+ });
+});
+
+function fileFeature(): string {
+ const dir = fixture();
+ git(dir, ['switch', 'feature']);
+ writeFileSync(join(dir, 'note.txt'), 'from feature\n');
+ git(dir, ['add', 'note.txt']);
+ git(dir, ['commit', '-m', 'add note']);
+ git(dir, ['switch', 'main']);
+ return dir;
+}
+
+function pushFixture(): { local: string } {
+ const root = mkdtempSync(join(tmpdir(), 'strand-drag-push-'));
+ roots.push(root);
+ const remote = join(root, 'origin.git');
+ const local = join(root, 'local');
+ mkdirSync(local, { recursive: true });
+ git(root, ['init', '--bare', '-b', 'main', remote]);
+ git(local, ['init', '-b', 'main']);
+ git(local, ['commit', '--allow-empty', '-m', 'root']);
+ git(local, ['remote', 'add', 'origin', remote]);
+ git(local, ['push', '--set-upstream', 'origin', 'HEAD']);
+ git(local, ['switch', '-c', 'feature']);
+ git(local, ['commit', '--allow-empty', '-m', 'feature change']);
+ return { local };
+}
+
+function linearFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'strand-drag-line-'));
+ roots.push(dir);
+ git(dir, ['init', '-b', 'main']);
+ for (const name of ['A', 'B', 'C'] as const) {
+ writeFileSync(join(dir, `${name.toLowerCase()}.txt`), `${name}\n`);
+ git(dir, ['add', `${name.toLowerCase()}.txt`]);
+ git(dir, ['commit', '-m', name]);
+ }
+ return dir;
+}
+
+function tip(dir: string): { a: string; b: string; c: string } {
+ return {
+ c: git(dir, ['rev-parse', 'HEAD']),
+ b: git(dir, ['rev-parse', 'HEAD~1']),
+ a: git(dir, ['rev-parse', 'HEAD~2']),
+ };
+}
+
+function rebaseIntent(dir: string, mode: 'reorder' | 'squash') {
+ const { a, b, c } = tip(dir);
+ const intent = resolveRebaseDrop(
+ commitDragFromRows([{ hash: c, short: 'ccc3333', parents: [b], index: 0, rewrite: true }])!,
+ {
+ kind: 'commit',
+ hash: b,
+ short: 'bbb2222',
+ parents: [a],
+ index: 1,
+ zone: mode === 'squash' ? 'squash' : 'after',
+ rewrite: true,
+ },
+ null,
+ );
+ if (!intent?.seed.base) throw new Error('expected a rebase base');
+ return intent;
+}
+
+function rebasePlan(dir: string, mode: 'reorder' | 'squash') {
+ const intent = rebaseIntent(dir, mode);
+ const entries = git(dir, ['log', '--reverse', '--format=%H', `${intent.seed.base}..HEAD`])
+ .split('\n')
+ .filter(Boolean)
+ .map((oid) => ({ oid }));
+ const steps = applyRebaseSeed(entries, intent.seed);
+ if (!steps) throw new Error('seed did not apply');
+ return { base: intent.seed.base!, steps };
+}
+
+function handPlan(dir: string, mode: 'reorder' | 'squash') {
+ const { b, c } = tip(dir);
+ return {
+ base: `${b}^`,
+ steps: mode === 'squash'
+ ? [{ oid: b, action: 'pick' as const }, { oid: c, action: 'squash' as const }]
+ : [{ oid: c, action: 'pick' as const }, { oid: b, action: 'pick' as const }],
+ };
+}
+
+function runRebase(dir: string, base: string, steps: { oid: string; action: string }[]) {
+ const editor = join(dir, 'seq.mjs');
+ writeFileSync(
+ editor,
+ `import { writeFileSync } from 'node:fs';\nconst steps = ${JSON.stringify(steps)};\nwriteFileSync(process.argv[2], steps.map((step) => step.action + ' ' + step.oid).join('\\n') + '\\n');\n`,
+ );
+ execFileSync('git', ['-c', 'commit.gpgsign=false', 'rebase', '-i', '--', base], {
+ cwd: dir,
+ encoding: 'utf8',
+ env: { ...env, GIT_SEQUENCE_EDITOR: `node ${editor}` },
+ });
+}
+
+function pushed(local: string): string {
+ return [
+ git(local, ['rev-parse', 'feature']),
+ git(local, ['rev-parse', 'refs/remotes/origin/feature']),
+ git(local, ['config', '--get', 'branch.feature.remote']),
+ git(local, ['config', '--get', 'branch.feature.merge']),
+ ].join('\n');
+}
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 2e5ce2a..04bfef3 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -16,6 +16,7 @@ import { ProgressPopup, formatDuration } from './components/ProgressPopup';
import { PullRequestMonitor } from './components/PullRequestMonitor';
import { RepoRail } from './components/RepoRail';
import { RepositoryFiles } from './components/RepositoryFiles';
+import { GitDragHost } from './components/GitDragHost';
import { Sidebar } from './components/Sidebar';
import { StatusBar } from './components/StatusBar';
import { Topbar } from './components/Topbar';
@@ -33,6 +34,7 @@ import { accentHueForColor, groupTabs, pathKey, repoFamilyName, workspaceMemberS
import { buildContentReportUrl, buildCrashIssueUrl } from './lib/crashReport';
import { pickCodeWorkspaceFile, pickRepoDirectories } from './lib/dialog';
import { editorTemplate, osType, terminalTemplate } from './lib/integrations';
+import type { RebaseSeed } from './lib/gitDrag';
import { t } from './lib/i18n';
import { LFS_ACTIONS } from './lib/lfs';
import { SUBMODULE_ACTIONS, type SubmoduleDialogAction } from './lib/submodules';
@@ -435,10 +437,18 @@ export function App() {
const [renameBranchDialog, setRenameBranchDialog] = useState<{ name: string } | null>(null);
const [branchNetworkDialog, setBranchNetworkDialog] = useState(null);
// null = closed; otherwise the branch to merge (`source`) into the current (`into`).
- const [mergeDialog, setMergeDialog] = useState<{ source: string; into: string } | null>(null);
+ const [mergeDialog, setMergeDialog] = useState<{
+ source: string;
+ into: string;
+ wrap?: (step: () => Promise) => Promise;
+ } | null>(null);
// null = closed; otherwise the interactive-rebase base (revspec before the
// first editable commit, null ⇒ root) + a short label for the blurb.
- const [rebaseDialog, setRebaseDialog] = useState<{ base: string | null; label: string } | null>(null);
+ const [rebaseDialog, setRebaseDialog] = useState<{
+ base: string | null;
+ label: string;
+ seed?: RebaseSeed | null;
+ } | null>(null);
const [amendInto, setAmendInto] = useState<{ target: string; label: string; subject: string } | null>(null);
// null = closed; otherwise the commit-ish to reset to + its human label.
const [resetDialog, setResetDialog] = useState<{ target: string; label: string } | null>(null);
@@ -2790,15 +2800,23 @@ export function App() {
setMergeDialog(null)}
onToast={showToast}
/>
)}
+ setMergeDialog(request)}
+ onPush={(request) => { void onPushBranch(request); }}
+ onOpenRebase={(request) => setRebaseDialog(request)}
+ onToast={showToast}
+ />
{rebaseDialog && (
setRebaseDialog(null)}
onToast={showToast}
/>
diff --git a/ui/src/components/GitDragHost.tsx b/ui/src/components/GitDragHost.tsx
new file mode 100644
index 0000000..4ec6c89
--- /dev/null
+++ b/ui/src/components/GitDragHost.tsx
@@ -0,0 +1,494 @@
+import { useEffect, useRef, useState } from 'react';
+
+import {
+ beginDrag,
+ branchFromDataset,
+ commitDragFromRows,
+ commitFromDataset,
+ commitZone,
+ dragCursor,
+ dragGhost,
+ finishDrag,
+ hitFromDataset,
+ moveDrag,
+ resolveGitDrop,
+ runAfterDropCheckout,
+ type BranchIntent,
+ type CherryPickIntent,
+ type DragCommit,
+ type DragSession,
+ type DragSource,
+ type DropHit,
+ type DropIntent,
+ type HistoryOperation,
+ type PushIntent,
+ type RebaseSeed,
+} from '../lib/gitDrag';
+import { t } from '../lib/i18n';
+import { errMessage } from '../lib/tauri';
+import type { BranchPushRequest, Commit } from '../lib/types';
+import { useRepo } from '../stores/repo';
+import { Dialog } from './Dialog';
+import { MainlineDialog } from '../views/MainlineDialog';
+import { RebaseOntoDialog } from '../views/RebaseOntoDialog';
+
+/**
+ * Pointer-drag for sidebar Git rows. Mirrors the Files-tree drag: a movement
+ * threshold, window-level move/up listeners, and a cursor-chasing ghost.
+ * HTML5 drag events are not used (WebView2 owns those for folder drops).
+ * Escape and a no-drop release never call merge or rebase.
+ */
+export function GitDragHost({
+ onOpenMerge,
+ onPush,
+ onOpenRebase,
+ onToast,
+}: {
+ onOpenMerge: (request: {
+ source: string;
+ into: string;
+ wrap?: (step: () => Promise) => Promise;
+ }) => void;
+ onPush: (request: BranchPushRequest) => void;
+ onOpenRebase: (request: { base: string | null; label: string; seed: RebaseSeed }) => void;
+ onToast: (message: string, kind?: 'success' | 'error') => void;
+}) {
+ const operation = useRepo((s) => s.meta?.operation ?? null);
+ const checkout = useRepo((s) => s.checkout);
+ const cherryPick = useRepo((s) => s.cherryPick);
+ const [mainline, setMainline] = useState(null);
+ // Drag-rebase opens the same RebaseOntoDialog as the sidebar Rebase menu,
+ // so the --update-refs choice and branch preview apply to drops too.
+ const [rebaseOnto, setRebaseOnto] = useState(null);
+ const [pending, setPending] = useState(null);
+ const pendingRef = useRef(pending);
+ pendingRef.current = pending;
+ const mainlineRef = useRef(mainline);
+ mainlineRef.current = mainline;
+ const rebaseOntoRef = useRef(rebaseOnto);
+ rebaseOntoRef.current = rebaseOnto;
+ const operationRef = useRef(operation);
+ operationRef.current = operation;
+ const openMergeRef = useRef(onOpenMerge);
+ openMergeRef.current = onOpenMerge;
+ const openRebaseRef = useRef(onOpenRebase);
+ openRebaseRef.current = onOpenRebase;
+ const checkoutRef = useRef(checkout);
+ checkoutRef.current = checkout;
+ // Check out the drop's branch, run the step, and switch back if it fails
+ // without leaving an operation paused there.
+ const onBranch = (branch: string | null, step: () => Promise): Promise => {
+ const meta = useRepo.getState().meta;
+ const original = meta && !meta.detached ? meta.branch : null;
+ return runAfterDropCheckout(branch, original, (name) => checkoutRef.current(name), step, async () => {
+ await useRepo.getState().refreshMeta();
+ return useRepo.getState().meta?.operation ?? null;
+ });
+ };
+
+ useEffect(() => {
+ let session: DragSession = { status: 'idle' };
+ let ghost: HTMLDivElement | null = null;
+ let hover: HTMLElement | null = null;
+ let suppressClick = false;
+ let detachMove = () => {};
+
+ const clearVisual = () => {
+ ghost?.remove();
+ ghost = null;
+ if (hover) delete hover.dataset.gitDropHover;
+ hover = null;
+ document.documentElement.classList.remove('git-drag-valid', 'git-drag-invalid');
+ document.body.style.userSelect = '';
+ };
+
+ const paint = (next: DragSession, x: number, y: number) => {
+ if (next.status !== 'dragging') return;
+ document.body.style.userSelect = 'none';
+ const cursor = dragCursor(next.intent);
+ document.documentElement.classList.toggle('git-drag-valid', cursor === 'copy');
+ document.documentElement.classList.toggle('git-drag-invalid', cursor === 'no-drop');
+ const row = document.elementFromPoint(x, y)?.closest('[data-git-drop]') ?? null;
+ if (hover !== row) {
+ if (hover) delete hover.dataset.gitDropHover;
+ hover = row;
+ }
+ if (hover) {
+ if (next.intent) hover.dataset.gitDropHover = 'valid';
+ else delete hover.dataset.gitDropHover;
+ }
+ if (!ghost) {
+ ghost = document.createElement('div');
+ ghost.className = 'tree-drag-ghost';
+ document.body.appendChild(ghost);
+ }
+ ghost.style.left = `${x + 14}px`;
+ ghost.style.top = `${y + 10}px`;
+ ghost.classList.toggle('invalid', !next.intent);
+ const ghostLabel = next.intent ? dragGhost(next.intent) : null;
+ ghost.textContent = ghostLabel
+ ? t('drag.git.ghost', ghostLabel)
+ : dragSourceLabel(next.source);
+ };
+
+ const end = () => {
+ detachMove();
+ detachMove = () => {};
+ session = { status: 'idle' };
+ clearVisual();
+ };
+
+ const onClick = (event: MouseEvent) => {
+ if (!suppressClick) return;
+ suppressClick = false;
+ event.preventDefault();
+ event.stopPropagation();
+ };
+
+ const onMouseDown = (event: MouseEvent) => {
+ if (event.button !== 0 || pendingRef.current || mainlineRef.current || rebaseOntoRef.current) return;
+ const target = event.target;
+ if (!(target instanceof Element)) return;
+ if (target.closest('input, textarea, select, .palette-backdrop, .context-menu, .context-menu-backdrop')) return;
+ const row = target.closest('[data-git-source]');
+ if (!row) return;
+ const source = readDragSource(row);
+ if (!source) return;
+ session = beginDrag(source, event.clientX, event.clientY);
+
+ const onMove = (ev: MouseEvent) => {
+ const intent = resolveGitDrop(source, readDropHit(ev.clientX, ev.clientY), operationRef.current);
+ const previous = session.status;
+ session = moveDrag(session, { x: ev.clientX, y: ev.clientY, intent });
+ if (session.status !== 'dragging') return;
+ if (previous !== 'dragging') suppressClick = true;
+ ev.preventDefault();
+ paint(session, ev.clientX, ev.clientY);
+ };
+ const onUp = (ev: MouseEvent) => {
+ const intent = resolveGitDrop(source, readDropHit(ev.clientX, ev.clientY), operationRef.current);
+ const chosen = session.status === 'dragging'
+ ? finishDrag({ status: 'dragging', source: session.source, intent }, true)
+ : null;
+ end();
+ if (chosen?.kind === 'rebase') {
+ openRebaseRef.current({ base: chosen.seed.base, label: chosen.seed.baseLabel, seed: chosen.seed });
+ return;
+ }
+ if (chosen) setPending(chosen);
+ };
+ const onKey = (ev: KeyboardEvent) => {
+ if (ev.key !== 'Escape') return;
+ ev.preventDefault();
+ finishDrag(session, false);
+ end();
+ };
+ detachMove = () => {
+ window.removeEventListener('mousemove', onMove, true);
+ window.removeEventListener('mouseup', onUp, true);
+ window.removeEventListener('keydown', onKey, true);
+ };
+ window.addEventListener('mousemove', onMove, true);
+ window.addEventListener('mouseup', onUp, true);
+ window.addEventListener('keydown', onKey, true);
+ };
+
+ window.addEventListener('mousedown', onMouseDown, true);
+ window.addEventListener('click', onClick, true);
+ return () => {
+ window.removeEventListener('mousedown', onMouseDown, true);
+ window.removeEventListener('click', onClick, true);
+ end();
+ };
+ }, []);
+
+ if (mainline?.mainline) {
+ const picked = mainline.mainline;
+ const checkoutName = mainline.checkout;
+ return (
+ onBranch(checkoutName, step) : undefined}
+ onClose={() => setMainline(null)}
+ onToast={onToast}
+ />
+ );
+ }
+
+ if (rebaseOnto) {
+ const intent = rebaseOnto;
+ const checkoutName = intent.checkout;
+ return (
+ onBranch(checkoutName, step) : undefined}
+ onClose={() => setRebaseOnto(null)}
+ onToast={onToast}
+ />
+ );
+ }
+
+ if (!pending) return null;
+ const dismiss = () => setPending(null);
+ if (pending.kind === 'cherry-pick') {
+ return (
+ {
+ const intent = pending;
+ dismiss();
+ if (intent.blockedMerge) return;
+ if (intent.mainline) {
+ setMainline(intent);
+ return;
+ }
+ void (async () => {
+ try {
+ const conflicted = await onBranch(intent.checkout, () => cherryPick(intent.hashes));
+ onToast(
+ conflicted
+ ? t('drag.git.cherryConflict', { label: intent.label })
+ : intent.hashes.length > 1
+ ? t('drag.git.cherryDoneMany', { count: intent.hashes.length })
+ : t('drag.git.cherryDone', { label: intent.label }),
+ );
+ } catch (caught) {
+ onToast(t('drag.git.cherryFailed', { error: errMessage(caught) }), 'error');
+ }
+ })();
+ }}
+ />
+ );
+ }
+ if (pending.kind === 'push') {
+ return (
+ {
+ dismiss();
+ onPush(request);
+ }}
+ />
+ );
+ }
+ if (pending.kind !== 'branch') return null;
+ return (
+ {
+ const checkoutName = pending.checkout;
+ dismiss();
+ openMergeRef.current({
+ source: pending.mergeRef,
+ into: pending.mergeInto,
+ wrap: checkoutName ? (step) => onBranch(checkoutName, step) : undefined,
+ });
+ }}
+ onRebase={() => {
+ const intent = pending;
+ dismiss();
+ setRebaseOnto(intent);
+ }}
+ />
+ );
+}
+
+function dragSourceLabel(source: DragSource): string {
+ if (source.kind !== 'commits') return source.label;
+ if (source.commits.length === 1) return source.commits[0].short;
+ return t('drag.git.commitCount', { count: source.commits.length });
+}
+
+function readDragSource(row: HTMLElement): DragSource | null {
+ const branch = branchFromDataset(row.dataset);
+ if (branch) return branch;
+ const commit = commitFromDataset(row.dataset);
+ if (!commit) return null;
+ if (row.dataset.gitSelected !== '1') return commitDragFromRows([commit]);
+ const raw = row.closest('[data-git-selection]')?.dataset.gitSelection;
+ if (raw) {
+ try {
+ const parsed = JSON.parse(raw) as DragCommit[];
+ if (Array.isArray(parsed) && parsed.length > 0 && parsed.every((item) => typeof item?.hash === 'string')) {
+ return {
+ kind: 'commits',
+ commits: parsed.map((item) => ({ ...item, rewrite: item.rewrite === true })),
+ };
+ }
+ } catch {
+ // The visible rows below still name the commits that are on screen.
+ }
+ }
+ const selected = [...document.querySelectorAll('[data-git-source="commit"][data-git-selected="1"]')]
+ .map((element) => commitFromDataset(element.dataset))
+ .filter((item): item is DragCommit => item != null);
+ return commitDragFromRows(selected);
+}
+
+function readDropHit(x: number, y: number): DropHit | null {
+ const element = document.elementFromPoint(x, y)?.closest('[data-git-drop]');
+ if (!element) return null;
+ if (element.dataset.gitDrop === 'commit') {
+ const commit = commitFromDataset(element.dataset);
+ if (!commit) return null;
+ const rect = element.getBoundingClientRect();
+ return { kind: 'commit', ...commit, zone: commitZone(y - rect.top, rect.height) };
+ }
+ return hitFromDataset(element.dataset);
+}
+
+function commitForMainline(commit: NonNullable): Commit {
+ return {
+ hash: commit.hash,
+ short_hash: commit.short,
+ subject: '',
+ body: '',
+ author_name: '',
+ author_email: '',
+ time_unix: 0,
+ parents: commit.parents,
+ };
+}
+
+function CherryPickConfirm({
+ intent,
+ onClose,
+ onConfirm,
+}: {
+ intent: CherryPickIntent;
+ onClose: () => void;
+ onConfirm: () => void;
+}) {
+ return (
+
+ {t('common.cancel')}
+ {intent.blockedMerge ? null : (
+ {t('drag.git.cherryButton')}
+ )}
+ >
+ }
+ >
+
+
+ {t('drag.git.cherryBody', { commits: intent.label, branch: intent.branch })}
+ {intent.checkout ? ` ${t('drag.git.checkoutFirst', { branch: intent.checkout })}` : null}
+
+ {intent.blockedMerge ? (
+
{t('drag.git.cherryMergeBlocked', { hash: intent.blockedMerge })}
+ ) : null}
+
+
+ );
+}
+
+function BranchConfirm({
+ intent,
+ onClose,
+ onMerge,
+ onRebase,
+}: {
+ intent: BranchIntent;
+ onClose: () => void;
+ onMerge: () => void;
+ onRebase: () => void;
+}) {
+ return (
+
+ {t('common.cancel')}
+ {t('drag.git.rebase')}
+ {t('drag.git.merge')}
+ >
+ }
+ >
+
+
+ {t('drag.git.branchBody', {
+ dragged: intent.draggedLabel,
+ dropped: intent.droppedLabel,
+ mergeRef: intent.mergeRef,
+ mergeInto: intent.mergeInto,
+ rebaseBranch: intent.rebaseBranch,
+ rebaseOnto: intent.rebaseOnto,
+ })}
+ {intent.checkout ? ` ${t('drag.git.checkoutFirst', { branch: intent.checkout })}` : null}
+
+
+
+ );
+}
+
+function PushConfirm({
+ intent,
+ onClose,
+ onPush,
+}: {
+ intent: PushIntent;
+ onClose: () => void;
+ onPush: (request: BranchPushRequest) => void;
+}) {
+ const [setUpstream, setSetUpstream] = useState(intent.offerUpstream);
+ const upstream = `${intent.remote}/${intent.remoteBranch}`;
+ return (
+
+ {t('common.cancel')}
+ onPush({
+ branch: intent.branch,
+ remote: intent.remote,
+ remoteBranch: intent.remoteBranch,
+ mode: 'default',
+ setUpstream,
+ })}
+ >
+ {setUpstream ? t('drag.git.pushAndSet') : t('drag.git.pushButton')}
+
+ >
+ }
+ >
+
+
+ {t('drag.git.pushBody', { branch: intent.branch, remote: intent.remote, destination: intent.remoteBranch })}
+
+ {intent.offerUpstream ? (
+
+ setSetUpstream(event.target.checked)}
+ />
+ {t('drag.git.pushUpstream', { upstream, branch: intent.branch })}
+
+ ) : null}
+
+
+ );
+}
diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsx
index 0f138d6..eb4fef4 100644
--- a/ui/src/components/Sidebar.tsx
+++ b/ui/src/components/Sidebar.tsx
@@ -5,6 +5,7 @@ import { userActionMenu } from '../lib/userActions';
import { Icon, type IconName } from './Icon';
import { copyToClipboard } from './PierreTree';
import { RepositoryFiles } from './RepositoryFiles';
+import { upstreamBranchName } from '../lib/gitDrag';
import { t } from '../lib/i18n';
import { formatBinding } from '../lib/keys';
import { customPanes } from '../lib/customView';
@@ -621,6 +622,16 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface
onSelect: () => compareAgainst(rb.name),
});
if (currentBranch) {
+ items.push({
+ label: t('drag.git.menuMerge', { branch: currentBranch }),
+ icon: 'branch',
+ onSelect: () => onMerge(rb.name, currentBranch),
+ });
+ items.push({
+ label: t('drag.git.menuRebase', { branch: currentBranch }),
+ icon: 'rebase',
+ onSelect: () => setRebaseOnto(rb.name),
+ });
items.push({
label: `Pull into ${currentBranch}`,
icon: 'arrow-down',
@@ -936,6 +947,15 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface
depth={depth}
icon={b.is_head ? 'check' : wt ? 'worktree' : 'branch'}
label={b.name}
+ git={{
+ source: 'local-branch',
+ drop: 'local-branch',
+ ref: b.name,
+ label: b.name,
+ head: b.is_head,
+ upstreamRemote: b.upstream?.remote ?? null,
+ upstreamBranch: b.upstream ? upstreamBranchName(b.upstream) : null,
+ }}
meta={wt ? 'worktree' : undefined}
merged={merged}
title={
@@ -967,6 +987,12 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface
return (
void runBranchOp(checkoutCommitProgress(), () => checkoutCommit(tg.target))}
@@ -1151,6 +1178,7 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface
showFolderCount: false,
folderMenu: remoteFolderMenu,
openMenu,
+ remoteDrop: true,
})}
(
* tree's remote-name rows. Opened via `openMenu` (the owner's menu state). */
folderMenu?: (name: string) => MenuItem[];
openMenu?: (x: number, y: number, items: MenuItem[]) => void;
+ /** Depth-0 folders are remotes and accept a local-branch push drop. */
+ remoteDrop?: boolean;
},
): React.ReactNode {
const open = folderOpts?.openMenu;
@@ -1283,6 +1313,7 @@ function renderTreeChildren(
count={folderOpts?.showFolderCount === false ? undefined : child.leaves}
onToggle={() => toggleCollapsed(collapseKey)}
onMenu={menuFor && open ? (x, y) => open(x, y, menuFor(child.name)) : undefined}
+ gitDrop={folderOpts?.remoteDrop && depth === 0 ? { ref: child.name, label: child.name } : undefined}
/>
{!isCollapsed &&
renderTreeChildren(child, depth + 1, collapsed, toggleCollapsed, renderLeaf, keyPrefix, folderOpts)}
@@ -1333,9 +1364,11 @@ interface FolderRowProps {
/** Open the folder's action menu at the given viewport coordinates —
* wired like SideLeaf's (right-click, or ContextMenu / Shift+F10). */
onMenu?: (x: number, y: number) => void;
+ /** Remote root row. Local branches dropped here push. */
+ gitDrop?: { ref: string; label: string };
}
-function FolderRow({ name, depth, collapsed, icon = 'folder', count, onToggle, onMenu }: FolderRowProps) {
+function FolderRow({ name, depth, collapsed, icon = 'folder', count, onToggle, onMenu, gitDrop }: FolderRowProps) {
const rowRef = useRef(null);
const openKeyboardMenu = () => {
const r = rowRef.current?.getBoundingClientRect();
@@ -1347,6 +1380,9 @@ function FolderRow({ name, depth, collapsed, icon = 'folder', count, onToggle, o
type="button"
className={'side-row branch-folder' + (collapsed ? ' collapsed' : '')}
style={{ paddingLeft: 16 + depth * 14 }}
+ data-git-drop={gitDrop ? 'remote' : undefined}
+ data-git-ref={gitDrop?.ref}
+ data-git-label={gitDrop?.label}
onClick={onToggle}
onContextMenu={
onMenu
@@ -1376,10 +1412,21 @@ function FolderRow({ name, depth, collapsed, icon = 'folder', count, onToggle, o
);
}
+interface SideGitDrag {
+ source?: 'local-branch' | 'remote-branch';
+ drop?: 'local-branch' | 'remote-branch' | 'remote' | 'tag';
+ ref: string;
+ label: string;
+ head?: boolean;
+ upstreamRemote?: string | null;
+ upstreamBranch?: string | null;
+}
+
interface SideLeafProps {
depth: number;
icon: IconName;
label: string;
+ git?: SideGitDrag;
/** Muted trailing text (stash branch, "annotated", …). */
meta?: string;
/** Commits ahead of upstream — rendered as a green `N↑`. */
@@ -1406,7 +1453,7 @@ interface SideLeafProps {
* — also lives in a right-click menu opened via `onMenu`. Keyboard users open
* it with the Menu key or Shift+F10, positioned at the row's corner.
*/
-function SideLeaf({ depth, icon, label, meta, ahead = 0, behind = 0, merged, active, title, onActivate, onSelect, onMenu }: SideLeafProps) {
+function SideLeaf({ depth, icon, label, git, meta, ahead = 0, behind = 0, merged, active, title, onActivate, onSelect, onMenu }: SideLeafProps) {
const rowRef = useRef(null);
const openKeyboardMenu = () => {
const r = rowRef.current?.getBoundingClientRect();
@@ -1417,6 +1464,13 @@ function SideLeaf({ depth, icon, label, meta, ahead = 0, behind = 0, merged, act
ref={rowRef}
className={'side-row branch-row' + (active ? ' active' : '')}
style={{ paddingLeft: 16 + depth * 14 }}
+ data-git-source={git?.source}
+ data-git-drop={git?.drop}
+ data-git-ref={git?.ref}
+ data-git-label={git?.label}
+ data-git-head={git?.head ? '1' : undefined}
+ data-git-upstream-remote={git?.upstreamRemote ?? undefined}
+ data-git-upstream-branch={git?.upstreamBranch ?? undefined}
onClick={onSelect}
onDoubleClick={onActivate}
onContextMenu={(e) => {
diff --git a/ui/src/lib/gitDrag.test.ts b/ui/src/lib/gitDrag.test.ts
new file mode 100644
index 0000000..8947acc
--- /dev/null
+++ b/ui/src/lib/gitDrag.test.ts
@@ -0,0 +1,442 @@
+import { describe, expect, it } from 'vitest';
+
+import { t } from './i18n';
+
+import {
+ beginDrag,
+ branchFromDataset,
+ cherryPickGitArgs,
+ commitDragFromRows,
+ commitFromDataset,
+ commitIndexByHash,
+ commitZone,
+ dragBlocksHistory,
+ dragCursor,
+ dragMergeArgs,
+ dragRebaseArgs,
+ finishDrag,
+ hitFromDataset,
+ MENU_MERGE_PREFIX,
+ MENU_REBASE_PREFIX,
+ moveDrag,
+ pushGitArgs,
+ resolveBranchDrop,
+ rebaseSeedMessageKey,
+ resolveCherryPick,
+ resolveGitDrop,
+ resolvePushDrop,
+ resolveRebaseDrop,
+ runAfterDropCheckout,
+ linearTipHashes,
+ upstreamBranchName,
+ type BranchHit,
+ type DragBranch,
+} from './gitDrag';
+
+const feature: DragBranch = {
+ kind: 'local-branch',
+ ref: 'feature',
+ label: 'feature',
+ isHead: false,
+ upstreamRemote: null,
+ upstreamBranch: null,
+};
+const mainHit: BranchHit = { kind: 'local-branch', ref: 'main', label: 'main', isHead: true };
+const featureHit: BranchHit = { kind: 'local-branch', ref: 'feature', label: 'feature', isHead: false };
+const originMain: BranchHit = { kind: 'remote-branch', ref: 'origin/main', label: 'origin/main', isHead: false };
+const originFeature: DragBranch = {
+ kind: 'remote-branch',
+ ref: 'origin/feature',
+ label: 'origin/feature',
+ isHead: false,
+ upstreamRemote: null,
+ upstreamBranch: null,
+};
+
+describe('drop-target resolution', () => {
+ it('reads branch rows and tag/remote hits from dataset attributes', () => {
+ expect(branchFromDataset({
+ gitSource: 'local-branch',
+ gitRef: 'feature',
+ gitLabel: 'feature',
+ gitHead: '1',
+ gitUpstreamRemote: 'origin',
+ gitUpstreamBranch: 'feature',
+ })).toEqual({
+ kind: 'local-branch',
+ ref: 'feature',
+ label: 'feature',
+ isHead: true,
+ upstreamRemote: 'origin',
+ upstreamBranch: 'feature',
+ });
+ expect(hitFromDataset({ gitDrop: 'tag', gitRef: 'refs/tags/v1', gitLabel: 'v1' })).toEqual({
+ kind: 'tag',
+ ref: 'refs/tags/v1',
+ label: 'v1',
+ isHead: false,
+ });
+ expect(branchFromDataset({ gitSource: 'commit' })).toBeNull();
+ expect(hitFromDataset({})).toBeNull();
+ });
+
+ it('drops feature on main as merge-into-main and rebase-main-onto-feature', () => {
+ const intent = resolveBranchDrop(feature, mainHit, null);
+ expect(intent).toMatchObject({
+ draggedRef: 'feature',
+ droppedRef: 'main',
+ checkout: null,
+ mergeRef: 'feature',
+ mergeInto: 'main',
+ rebaseOnto: 'feature',
+ rebaseBranch: 'main',
+ });
+ expect(dragMergeArgs(intent!)).toEqual([...MENU_MERGE_PREFIX, 'feature']);
+ expect(dragRebaseArgs(intent!)).toEqual([...MENU_REBASE_PREFIX, 'feature']);
+ expect(dragCursor(intent)).toBe('copy');
+ expect(t('drag.git.branchBody', {
+ dragged: intent!.draggedLabel,
+ dropped: intent!.droppedLabel,
+ mergeRef: intent!.mergeRef,
+ mergeInto: intent!.mergeInto,
+ rebaseBranch: intent!.rebaseBranch,
+ rebaseOnto: intent!.rebaseOnto,
+ })).toBe('Dropped feature on main. Merge feature into main, or rebase main onto feature.');
+ });
+
+ it('swaps the verbs when main is dropped on feature', () => {
+ const main: DragBranch = { ...feature, ref: 'main', label: 'main', isHead: true };
+ expect(resolveBranchDrop(main, featureHit, null)).toMatchObject({
+ checkout: 'feature',
+ mergeRef: 'main',
+ mergeInto: 'feature',
+ rebaseOnto: 'main',
+ rebaseBranch: 'feature',
+ });
+ });
+
+ it('merges a remote branch into the local target and rebases the target onto it', () => {
+ expect(resolveBranchDrop(originFeature, mainHit, null)).toMatchObject({
+ checkout: null,
+ mergeRef: 'origin/feature',
+ mergeInto: 'main',
+ rebaseOnto: 'origin/feature',
+ rebaseBranch: 'main',
+ });
+ });
+
+ it('moves the local branch when it is dropped on a remote-tracking branch', () => {
+ const headFeature: DragBranch = { ...feature, isHead: true };
+ expect(resolveBranchDrop(headFeature, originMain, null)).toMatchObject({
+ checkout: null,
+ mergeRef: 'origin/main',
+ mergeInto: 'feature',
+ rebaseOnto: 'origin/main',
+ rebaseBranch: 'feature',
+ });
+ const other: DragBranch = { ...feature, isHead: false };
+ expect(resolveBranchDrop(other, originMain, null)?.checkout).toBe('feature');
+ });
+
+ it('rejects a branch dropped on itself, on a tag, on a remote, or onto another remote branch', () => {
+ expect(resolveBranchDrop(feature, { ...featureHit }, null)).toBeNull();
+ expect(resolveBranchDrop(feature, { kind: 'tag', ref: 'refs/tags/v1', label: 'v1', isHead: false }, null)).toBeNull();
+ expect(resolveBranchDrop(feature, { kind: 'remote', ref: 'origin', label: 'origin', isHead: false }, null)).toBeNull();
+ expect(resolveBranchDrop(originFeature, originMain, null)).toBeNull();
+ expect(dragCursor(null)).toBe('no-drop');
+ });
+
+ it('rejects every drop while any Git operation is in progress', () => {
+ expect(dragBlocksHistory(null)).toBe(false);
+ for (const op of ['merge', 'rebase', 'cherry-pick', 'revert', 'mailbox', 'bisect'] as const) {
+ expect(dragBlocksHistory(op)).toBe(true);
+ expect(resolveBranchDrop(feature, mainHit, op)).toBeNull();
+ expect(resolveGitDrop(feature, mainHit, op)).toBeNull();
+ }
+ });
+
+ it('pushes a local branch onto a remote and offers to create a missing upstream', () => {
+ const origin: BranchHit = { kind: 'remote', ref: 'origin', label: 'origin', isHead: false };
+ const intent = resolvePushDrop(feature, origin, null);
+ expect(intent).toEqual({
+ kind: 'push',
+ branch: 'feature',
+ remote: 'origin',
+ remoteBranch: 'feature',
+ offerUpstream: true,
+ });
+ const menu = ['push', '--progress', '--set-upstream', '--', 'origin', 'refs/heads/feature:refs/heads/feature'];
+ expect(pushGitArgs(intent!, true)).toEqual(menu);
+ expect(resolveGitDrop(feature, origin, null)).toEqual(intent);
+ expect(t('drag.git.pushBody', { branch: 'feature', remote: 'origin', destination: 'feature' }))
+ .toBe('Push feature to origin/feature.');
+ expect(t('drag.git.pushUpstream', { upstream: 'origin/feature', branch: 'feature' }))
+ .toBe('Set origin/feature as the upstream for feature.');
+ });
+
+ it('keeps an existing upstream on that remote and does not prompt to create one', () => {
+ const tracked: DragBranch = {
+ ...feature,
+ upstreamRemote: 'origin',
+ upstreamBranch: 'feature',
+ };
+ expect(resolvePushDrop(tracked, { kind: 'remote', ref: 'origin', label: 'origin', isHead: false }, null))
+ .toMatchObject({ remoteBranch: 'feature', offerUpstream: false });
+ const elsewhere: DragBranch = { ...feature, upstreamRemote: 'other', upstreamBranch: 'feature' };
+ expect(resolvePushDrop(elsewhere, { kind: 'remote', ref: 'origin', label: 'origin', isHead: false }, null))
+ .toMatchObject({ remoteBranch: 'feature', offerUpstream: false });
+ });
+
+ it('does not push a remote-tracking branch or push while a rebase is paused', () => {
+ const origin: BranchHit = { kind: 'remote', ref: 'origin', label: 'origin', isHead: false };
+ expect(resolvePushDrop(originFeature, origin, null)).toBeNull();
+ expect(resolveGitDrop(feature, origin, 'rebase')).toBeNull();
+ expect(resolveGitDrop(feature, origin, 'merge')).toBeNull();
+ });
+
+ it('cherry-picks dragged commits onto a local branch, oldest first', () => {
+ const older = { hash: 'aaa', short: 'aaa1111', parents: ['root'], index: 2, rewrite: true };
+ const newer = { hash: 'bbb', short: 'bbb2222', parents: ['aaa'], index: 0, rewrite: true };
+ const source = commitDragFromRows([newer, older]);
+ expect(source?.commits.map((commit) => commit.hash)).toEqual(['aaa', 'bbb']);
+ const intent = resolveCherryPick(source!, mainHit, null);
+ expect(intent).toMatchObject({
+ hashes: ['aaa', 'bbb'],
+ label: 'aaa1111, bbb2222',
+ branch: 'main',
+ checkout: null,
+ mainline: null,
+ blockedMerge: null,
+ });
+ expect(cherryPickGitArgs(intent!.hashes)).toEqual(['cherry-pick', '--', 'aaa', 'bbb']);
+ expect(t('drag.git.cherryBody', { commits: intent!.label, branch: 'main' }))
+ .toBe('Cherry-pick aaa1111, bbb2222 onto main.');
+ const other: BranchHit = { kind: 'local-branch', ref: 'feature', label: 'feature', isHead: false };
+ expect(resolveCherryPick(source!, other, null)?.checkout).toBe('feature');
+ });
+
+ it('sends a single merge commit through the mainline dialog and blocks a mixed selection', () => {
+ const merge = commitDragFromRows([{ hash: 'mmm', short: 'mmm3333', parents: ['a', 'b'], index: 0, rewrite: false }])!;
+ expect(resolveCherryPick(merge, mainHit, null)?.mainline).toEqual({
+ hash: 'mmm', short: 'mmm3333', parents: ['a', 'b'],
+ });
+ const mixed = commitDragFromRows([
+ { hash: 'mmm', short: 'mmm3333', parents: ['a', 'b'], index: 1, rewrite: false },
+ { hash: 'ccc', short: 'ccc4444', parents: ['mmm'], index: 0, rewrite: true },
+ ])!;
+ expect(resolveCherryPick(mixed, mainHit, null)?.blockedMerge).toBe('mmm3333');
+ expect(resolveCherryPick(mixed, originMain, null)).toBeNull();
+ expect(resolveCherryPick(mixed, mainHit, 'merge')).toBeNull();
+ });
+
+ it('reads commit rows and classifies squash versus reorder zones', () => {
+ expect(commitFromDataset({
+ gitSource: 'commit',
+ gitHash: 'abc',
+ gitShort: 'abc1234',
+ gitParents: 'p1 p2',
+ gitIndex: '4',
+ })).toEqual({ hash: 'abc', short: 'abc1234', parents: ['p1', 'p2'], index: 4, rewrite: false });
+ expect(commitZone(2, 28)).toBe('before');
+ expect(commitZone(14, 28)).toBe('squash');
+ expect(commitZone(26, 28)).toBe('after');
+ expect(resolveGitDrop(
+ commitDragFromRows([{ hash: 'abc', short: 'abc1234', parents: ['p'], index: 1, rewrite: true }])!,
+ { kind: 'tag', ref: 'refs/tags/v1', label: 'v1', isHead: false },
+ null,
+ )).toBeNull();
+ });
+
+ it('opens a prefilled rebase when a linear-tip commit is reordered or squashed', () => {
+ const older = { hash: 'bbb', short: 'bbb2222', parents: ['aaa'], index: 1, rewrite: true };
+ const newer = { hash: 'ccc', short: 'ccc3333', parents: ['bbb'], index: 0, rewrite: true };
+ const source = commitDragFromRows([newer])!;
+ const ontoOlder = resolveRebaseDrop(source, { ...older, kind: 'commit', zone: 'after' }, null);
+ expect(ontoOlder?.seed).toMatchObject({
+ move: ['ccc'],
+ mode: 'reorder',
+ anchor: 'bbb',
+ place: 'before',
+ base: 'bbb^',
+ baseLabel: 'bbb2222',
+ });
+ expect(t(rebaseSeedMessageKey(ontoOlder!.seed), {
+ commits: ontoOlder!.seed.moveLabel,
+ target: ontoOlder!.seed.anchorLabel,
+ })).toBe('Move ccc3333 to be older than bbb2222. Review this rebase plan — nothing runs until you start it.');
+ const squash = resolveRebaseDrop(source, { ...older, kind: 'commit', zone: 'squash' }, null);
+ expect(squash?.seed.mode).toBe('squash');
+ expect(squash?.seed.place).toBe('after');
+ expect(t(rebaseSeedMessageKey(squash!.seed), {
+ commits: squash!.seed.moveLabel,
+ target: squash!.seed.anchorLabel,
+ })).toBe('Squash ccc3333 into bbb2222. Review this rebase plan — nothing runs until you start it.');
+ });
+
+ it('rejects a no-op reorder, a drop on itself, an off-tip commit, and a paused rebase', () => {
+ const older = { hash: 'bbb', short: 'bbb2222', parents: ['aaa'], index: 1, rewrite: true };
+ const newer = { hash: 'ccc', short: 'ccc3333', parents: ['bbb'], index: 0, rewrite: true };
+ const source = commitDragFromRows([newer])!;
+ expect(resolveRebaseDrop(source, { ...older, kind: 'commit', zone: 'before' }, null)).toBeNull();
+ expect(resolveRebaseDrop(source, { ...newer, kind: 'commit', zone: 'squash' }, null)).toBeNull();
+ expect(resolveRebaseDrop(source, { ...older, kind: 'commit', zone: 'after', rewrite: false }, null)).toBeNull();
+ expect(resolveRebaseDrop(commitDragFromRows([{ ...newer, rewrite: false }])!, {
+ ...older, kind: 'commit', zone: 'after',
+ }, null)).toBeNull();
+ expect(resolveRebaseDrop(source, { ...older, kind: 'commit', zone: 'after' }, 'rebase')).toBeNull();
+ expect(resolveRebaseDrop(source, { ...older, kind: 'commit', zone: 'squash' }, 'merge')).toBeNull();
+ const commits = [
+ { hash: 'mmm', parents: ['aaa', 'zzz'] },
+ { hash: 'ccc', parents: ['mmm'] },
+ { hash: 'bbb', parents: ['aaa'] },
+ { hash: 'aaa', parents: [] },
+ ];
+ expect([...linearTipHashes(commits, 'ccc')]).toEqual(['ccc']);
+ expect([...linearTipHashes(commits, 'bbb')]).toEqual(['bbb', 'aaa']);
+ });
+
+ it('orders a multi-selection by commit-list index, not graph row', () => {
+ // Graph rows interleave stashes; row numbers would be c3=1, c2=3, c1=4
+ // while the selection uses commit-list positions.
+ const rows = [
+ { hash: 's0', stash: { index: 0 } },
+ { hash: 'c3' },
+ { hash: 's1', stash: { index: 1 } },
+ { hash: 'c2' },
+ { hash: 'c1' },
+ ];
+ const commits = rows.filter((row) => !row.stash).map((row) => row.hash);
+ const index = commitIndexByHash(rows);
+ expect([...index]).toEqual(commits.map((hash, at) => [hash, at]));
+ const row = (hash: string, parent: string) => (
+ { hash, short: hash, parents: [parent], index: index.get(hash)!, rewrite: true }
+ );
+ const c3 = row('c3', 'c2');
+ const c2 = row('c2', 'c1');
+ const c1 = row('c1', 'c0');
+ const intent = resolveRebaseDrop(commitDragFromRows([c3, c1])!, { ...c2, kind: 'commit', zone: 'squash' }, null);
+ expect(intent?.seed.base).toBe('c1^');
+ expect(intent?.seed.move).toEqual(['c1', 'c3']);
+ });
+
+ it('splits an upstream short name after the remote', () => {
+ expect(upstreamBranchName({ name: 'origin/feature/auth', remote: 'origin' })).toBe('feature/auth');
+ expect(upstreamBranchName({ name: 'feature', remote: 'origin' })).toBe('feature');
+ });
+});
+
+describe('drag confirm gate', () => {
+ it('Escape cancels an in-progress drag with no intent', () => {
+ let session = beginDrag(feature, 0, 0);
+ session = moveDrag(session, { x: 20, y: 0, intent: resolveBranchDrop(feature, mainHit, null) });
+ expect(session.status).toBe('dragging');
+ expect(finishDrag(session, false)).toBeNull();
+ });
+
+ it('a release before the threshold, or over a rejected target, confirms nothing', () => {
+ const armed = beginDrag(feature, 10, 10);
+ expect(moveDrag(armed, { x: 12, y: 10, intent: null }).status).toBe('armed');
+ expect(finishDrag(armed, true)).toBeNull();
+ const dragging = moveDrag(armed, { x: 40, y: 10, intent: null });
+ expect(finishDrag(dragging, true)).toBeNull();
+ });
+
+ it('a release over a branch confirms that drop and nothing earlier', () => {
+ const armed = beginDrag(feature, 0, 0);
+ const dragging = moveDrag(armed, {
+ x: 8,
+ y: 0,
+ intent: resolveBranchDrop(feature, mainHit, null),
+ });
+ const chosen = finishDrag(dragging, true);
+ expect(chosen?.kind).toBe('branch');
+ if (chosen?.kind === 'branch') expect(chosen.mergeRef).toBe('feature');
+ });
+
+ it('Escape cancels a reorder drag before the rebase editor opens', () => {
+ const newer = { hash: 'ccc', short: 'ccc3333', parents: ['bbb'], index: 0, rewrite: true };
+ const older = { hash: 'bbb', short: 'bbb2222', parents: ['aaa'], index: 1, rewrite: true };
+ const intent = resolveRebaseDrop(
+ commitDragFromRows([newer])!,
+ { ...older, kind: 'commit', zone: 'after' },
+ null,
+ );
+ let session = beginDrag(commitDragFromRows([newer])!, 0, 0);
+ session = moveDrag(session, { x: 20, y: 0, intent });
+ expect(finishDrag(session, false)).toBeNull();
+ expect(finishDrag(session, true)?.kind).toBe('rebase');
+ });
+});
+
+describe('drop checkout', () => {
+ const idle = async () => null;
+
+ it('runs the step on the current branch without a checkout', async () => {
+ const calls: string[] = [];
+ const result = await runAfterDropCheckout(null, 'main', async (name) => { calls.push(name); }, async () => 'ok', idle);
+ expect(result).toBe('ok');
+ expect(calls).toEqual([]);
+ });
+
+ it('keeps the target branch when the step succeeds or pauses', async () => {
+ const calls: string[] = [];
+ const paused = await runAfterDropCheckout(
+ 'feature', 'main', async (name) => { calls.push(name); }, async () => true, idle,
+ );
+ expect(paused).toBe(true);
+ expect(calls).toEqual(['feature']);
+ });
+
+ it('switches back to the original branch when the step fails', async () => {
+ const calls: string[] = [];
+ await expect(runAfterDropCheckout('feature', 'main', async (name) => { calls.push(name); }, async () => {
+ throw { message: 'boom' };
+ }, idle)).rejects.toEqual({ message: t('drag.git.restored', { error: 'boom', branch: 'main' }) });
+ expect(calls).toEqual(['feature', 'main']);
+ });
+
+ it('stays on the target branch when the failure left an operation in progress', async () => {
+ for (const op of ['cherry-pick', 'merge', 'rebase', 'revert'] as const) {
+ const calls: string[] = [];
+ await expect(runAfterDropCheckout('feature', 'main', async (name) => { calls.push(name); }, async () => {
+ throw { message: 'boom' };
+ }, async () => op)).rejects.toEqual({ message: t('drag.git.pausedOn', { error: 'boom', branch: 'feature' }) });
+ expect(calls).toEqual(['feature']);
+ }
+ expect(t('drag.git.pausedOn', { error: 'boom', branch: 'feature' })).toContain('paused on feature');
+ });
+
+ it('stays on the target branch when the operation state cannot be read', async () => {
+ const calls: string[] = [];
+ await expect(runAfterDropCheckout('feature', 'main', async (name) => { calls.push(name); }, async () => {
+ throw new Error('boom');
+ }, async () => { throw new Error('meta failed'); })).rejects.toEqual({
+ message: t('drag.git.leftOn', { error: 'boom', branch: 'feature' }),
+ });
+ expect(calls).toEqual(['feature']);
+ });
+
+ it('says it left a detached start on the target branch', async () => {
+ const calls: string[] = [];
+ await expect(runAfterDropCheckout('feature', null, async (name) => { calls.push(name); }, async () => {
+ throw new Error('boom');
+ }, idle)).rejects.toEqual({ message: t('drag.git.leftOn', { error: 'boom', branch: 'feature' }) });
+ expect(calls).toEqual(['feature']);
+ expect(t('drag.git.leftOn', { error: 'boom', branch: 'feature' })).toBe('boom — left on feature.');
+ });
+
+ it('says so when switching back fails too', async () => {
+ const checkout = async (name: string) => { if (name === 'main') throw new Error('locked'); };
+ await expect(runAfterDropCheckout('feature', 'main', checkout, async () => {
+ throw new Error('boom');
+ }, idle)).rejects.toEqual({ message: t('drag.git.restoreFailed', { error: 'boom', branch: 'main' }) });
+ });
+
+ it('does not run the step when the checkout itself fails', async () => {
+ let ran = false;
+ await expect(runAfterDropCheckout('feature', 'main', async () => { throw new Error('dirty'); }, async () => {
+ ran = true;
+ }, idle)).rejects.toThrow('dirty');
+ expect(ran).toBe(false);
+ });
+});
diff --git a/ui/src/lib/gitDrag.ts b/ui/src/lib/gitDrag.ts
new file mode 100644
index 0000000..eef7b2f
--- /dev/null
+++ b/ui/src/lib/gitDrag.ts
@@ -0,0 +1,497 @@
+/**
+ * Drop-target resolution for sidebar / graph Git drags.
+ *
+ * A branch dropped on a local branch uses the dragged branch's context-menu
+ * verbs: merge the dragged ref into the target, or rebase the target onto the
+ * dragged ref. A local branch dropped on a remote-tracking branch moves the
+ * local branch instead (merge the remote ref in, or rebase onto it) — a
+ * remote-tracking branch cannot be checked out. Nothing here runs Git; the
+ * confirm dialog does, through the same `merge` / `rebase` commands as the menus.
+ */
+
+import { t } from './i18n';
+
+export const DRAG_THRESHOLD_PX = 5;
+
+/** `Repo::merge(ref, Auto)` — `git merge --no-edit -- [`. */
+export const MENU_MERGE_PREFIX = ['merge', '--no-edit', '--'] as const;
+/** `Repo::rebase(onto)` — `git rebase -- ]`. */
+export const MENU_REBASE_PREFIX = ['rebase', '--'] as const;
+
+export type HistoryOperation =
+ | 'rebase'
+ | 'cherry-pick'
+ | 'revert'
+ | 'merge'
+ | 'mailbox'
+ | 'bisect'
+ | null;
+
+export interface DragBranch {
+ kind: 'local-branch' | 'remote-branch';
+ ref: string;
+ label: string;
+ isHead: boolean;
+ upstreamRemote: string | null;
+ upstreamBranch: string | null;
+}
+
+export interface BranchHit {
+ kind: 'local-branch' | 'remote-branch' | 'remote' | 'tag';
+ ref: string;
+ label: string;
+ isHead: boolean;
+}
+
+/** Local branch dropped on a remote. `offerUpstream` is the "create upstream" prompt. */
+export interface PushIntent {
+ kind: 'push';
+ branch: string;
+ remote: string;
+ remoteBranch: string;
+ offerUpstream: boolean;
+}
+
+export interface DragCommit {
+ hash: string;
+ short: string;
+ parents: string[];
+ /** Graph row index, newest first. Higher means older. */
+ index: number;
+ /** On the linear first-parent tip, so a reorder/squash can rewrite it. */
+ rewrite: boolean;
+}
+
+export interface CommitDrag {
+ kind: 'commits';
+ commits: DragCommit[];
+}
+
+export type DragSource = DragBranch | CommitDrag;
+
+export interface CommitHit {
+ kind: 'commit';
+ hash: string;
+ short: string;
+ parents: string[];
+ index: number;
+ zone: 'before' | 'after' | 'squash';
+ rewrite: boolean;
+}
+
+/** Plan handed to the interactive rebase editor. Nothing here runs Git. */
+export interface RebaseSeed {
+ move: string[];
+ mode: 'reorder' | 'squash';
+ anchor: string;
+ /** Where `move` sits relative to `anchor` in the oldest-first todo. */
+ place: 'before' | 'after';
+ moveLabel: string;
+ anchorLabel: string;
+ /** Parent rev of the oldest involved commit, or null when that commit is a root. */
+ base: string | null;
+ baseLabel: string;
+}
+
+export interface RebaseIntent {
+ kind: 'rebase';
+ seed: RebaseSeed;
+}
+
+export type DropHit = BranchHit | CommitHit;
+
+/** Commits dropped on a local branch. Hashes are oldest-first, matching the graph menu. */
+export interface CherryPickIntent {
+ kind: 'cherry-pick';
+ hashes: string[];
+ label: string;
+ branch: string;
+ checkout: string | null;
+ /** One merge commit: the existing mainline dialog picks the parent. */
+ mainline: { hash: string; short: string; parents: string[] } | null;
+ /** Short hash when a multi-selection includes a merge and must not run. */
+ blockedMerge: string | null;
+}
+
+export type DropIntent = BranchIntent | PushIntent | CherryPickIntent | RebaseIntent;
+
+/** Confirmed branch drop. `checkout` runs only after the user picks Merge or Rebase. */
+export interface BranchIntent {
+ kind: 'branch';
+ draggedRef: string;
+ draggedLabel: string;
+ droppedRef: string;
+ droppedLabel: string;
+ /** Local branch to check out before the verb. Null when it is already HEAD. */
+ checkout: string | null;
+ /** `git merge --no-edit -- ` into `mergeInto`. */
+ mergeRef: string;
+ mergeInto: string;
+ /** `git rebase -- ` while `rebaseBranch` is checked out. */
+ rebaseOnto: string;
+ rebaseBranch: string;
+}
+
+export type DragSession =
+ | { status: 'idle' }
+ | { status: 'armed'; x: number; y: number; source: DragSource }
+ | { status: 'dragging'; source: DragSource; intent: DropIntent | null };
+
+export function upstreamBranchName(upstream: { name: string; remote: string }): string {
+ const prefix = `${upstream.remote}/`;
+ return upstream.name.startsWith(prefix) ? upstream.name.slice(prefix.length) : upstream.name;
+}
+
+/** Any paused merge, rebase, cherry-pick, revert, am or bisect blocks every drop. */
+export function dragBlocksHistory(operation: HistoryOperation): boolean {
+ return operation !== null;
+}
+
+/**
+ * Run a drop's Git step on `branch`, checking it out first when set. If the
+ * step fails after that checkout, re-read the repo's operation: when one is
+ * in progress the failure left it paused on `branch`, so stay there for
+ * Continue/Abort, and when that can't be read, stay too; otherwise switch
+ * back to `original` (best effort). Either
+ * way, say so in the error. A conflict pause is a result, not a failure, so
+ * it stays on `branch`.
+ */
+export async function runAfterDropCheckout(
+ branch: string | null,
+ original: string | null,
+ checkout: (name: string) => Promise,
+ step: () => Promise,
+ readOperation: () => Promise,
+): Promise {
+ if (!branch) return step();
+ await checkout(branch);
+ try {
+ return await step();
+ } catch (caught) {
+ const message = caught && typeof caught === 'object' && 'message' in caught
+ ? String((caught as { message: unknown }).message)
+ : String(caught);
+ let operation: HistoryOperation;
+ try {
+ operation = await readOperation();
+ } catch {
+ // Unknown state: switching branches could carry a paused operation along.
+ throw { message: t('drag.git.leftOn', { error: message, branch }) };
+ }
+ if (operation !== null) throw { message: t('drag.git.pausedOn', { error: message, branch }) };
+ if (!original) throw { message: t('drag.git.leftOn', { error: message, branch }) };
+ if (original === branch) throw { message };
+ try {
+ await checkout(original);
+ } catch {
+ throw { message: t('drag.git.restoreFailed', { error: message, branch: original }) };
+ }
+ throw { message: t('drag.git.restored', { error: message, branch: original }) };
+ }
+}
+
+export function branchFromDataset(dataset: Record): DragBranch | null {
+ const kind = dataset.gitSource;
+ if (kind !== 'local-branch' && kind !== 'remote-branch') return null;
+ const ref = dataset.gitRef;
+ const label = dataset.gitLabel;
+ if (!ref || !label) return null;
+ return {
+ kind,
+ ref,
+ label,
+ isHead: dataset.gitHead === '1',
+ upstreamRemote: dataset.gitUpstreamRemote ?? null,
+ upstreamBranch: dataset.gitUpstreamBranch ?? null,
+ };
+}
+
+export function hitFromDataset(dataset: Record): BranchHit | null {
+ const kind = dataset.gitDrop;
+ if (kind !== 'local-branch' && kind !== 'remote-branch' && kind !== 'remote' && kind !== 'tag') return null;
+ const ref = dataset.gitRef;
+ const label = dataset.gitLabel;
+ if (!ref || !label) return null;
+ return { kind, ref, label, isHead: dataset.gitHead === '1' };
+}
+
+export function resolveBranchDrop(
+ source: DragBranch,
+ hit: BranchHit | null,
+ operation: HistoryOperation,
+): BranchIntent | null {
+ if (dragBlocksHistory(operation) || !hit) return null;
+ if (hit.kind === 'tag' || hit.kind === 'remote') return null;
+ if (source.ref === hit.ref) return null;
+
+ if (hit.kind === 'local-branch') {
+ return {
+ kind: 'branch',
+ draggedRef: source.ref,
+ draggedLabel: source.label,
+ droppedRef: hit.ref,
+ droppedLabel: hit.label,
+ checkout: hit.isHead ? null : hit.ref,
+ mergeRef: source.ref,
+ mergeInto: hit.label,
+ rebaseOnto: source.ref,
+ rebaseBranch: hit.label,
+ };
+ }
+
+ if (source.kind === 'local-branch') {
+ return {
+ kind: 'branch',
+ draggedRef: source.ref,
+ draggedLabel: source.label,
+ droppedRef: hit.ref,
+ droppedLabel: hit.label,
+ checkout: source.isHead ? null : source.ref,
+ mergeRef: hit.ref,
+ mergeInto: source.label,
+ rebaseOnto: hit.ref,
+ rebaseBranch: source.label,
+ };
+ }
+
+ return null;
+}
+
+/** Drop a local branch on a remote folder. Remote-tracking rows stay merge/rebase targets. */
+export function resolvePushDrop(
+ source: DragBranch,
+ hit: BranchHit | null,
+ operation: HistoryOperation,
+): PushIntent | null {
+ if (dragBlocksHistory(operation) || !hit) return null;
+ if (source.kind !== 'local-branch' || hit.kind !== 'remote') return null;
+ const trackedHere = source.upstreamRemote === hit.ref && source.upstreamBranch != null;
+ return {
+ kind: 'push',
+ branch: source.ref,
+ remote: hit.ref,
+ remoteBranch: trackedHere ? source.upstreamBranch! : source.ref,
+ offerUpstream: source.upstreamRemote == null,
+ };
+}
+
+export function commitZone(offsetY: number, height: number): 'before' | 'after' | 'squash' {
+ const edge = Math.min(8, Math.max(height, 0) * 0.25);
+ if (offsetY <= edge) return 'before';
+ if (offsetY >= height - edge) return 'after';
+ return 'squash';
+}
+
+export function commitFromDataset(dataset: Record): DragCommit | null {
+ if (dataset.gitSource !== 'commit' && dataset.gitDrop !== 'commit') return null;
+ const hash = dataset.gitHash;
+ const short = dataset.gitShort;
+ if (!hash || !short) return null;
+ const index = Number(dataset.gitIndex);
+ return {
+ hash,
+ short,
+ parents: dataset.gitParents ? dataset.gitParents.split(' ').filter(Boolean) : [],
+ index: Number.isFinite(index) ? index : 0,
+ rewrite: dataset.gitRewrite === '1',
+ };
+}
+
+/** Commits on the linear first-parent suffix of `tip`. A merge stops the walk. */
+export function linearTipHashes(
+ commits: readonly { hash: string; parents: string[] }[],
+ tip: string | null,
+): Set {
+ const byHash = new Map(commits.map((commit) => [commit.hash, commit]));
+ const out = new Set();
+ let hash = tip;
+ let guard = 0;
+ while (hash && guard++ <= commits.length) {
+ const commit = byHash.get(hash);
+ if (!commit || out.has(hash) || commit.parents.length > 1) break;
+ out.add(hash);
+ hash = commit.parents[0];
+ }
+ return out;
+}
+
+/**
+ * Drag index per commit hash, counting graph rows but skipping stash rows, so
+ * it matches the position in the commit list. Rows and multi-selections must
+ * compare on this, never on the graph row number.
+ */
+export function commitIndexByHash(rows: readonly { hash: string; stash?: unknown }[]): Map {
+ const out = new Map();
+ for (const row of rows) {
+ if (!row.stash) out.set(row.hash, out.size);
+ }
+ return out;
+}
+
+/** Oldest-first, matching `selectedCommitsOldestFirst`. A selected row drags the whole selection. */
+export function commitDragFromRows(rows: DragCommit[]): CommitDrag | null {
+ if (rows.length === 0) return null;
+ const commits = [...rows].sort((a, b) => b.index - a.index);
+ return { kind: 'commits', commits };
+}
+
+export function resolveCherryPick(
+ source: CommitDrag,
+ hit: DropHit | null,
+ operation: HistoryOperation,
+): CherryPickIntent | null {
+ if (dragBlocksHistory(operation) || !hit || hit.kind !== 'local-branch' || source.commits.length === 0) return null;
+ const merges = source.commits.filter((commit) => commit.parents.length > 1);
+ const only = source.commits.length === 1 ? source.commits[0] : null;
+ return {
+ kind: 'cherry-pick',
+ hashes: source.commits.map((commit) => commit.hash),
+ label: source.commits.map((commit) => commit.short).join(', '),
+ branch: hit.ref,
+ checkout: hit.isHead ? null : hit.ref,
+ mainline: only && only.parents.length > 1
+ ? { hash: only.hash, short: only.short, parents: only.parents }
+ : null,
+ blockedMerge: source.commits.length > 1 && merges.length > 0 ? merges[0].short : null,
+ };
+}
+
+/** `Repo::cherry_pick` without a mainline: `git cherry-pick -- `. */
+export function cherryPickGitArgs(hashes: string[]): string[] {
+ return ['cherry-pick', '--', ...hashes];
+}
+
+/**
+ * Drop commits on another commit of the current linear tip. The top edge places
+ * them newer than the target, the bottom edge older, and the middle squashes
+ * them into it. A no-op reorder, a drop on itself, or a commit off that tip
+ * resolves to null so the cursor stays no-drop.
+ */
+export function resolveRebaseDrop(
+ source: CommitDrag,
+ hit: CommitHit | null,
+ operation: HistoryOperation,
+): RebaseIntent | null {
+ if (dragBlocksHistory(operation) || !hit || source.commits.length === 0) return null;
+ if (!hit.rewrite || source.commits.some((commit) => !commit.rewrite)) return null;
+ if (source.commits.some((commit) => commit.hash === hit.hash)) return null;
+ const ordered = [...source.commits].sort((a, b) => b.index - a.index);
+ const mode = hit.zone === 'squash' ? 'squash' : 'reorder';
+ const place = hit.zone === 'after' ? 'before' : 'after';
+ const involved = [...ordered, hit];
+ const oldest = involved.reduce((a, b) => (a.index >= b.index ? a : b));
+ const seed: RebaseSeed = {
+ move: ordered.map((commit) => commit.hash),
+ mode,
+ anchor: hit.hash,
+ place,
+ moveLabel: ordered.length === 1 ? ordered[0].short : ordered.map((commit) => commit.short).join(', '),
+ anchorLabel: hit.short,
+ base: oldest.parents.length > 0 ? `${oldest.hash}^` : null,
+ baseLabel: oldest.short,
+ };
+ if (mode === 'reorder' && rebaseOrderIsUnchanged(ordered, hit, place)) return null;
+ return { kind: 'rebase', seed };
+}
+
+function rebaseOrderIsUnchanged(
+ ordered: readonly DragCommit[],
+ hit: CommitHit,
+ place: 'before' | 'after',
+): boolean {
+ const current = [...ordered, hit].sort((a, b) => b.index - a.index).map((commit) => commit.hash);
+ const moving = new Set(ordered.map((commit) => commit.hash));
+ const rest = current.filter((hash) => !moving.has(hash));
+ const anchorAt = rest.indexOf(hit.hash);
+ const insertAt = place === 'before' ? anchorAt : anchorAt + 1;
+ const desired = [...rest.slice(0, insertAt), ...ordered.map((commit) => commit.hash), ...rest.slice(insertAt)];
+ return desired.join('\0') === current.join('\0');
+}
+
+export function resolveGitDrop(
+ source: DragSource,
+ hit: DropHit | null,
+ operation: HistoryOperation,
+): DropIntent | null {
+ if (source.kind === 'commits') {
+ if (hit?.kind === 'commit') return resolveRebaseDrop(source, hit, operation);
+ return resolveCherryPick(source, hit, operation);
+ }
+ const branchHit = hit && hit.kind !== 'commit' ? hit : null;
+ return resolveBranchDrop(source, branchHit, operation) ?? resolvePushDrop(source, branchHit, operation);
+}
+
+export function rebaseSeedMessageKey(seed: RebaseSeed):
+ | 'drag.git.rebaseSeedNewer'
+ | 'drag.git.rebaseSeedOlder'
+ | 'drag.git.rebaseSeedSquash' {
+ if (seed.mode === 'squash') return 'drag.git.rebaseSeedSquash';
+ return seed.place === 'before' ? 'drag.git.rebaseSeedOlder' : 'drag.git.rebaseSeedNewer';
+}
+
+export function sourceLabel(source: DragSource): string {
+ if (source.kind !== 'commits') return source.label;
+ return source.commits.length === 1 ? source.commits[0].short : String(source.commits.length);
+}
+
+/** `Repo::push_branch` for a normal push: `git push --progress [--set-upstream] -- `. */
+export function pushGitArgs(intent: PushIntent, setUpstream: boolean): string[] {
+ const args = ['push', '--progress'];
+ if (setUpstream) args.push('--set-upstream');
+ args.push('--', intent.remote, `refs/heads/${intent.branch}:refs/heads/${intent.remoteBranch}`);
+ return args;
+}
+
+export function dragGhost(intent: DropIntent): { source: string; target: string } {
+ switch (intent.kind) {
+ case 'branch':
+ return { source: intent.draggedLabel, target: intent.droppedLabel };
+ case 'push':
+ return { source: intent.branch, target: intent.remote };
+ case 'cherry-pick':
+ return { source: intent.label, target: intent.branch };
+ case 'rebase':
+ return { source: intent.seed.moveLabel, target: intent.seed.anchorLabel };
+ default: {
+ const unreachable: never = intent;
+ return unreachable;
+ }
+ }
+}
+
+export function dragMergeArgs(intent: BranchIntent): string[] {
+ return [...MENU_MERGE_PREFIX, intent.mergeRef];
+}
+
+export function dragRebaseArgs(intent: BranchIntent): string[] {
+ return [...MENU_REBASE_PREFIX, intent.rebaseOnto];
+}
+
+export function beginDrag(source: DragSource, x: number, y: number): DragSession {
+ return { status: 'armed', x, y, source };
+}
+
+export function moveDrag(
+ session: DragSession,
+ move: { x: number; y: number; intent: DropIntent | null },
+): DragSession {
+ if (session.status === 'armed') {
+ if (Math.hypot(move.x - session.x, move.y - session.y) < DRAG_THRESHOLD_PX) return session;
+ return { status: 'dragging', source: session.source, intent: move.intent };
+ }
+ if (session.status === 'dragging') return { status: 'dragging', source: session.source, intent: move.intent };
+ return session;
+}
+
+/**
+ * `commit` is false for Escape and for any cancel. A release before the
+ * movement threshold, or over a rejected target, also yields null — no Git op.
+ */
+export function finishDrag(session: DragSession, commit: boolean): DropIntent | null {
+ if (!commit || session.status !== 'dragging') return null;
+ return session.intent;
+}
+
+export function dragCursor(intent: DropIntent | null): 'copy' | 'no-drop' {
+ return intent ? 'copy' : 'no-drop';
+}
diff --git a/ui/src/lib/i18n.ts b/ui/src/lib/i18n.ts
index b77edbf..89b88b5 100644
--- a/ui/src/lib/i18n.ts
+++ b/ui/src/lib/i18n.ts
@@ -420,6 +420,39 @@ export const en = {
'gitUndo.hint': 'Enter walks the stack through the focused action.',
'gitUndo.drop': 'Remove “{label}” from history',
'gitUndo.dropHint': 'This entry can’t be applied any more. Removing it changes nothing in the repository.',
+ 'drag.git.branchTitle': 'Merge or rebase',
+ 'drag.git.branchBody': 'Dropped {dragged} on {dropped}. Merge {mergeRef} into {mergeInto}, or rebase {rebaseBranch} onto {rebaseOnto}.',
+ 'drag.git.merge': 'Merge',
+ 'drag.git.rebase': 'Rebase',
+ 'drag.git.ghost': '{source} → {target}',
+ 'drag.git.rebaseConflict': 'Rebase onto {onto} has conflicts — resolve in Local Changes',
+ 'drag.git.rebaseDone': 'Rebased {branch} onto {onto}',
+ 'drag.git.rebaseFailed': 'Rebase failed: {error}',
+ 'drag.git.menuMerge': 'Merge into {branch}',
+ 'drag.git.menuRebase': 'Rebase {branch} onto this',
+ 'drag.git.pushTitle': 'Push branch',
+ 'drag.git.pushBody': 'Push {branch} to {remote}/{destination}.',
+ 'drag.git.pushUpstream': 'Set {upstream} as the upstream for {branch}.',
+ 'drag.git.pushButton': 'Push',
+ 'drag.git.pushAndSet': 'Push and set upstream',
+ 'drag.git.cherryTitle': 'Cherry-pick',
+ 'drag.git.cherryBody': 'Cherry-pick {commits} onto {branch}.',
+ 'drag.git.checkoutFirst': 'Checks out {branch} first.',
+ 'drag.git.restored': '{error} — switched back to {branch}.',
+ 'drag.git.restoreFailed': '{error} — could not switch back to {branch}.',
+ 'drag.git.pausedOn': '{error} — the operation is paused on {branch}; Continue or Abort it there.',
+ 'drag.git.leftOn': '{error} — left on {branch}.',
+ 'drag.git.cherryButton': 'Cherry-pick',
+ 'drag.git.cherryConflict': 'Cherry-pick of {label} has conflicts — resolve in Local Changes',
+ 'drag.git.cherryDone': 'Cherry-picked {label}',
+ 'drag.git.cherryDoneMany': 'Cherry-picked {count} commits in oldest-to-newest order',
+ 'drag.git.cherryFailed': 'Cherry-pick failed: {error}',
+ 'drag.git.cherryMergeBlocked': 'Selection includes merge {hash} — apply merge commits individually so you can choose a mainline parent',
+ 'drag.git.commitCount': '{count} commits',
+ 'drag.git.rebaseSeedNewer': 'Move {commits} to be newer than {target}. Review this rebase plan — nothing runs until you start it.',
+ 'drag.git.rebaseSeedOlder': 'Move {commits} to be older than {target}. Review this rebase plan — nothing runs until you start it.',
+ 'drag.git.rebaseSeedSquash': 'Squash {commits} into {target}. Review this rebase plan — nothing runs until you start it.',
+ 'drag.git.rebaseSeedMissing': 'Those commits are not in this rebase range, so the plan was not applied.',
} as const;
export type MessageKey = keyof typeof en;
diff --git a/ui/src/lib/rebase.test.ts b/ui/src/lib/rebase.test.ts
index ca6aa47..940dadf 100644
--- a/ui/src/lib/rebase.test.ts
+++ b/ui/src/lib/rebase.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { autosquashPlan, planUpdateRefs, withMovedBranches, type AutosquashInput } from './rebase';
+import { applyRebaseSeed, autosquashPlan, planUpdateRefs, withMovedBranches, type AutosquashInput } from './rebase';
const e = (oid: string, subject: string): AutosquashInput => ({ oid, subject });
@@ -182,3 +182,28 @@ describe('withMovedBranches', () => {
);
});
});
+
+describe('applyRebaseSeed', () => {
+ const todo = [{ oid: 'a' }, { oid: 'b' }, { oid: 'c' }];
+
+ it('moves a newer commit to just before an older one', () => {
+ expect(applyRebaseSeed(todo, { move: ['c'], mode: 'reorder', anchor: 'b', place: 'before' })).toEqual([
+ { oid: 'a', action: 'pick' },
+ { oid: 'c', action: 'pick' },
+ { oid: 'b', action: 'pick' },
+ ]);
+ });
+
+ it('squashes the moved commits into the anchor', () => {
+ expect(applyRebaseSeed(todo, { move: ['c'], mode: 'squash', anchor: 'b', place: 'after' })).toEqual([
+ { oid: 'a', action: 'pick' },
+ { oid: 'b', action: 'pick' },
+ { oid: 'c', action: 'squash' },
+ ]);
+ });
+
+ it('returns null when a dragged commit is outside the todo', () => {
+ expect(applyRebaseSeed(todo, { move: ['missing'], mode: 'reorder', anchor: 'b', place: 'after' })).toBeNull();
+ expect(applyRebaseSeed(todo, { move: ['b'], mode: 'squash', anchor: 'b', place: 'after' })).toBeNull();
+ });
+});
diff --git a/ui/src/lib/rebase.ts b/ui/src/lib/rebase.ts
index 5455725..e35f802 100644
--- a/ui/src/lib/rebase.ts
+++ b/ui/src/lib/rebase.ts
@@ -167,3 +167,39 @@ export function withMovedBranches(message: string, moved: readonly string[]): st
const base = message.endsWith('.') ? message : `${message}.`;
return t('rebase.moved', { message: base, branches: moved.join(', ') });
}
+
+/** Dragged commits inserted around an anchor in an oldest-first todo. */
+export interface RebaseSeedPlan {
+ move: string[];
+ mode: 'reorder' | 'squash';
+ anchor: string;
+ /** Where `move` sits relative to `anchor` in the oldest-first todo. */
+ place: 'before' | 'after';
+}
+
+/**
+ * Apply a drag plan to a rebase todo. Moved commits leave their old slots and
+ * land as a block before or after the anchor. Squash marks only the moved
+ * commits, so they fold into the anchor when placed after it. Returns null
+ * when an oid is missing or the anchor is one of the moved commits — the
+ * editor shows that and does not start a rebase.
+ */
+export function applyRebaseSeed(
+ entries: readonly { oid: string }[],
+ seed: RebaseSeedPlan,
+): { oid: string; action: 'pick' | 'squash' }[] | null {
+ if (seed.move.length === 0 || seed.move.includes(seed.anchor)) return null;
+ const known = new Set(entries.map((entry) => entry.oid));
+ if (!known.has(seed.anchor) || seed.move.some((oid) => !known.has(oid))) return null;
+ const moving = new Set(seed.move);
+ const rest = entries.filter((entry) => !moving.has(entry.oid));
+ const anchorAt = rest.findIndex((entry) => entry.oid === seed.anchor);
+ if (anchorAt < 0) return null;
+ const insertAt = seed.place === 'before' ? anchorAt : anchorAt + 1;
+ const moved = seed.move.map((oid) => entries.find((entry) => entry.oid === oid)!);
+ const ordered = [...rest.slice(0, insertAt), ...moved, ...rest.slice(insertAt)];
+ return ordered.map((entry) => ({
+ oid: entry.oid,
+ action: seed.mode === 'squash' && moving.has(entry.oid) ? 'squash' : 'pick',
+ }));
+}
diff --git a/ui/src/styles/features.css b/ui/src/styles/features.css
index 2bd388f..856ed13 100644
--- a/ui/src/styles/features.css
+++ b/ui/src/styles/features.css
@@ -7769,6 +7769,19 @@ textarea.clone-input {
color: var(--text-dim);
border-style: dashed;
}
+/* Git-row drags set these on so row `cursor: pointer` cannot win. */
+html.git-drag-invalid,
+html.git-drag-invalid * {
+ cursor: no-drop !important;
+}
+html.git-drag-valid,
+html.git-drag-valid * {
+ cursor: copy !important;
+}
+.side-row[data-git-drop-hover='valid'],
+tr[data-git-drop-hover='valid'] {
+ background: var(--bg-sel);
+}
/* Files sidebar tab — a bounded-height column so the tree owns its own scroll
(it must not nest inside the .side-scroll region used by the Git tab). */
diff --git a/ui/src/views/Commits.tsx b/ui/src/views/Commits.tsx
index 08830b7..179ed4b 100644
--- a/ui/src/views/Commits.tsx
+++ b/ui/src/views/Commits.tsx
@@ -6,6 +6,7 @@ import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import { computeGraph } from '../lib/graph';
import { pickCommitPatchDestination } from '../lib/dialog';
import { EDITABLE_SELECTOR, eventInside } from '../lib/keys';
+import { commitIndexByHash, linearTipHashes } from '../lib/gitDrag';
import { selectedCommitsOldestFirst } from '../lib/historySelection';
import {
checkoutCommitProgress,
@@ -540,6 +541,23 @@ export function Commits({ onCreateTag, onInteractiveRebase, onAmendInto, onReset
[providerMergedBranches, refs],
);
const currentCommit = useMemo(() => currentCommitHash(refs, commits), [commits, refs]);
+ const rewriteCommits = useMemo(() => linearTipHashes(commits, currentCommit), [commits, currentCommit]);
+ // Drag order uses the index in `commits`, never the graph row (stash rows
+ // shift row numbers), so rows and multi-selections compare the same way.
+ const commitIndex = useMemo(() => commitIndexByHash(rows), [rows]);
+ const commitDragSelection = useMemo(
+ () => {
+ if (bulkSelection.length <= 1) return undefined;
+ return JSON.stringify(bulkSelection.map((commit) => ({
+ hash: commit.hash,
+ short: commit.short_hash,
+ parents: commit.parents,
+ index: commitIndex.get(commit.hash) ?? 0,
+ rewrite: rewriteCommits.has(commit.hash),
+ })));
+ },
+ [bulkSelection, commitIndex, rewriteCommits],
+ );
const colWidth = graphColWidth(graph.laneCount);
// Hashes of the commits since the review baseline (`baseline..HEAD` over
@@ -1191,6 +1209,7 @@ export function Commits({ onCreateTag, onInteractiveRebase, onAmendInto, onReset
ref={graphMainRef}
className="graph-main"
data-git-undo-surface="graph"
+ data-git-selection={commitDragSelection}
tabIndex={0}
role="grid"
aria-multiselectable
@@ -1238,6 +1257,15 @@ export function Commits({ onCreateTag, onInteractiveRebase, onAmendInto, onReset
.filter(Boolean)
.join(' ') || undefined}
aria-selected={selected}
+ data-git-source={stash ? undefined : 'commit'}
+ data-git-drop={stash ? undefined : 'commit'}
+ data-git-hash={stash ? undefined : c.hash}
+ data-git-short={stash ? undefined : c.short_hash}
+ data-git-parents={stash ? undefined : c.parents.join(' ')}
+ data-git-index={stash ? undefined : commitIndex.get(c.hash)}
+ data-git-selected={!stash && selected ? '1' : undefined}
+ data-git-tip={!stash && c.hash === currentCommit ? '1' : undefined}
+ data-git-rewrite={!stash && rewriteCommits.has(c.hash) ? '1' : undefined}
onClick={(e) => (stash ? onStashClick(stash) : onRowClick(c.hash, e))}
onContextMenu={(e) => {
e.preventDefault();
diff --git a/ui/src/views/MainlineDialog.tsx b/ui/src/views/MainlineDialog.tsx
index 3d696e5..20a514a 100644
--- a/ui/src/views/MainlineDialog.tsx
+++ b/ui/src/views/MainlineDialog.tsx
@@ -11,11 +11,14 @@ export type MainlineOperation = 'cherry-pick' | 'revert';
export function MainlineDialog({
commit,
operation,
+ wrap,
onClose,
onToast,
}: {
commit: Commit;
operation: MainlineOperation;
+ /** Wraps the history command once the parent is confirmed. */
+ wrap?: (step: () => Promise) => Promise;
onClose: () => void;
onToast: (message: string, kind?: 'success' | 'error') => void;
}) {
@@ -30,10 +33,11 @@ export function MainlineDialog({
setBusy(true);
setError(null);
try {
- const conflicted =
+ const run = () =>
operation === 'cherry-pick'
- ? await cherryPick([commit.hash], parent)
- : await revert([commit.hash], parent);
+ ? cherryPick([commit.hash], parent)
+ : revert([commit.hash], parent);
+ const conflicted = await (wrap ? wrap(run) : run());
const verb = operation === 'cherry-pick' ? 'Cherry-pick' : 'Revert';
onToast(
conflicted
diff --git a/ui/src/views/MergeDialog.tsx b/ui/src/views/MergeDialog.tsx
index 72965f3..5207612 100644
--- a/ui/src/views/MergeDialog.tsx
+++ b/ui/src/views/MergeDialog.tsx
@@ -33,11 +33,15 @@ const MODES: { value: MergeMode; label: string; hint: string }[] = [
export function MergeDialog({
source,
into,
+ wrap,
onClose,
onToast,
}: {
source: string;
into: string;
+ /** Wraps `merge` once Merge is confirmed (a drop checks out first and
+ * switches back on failure). Escape never calls it. */
+ wrap?: (step: () => Promise) => Promise;
onClose: () => void;
onToast: (msg: string, kind?: 'success' | 'error') => void;
}) {
@@ -56,7 +60,8 @@ export function MergeDialog({
setBusy(true);
setError(null);
try {
- const conflicted = await merge(source, mode);
+ const run = () => merge(source, mode);
+ const conflicted = await (wrap ? wrap(run) : run());
onToast(
conflicted
? `Merge stopped with conflicts — resolve them in Local Changes`
diff --git a/ui/src/views/RebaseEditor.tsx b/ui/src/views/RebaseEditor.tsx
index db9644c..0b1c8fd 100644
--- a/ui/src/views/RebaseEditor.tsx
+++ b/ui/src/views/RebaseEditor.tsx
@@ -2,8 +2,9 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Icon } from '../components/Icon';
import { Select } from '../components/Select';
+import { rebaseSeedMessageKey, type RebaseSeed } from '../lib/gitDrag';
import { t } from '../lib/i18n';
-import { autosquashPlan, planUpdateRefs, withMovedBranches } from '../lib/rebase';
+import { applyRebaseSeed, autosquashPlan, planUpdateRefs, withMovedBranches } from '../lib/rebase';
import { errMessage } from '../lib/tauri';
import { useRepo } from '../stores/repo';
import type { RebaseAction, RebaseStep } from '../lib/types';
@@ -56,6 +57,7 @@ const KEY_TO_ACTION: Record = {
export function RebaseEditor({
base,
label,
+ seed = null,
onClose,
onToast,
}: {
@@ -63,6 +65,8 @@ export function RebaseEditor({
base: string | null;
/** Short human label for the starting point, shown in the blurb. */
label: string;
+ /** Drag plan to review. When set, autosquash is skipped and Start is the only Git write. */
+ seed?: RebaseSeed | null;
onClose: () => void;
onToast: (msg: string, kind?: 'success' | 'error') => void;
}) {
@@ -129,14 +133,25 @@ export function RebaseEditor({
// every row stays editable, and isNoop correctly sees a non-noop plan.
const hasMergeEntries = entries.some((entry) => entry.is_merge);
setPreserveMerges(hasMergeEntries);
- const plan = hasMergeEntries
- ? null
- : autosquashPlan(entries.map((e) => ({ oid: e.oid, subject: e.subject })));
- if (plan) {
+ if (seed) {
+ const plan = hasMergeEntries ? null : applyRebaseSeed(entries, seed);
+ if (!plan) {
+ setLoadError(t('drag.git.rebaseSeedMissing'));
+ return;
+ }
const byOid = new Map(next.map((r) => [r.oid, r]));
- next = plan.map((s) => ({ ...byOid.get(s.oid)!, action: s.action }));
+ next = plan.map((step) => ({ ...byOid.get(step.oid)!, action: step.action }));
+ setAutosquashed(0);
+ } else {
+ const plan = hasMergeEntries
+ ? null
+ : autosquashPlan(entries.map((e) => ({ oid: e.oid, subject: e.subject })));
+ if (plan) {
+ const byOid = new Map(next.map((r) => [r.oid, r]));
+ next = plan.map((s) => ({ ...byOid.get(s.oid)!, action: s.action }));
+ }
+ setAutosquashed(plan ? plan.filter((s) => s.action !== 'pick').length : 0);
}
- setAutosquashed(plan ? plan.filter((s) => s.action !== 'pick').length : 0);
setRows(next);
setFocused(0);
})
@@ -146,7 +161,7 @@ export function RebaseEditor({
return () => {
alive = false;
};
- }, [base, loadRebaseTodo]);
+ }, [base, loadRebaseTodo, seed]);
useEffect(() => {
let alive = true;
@@ -385,6 +400,11 @@ export function RebaseEditor({
p /r /e /s /f /d .
+ {seed ? (
+
+ {t(rebaseSeedMessageKey(seed), { commits: seed.moveLabel, target: seed.anchorLabel })}
+
+ ) : null}
{autosquashed > 0 ? (
Autosquash: {autosquashed} fixup commit{autosquashed === 1 ? '' : 's'} moved under{' '}
diff --git a/ui/src/views/RebaseOntoDialog.tsx b/ui/src/views/RebaseOntoDialog.tsx
index 523fcb1..a39e2f6 100644
--- a/ui/src/views/RebaseOntoDialog.tsx
+++ b/ui/src/views/RebaseOntoDialog.tsx
@@ -12,17 +12,28 @@ import { UpdateRefsToggle } from './RebaseUpdateRefs';
* Confirm a plain `git rebase
` and choose whether other local branches
* in the range follow (`--update-refs`). The choice is remembered per repo as
* Strand's `strand.rebaseUpdateRefs` once the rebase starts.
+ *
+ * The sidebar Rebase menu and a branch drag-and-drop both open this dialog.
+ * A drop that has to switch branches first passes `checkout` and `wrap`; the
+ * branch preview is skipped then, because it is computed from the current
+ * HEAD, not the branch the drop checks out.
*/
export function RebaseOntoDialog({
onto,
branch,
onClose,
onToast,
+ checkout = null,
+ wrap,
}: {
onto: string;
branch: string;
onClose: () => void;
onToast: (msg: string, kind?: 'success' | 'error') => void;
+ /** Branch a drop checks out before rebasing; null when HEAD is already `branch`. */
+ checkout?: string | null;
+ /** Runs the rebase after that checkout, switching back if it fails. */
+ wrap?: (step: () => Promise) => Promise;
}) {
const rebase = useRepo((s) => s.rebase);
const loadRebaseUpdateRefs = useRepo((s) => s.loadRebaseUpdateRefs);
@@ -53,7 +64,7 @@ export function RebaseOntoDialog({
.catch((caught) => {
if (alive) setError(errMessage(caught));
});
- if (path) {
+ if (path && !checkout) {
tauri.repoRebaseRefPreview(path, onto)
.then((rows) => {
if (alive) setPreview(rows);
@@ -65,7 +76,7 @@ export function RebaseOntoDialog({
return () => {
alive = false;
};
- }, [loadRebaseUpdateRefs, onto, path]);
+ }, [checkout, loadRebaseUpdateRefs, onto, path]);
function onToggle(enabled: boolean) {
setUpdateRefs(enabled);
@@ -79,7 +90,8 @@ export function RebaseOntoDialog({
try {
// Remember the choice only once a rebase actually starts.
if (supported) await setRebaseUpdateRefs(updateRefs);
- const outcome = await rebase(onto, supported && updateRefs);
+ const run = () => rebase(onto, supported && updateRefs);
+ const outcome = wrap ? await wrap(run) : await run();
const done = outcome.paused
? t('rebase.plainConflict', { onto })
: t('rebase.plainDone', { branch, onto });
@@ -114,7 +126,10 @@ export function RebaseOntoDialog({
}
>
-
{t('rebase.ontoBlurb', { branch, onto })}
+
+ {t('rebase.ontoBlurb', { branch, onto })}
+ {checkout ? ` ${t('drag.git.checkoutFirst', { branch: checkout })}` : null}
+
to here…** — opens the Reset dialog.
- **New worktree from here…** — cut a task branch at this exact commit; see [Worktrees](worktrees.md).
- **Review changes since this** — pin the review baseline here and jump to the Review view.
diff --git a/website/docs/everyday-git.md b/website/docs/everyday-git.md
index 1a27fc3..de310da 100644
--- a/website/docs/everyday-git.md
+++ b/website/docs/everyday-git.md
@@ -265,12 +265,15 @@ objects.
- **Cherry-pick** and **Revert** act on a single commit from the commit detail
panel or graph row menu. For a merge commit, choose the parent Git should
- treat as the mainline.
+ treat as the mainline. Drag commits from the graph onto a local branch in the
+ sidebar for the same cherry-pick; the confirmation names the commits and the
+ branch, and Escape cancels before Git runs.
- Multi-select commits in All Commits to **Cherry-pick selected** in
oldest-to-newest order. Exactly two selected commits can also be compared in
a changed-file and full-diff dialog.
- **Merge** ("Merge into " on a branch) opens a dialog with three modes: fast-forward when possible, always create a merge commit (no-FF), or squash — a squash merge leaves the result staged so you write the commit yourself.
- A plain **rebase** ("Rebase onto this") is available from the branch context menu. It opens a dialog that names the branch being replayed and lets you turn on **Update other branches (--update-refs)**. That choice is remembered for this repository once you start the rebase. It is Strand's own setting, so `git pull --rebase` and rebases you run in a terminal are unaffected. When it is on, the dialog lists other local branches whose tips sit in the range and will move with it, and names any that will not because they are checked out in another worktree. The result toast lists the branches that actually moved. The option needs Git 2.38 or newer; on an older Git it stays off, with an explanation, and the rebase still runs.
+- Drag a branch onto another branch in the sidebar. The confirmation names both refs and offers **Merge** (the dragged ref into the drop target) or **Rebase** (the drop target onto the dragged ref) — the same commands as those menu items. **Rebase** opens the same Rebase dialog as the menu item, including **Update other branches (--update-refs)**. Remote-tracking branches work in either direction; the local branch is the one Git moves, and a remote branch's menu has the same **Merge into…** and **Rebase … onto this** items. Dropping a branch on itself, on a tag, or while a merge, rebase, cherry-pick, revert, `git am` or bisect is paused shows a no-drop cursor and does nothing. When the drop has to switch to another branch first, the confirmation says so; if Git then fails, Strand switches back to the branch you were on — unless the failure left the operation paused, in which case you stay on that branch to Continue or Abort it. Escape closes the confirmation without checking out or running Git. Drop a local branch on a remote (the remote's own row, such as `origin`) to push it. If the branch has no upstream, the confirmation offers to create `remote/branch` — the same push the **Push to remote…** dialog sends when you accept that remote, destination, and upstream checkbox. Drag commits within the current branch’s linear history to reorder or squash them: the interactive rebase editor opens with that plan filled in, and Escape closes it before Git runs.
Open **Compare branches…** from the command palette (⌘K / Ctrl+K) or the
**Branches → Branch actions** menu to compare any two local or remote branches.