From 72b338b927929a4615fcf56accd421b639e01bc7 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 26 Nov 2026 13:46:35 -0500 Subject: [PATCH 1/2] Remove the Merge Locally panel and its local squash-merge The panel sat at the top of the right column for every worktree without a PR, merged into main with one click and no confirmation, overwrote the agent's commit message with " (squashed)", and moved the worktree into the collapsed Merged / Closed group. Removed: MergeLocallyPanel (desktop + mobile), the 'merge' right-panel key and its toolbar entry, useLocalMergeState, the worktree:mainStatus / prepareMain / previewMerge / mergeLocal handlers and backend methods, local-merge.ts, mergeWorktreeLocally / prepareMainForMerge / getMainWorktreeStatus (+ cache) / previewMergeConflicts, and the prs slice's mergingByPath + localMergeStarted/Finished events. Kept: mergeStrategy (the GitHub PR merge button uses it; Settings copy now describes GitHub's methods), merge-conflict-request.ts (PR flow), and the read-only side of config.locallyMerged so worktrees already merged this way stay under Merged / Closed instead of jumping back to Active. Nothing adds entries any more, so that map only shrinks. Repo configs still carrying hideMergePanel / hiddenRightPanels.merge / 'merge' in rightPanelOrder load cleanly and are never rewritten on their own; the stale keys drop on the next user-initiated write. Co-Authored-By: Claude Opus 5.5 --- src/main/index.ts | 43 +- src/main/local-merge.test.ts | 97 ----- src/main/local-merge.ts | 88 ---- src/main/persistence.ts | 13 +- src/main/repo-config.test.ts | 48 +++ src/main/repo-config.ts | 15 +- src/main/worktree-main-status-cache.test.ts | 110 ----- src/main/worktree.ts | 287 +------------ src/renderer/App.tsx | 8 - src/renderer/build-backend.ts | 10 - src/renderer/components/MobileRightPanel.tsx | 20 +- src/renderer/components/PRStatusPanel.tsx | 386 +----------------- src/renderer/components/RightColumn.tsx | 22 +- .../components/RightColumnToolbar.tsx | 1 - src/renderer/components/Settings.tsx | 18 +- src/renderer/store.ts | 19 - src/renderer/types.ts | 33 -- src/shared/state/prs.test.ts | 23 -- src/shared/state/prs.ts | 38 +- src/shared/state/repo-configs.test.ts | 41 +- src/shared/state/repo-configs.ts | 12 +- 21 files changed, 117 insertions(+), 1215 deletions(-) delete mode 100644 src/main/local-merge.test.ts delete mode 100644 src/main/local-merge.ts delete mode 100644 src/main/worktree-main-status-cache.test.ts diff --git a/src/main/index.ts b/src/main/index.ts index 43a91bf38..594933cad 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -107,8 +107,7 @@ import { getWeeklyStats } from './weekly-stats' import { discoverTools, runTool } from './tools' import type { TerminalTab, PaneNode, PaneLeaf } from '../shared/state/terminals' import { findTabById, getLeaves, mapLeaves } from '../shared/state/terminals' -import { createLocalMergeOps } from './local-merge' -import { resolveCommitSha, listWorktrees, listBranches, continueWorktree, isWorktreeDirty, defaultWorktreeDir, getChangedFiles, getFileDiff, getBranchCommits, getCommitDiff, getCommitMeta, getCommitChangedFiles, getCommitFileDiffSides, getCommitRangeChangedFiles, getCommitRangeFileDiffSides, getMainWorktreeStatus, prepareMainForMerge, mergeWorktreeLocally, getBranchSha, previewMergeConflicts, getBranchDiffStats, listAllFiles, listRecentCommitShas, readWorktreeFile, readWorktreeFileBinary, writeWorktreeFile, getFileDiffSides, getCurrentBranch, renameWorktreeBranch, unsymlinkClaudeSettings, readClaudeAllowEntries, pruneWorktrees, type MergeStrategy } from './worktree' +import { resolveCommitSha, listWorktrees, listBranches, continueWorktree, isWorktreeDirty, defaultWorktreeDir, getChangedFiles, getFileDiff, getBranchCommits, getCommitDiff, getCommitMeta, getCommitChangedFiles, getCommitFileDiffSides, getCommitRangeChangedFiles, getCommitRangeFileDiffSides, getBranchDiffStats, listAllFiles, listRecentCommitShas, readWorktreeFile, readWorktreeFileBinary, writeWorktreeFile, getFileDiffSides, getCurrentBranch, renameWorktreeBranch, unsymlinkClaudeSettings, readClaudeAllowEntries, pruneWorktrees } from './worktree' import { listOpenPRs, getPRByNumber, testToken, starRepo, unstarRepo, isRepoStarred, mergePR, approvePR, getRepoInfo, type GitHubMergeMethod, type MergePRResult, type PRLookupResult } from './github' import { AVAILABLE_EDITORS, DEFAULT_EDITOR_ID, openInEditor } from './editor' import { resolveEditorId } from '../shared/editor-resolve' @@ -2878,46 +2877,6 @@ function registerIpcHandlers(): void { return getWeeklyStats(snap.prs, snap.worktrees) }) - transport.onRequest('worktree:mainStatus', async (_ctx, repoRoot: string) => { - if (!repoRoot) throw new Error('No repo root provided') - return getMainWorktreeStatus(repoRoot) - }) - - transport.onRequest('worktree:previewMerge', async (_ctx, repoRoot: string, sourceBranch: string, worktreePath?: string) => { - if (!repoRoot) throw new Error('No repo root provided') - let branch = sourceBranch - if (worktreePath) { - const resolved = await getCurrentBranch(worktreePath) - if (resolved) branch = resolved - } - const status = await getMainWorktreeStatus(repoRoot) - return previewMergeConflicts(repoRoot, branch, status.baseBranch) - }) - - const localMerge = createLocalMergeOps({ - dispatch: (event) => store.dispatch(event), - getCurrentBranch, - mergeWorktreeLocally, - prepareMainForMerge, - getBranchSha, - recordLocallyMerged: (branch, sha) => { - if (!config.locallyMerged) config.locallyMerged = {} - config.locallyMerged[branch] = sha - saveConfig(config) - }, - refreshAll: () => void prPoller.refreshAll() - }) - - transport.onRequest('worktree:prepareMain', (_ctx, repoRoot: string) => - localMerge.prepareMain(repoRoot) - ) - - transport.onRequest( - 'worktree:mergeLocal', - (_ctx, repoRoot: string, sourceBranch: string, strategy: MergeStrategy, worktreePath?: string) => - localMerge.mergeLocal(repoRoot, sourceBranch, strategy, worktreePath) - ) - // Legacy worktree:mergedStatus handler is gone — the computation is now // inlined in PRPoller.refreshAll, which runs across all roots in one pass // and dispatches prs/mergedChanged. diff --git a/src/main/local-merge.test.ts b/src/main/local-merge.test.ts deleted file mode 100644 index 5fcaa14c5..000000000 --- a/src/main/local-merge.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { describe, it, expect, vi } from 'vitest' -import { createLocalMergeOps, type LocalMergeDeps } from './local-merge' -import type { MainWorktreeStatus, MergeLocalResult } from './worktree' - -function deferred(): { promise: Promise; resolve: (v: T) => void; reject: (e: unknown) => void } { - let resolve!: (v: T) => void - let reject!: (e: unknown) => void - const promise = new Promise((res, rej) => { - resolve = res - reject = rej - }) - return { promise, resolve, reject } -} - -const RESULT: MergeLocalResult = { - ok: true, - strategy: 'squash', - mergedBranch: 'feat', - baseBranch: 'main', - mainPath: '/repo' -} -const STATUS = { ready: true } as MainWorktreeStatus - -function makeDeps(overrides: Partial = {}): LocalMergeDeps { - return { - dispatch: vi.fn(), - getCurrentBranch: vi.fn(async () => 'feat'), - mergeWorktreeLocally: vi.fn(async () => RESULT), - prepareMainForMerge: vi.fn(async () => STATUS), - getBranchSha: vi.fn(async () => 'sha1'), - recordLocallyMerged: vi.fn(), - refreshAll: vi.fn(), - ...overrides - } -} - -describe('createLocalMergeOps', () => { - it('dispatches started, records the SHA, and finishes as merged', async () => { - const deps = makeDeps() - const ops = createLocalMergeOps(deps) - await expect(ops.mergeLocal('/repo', 'feat', 'squash', '/wt/a')).resolves.toBe(RESULT) - expect(deps.recordLocallyMerged).toHaveBeenCalledWith('feat', 'sha1') - expect(deps.refreshAll).toHaveBeenCalled() - expect(vi.mocked(deps.dispatch).mock.calls.map((c) => c[0])).toEqual([ - { type: 'prs/localMergeStarted', payload: { path: '/wt/a' } }, - { type: 'prs/localMergeFinished', payload: { path: '/wt/a', merged: true } } - ]) - }) - - it('finishes as not merged when the merge throws', async () => { - const deps = makeDeps({ mergeWorktreeLocally: vi.fn(async () => { throw new Error('conflict') }) }) - const ops = createLocalMergeOps(deps) - await expect(ops.mergeLocal('/repo', 'feat', 'squash', '/wt/a')).rejects.toThrow('conflict') - expect(deps.dispatch).toHaveBeenLastCalledWith({ - type: 'prs/localMergeFinished', - payload: { path: '/wt/a', merged: false } - }) - }) - - it('finishes as not merged when no SHA could be recorded', async () => { - const deps = makeDeps({ getBranchSha: vi.fn(async () => null) }) - const ops = createLocalMergeOps(deps) - await ops.mergeLocal('/repo', 'feat', 'squash', '/wt/a') - expect(deps.recordLocallyMerged).not.toHaveBeenCalled() - expect(deps.dispatch).toHaveBeenLastCalledWith({ - type: 'prs/localMergeFinished', - payload: { path: '/wt/a', merged: false } - }) - }) - - it('refuses a second merge or prepare into the same repo while one runs', async () => { - const gate = deferred() - const deps = makeDeps({ mergeWorktreeLocally: vi.fn(() => gate.promise) }) - const ops = createLocalMergeOps(deps) - const first = ops.mergeLocal('/repo', 'feat', 'squash', '/wt/a') - await expect(ops.mergeLocal('/repo', 'other', 'squash', '/wt/b')).rejects.toThrow(/in progress/) - await expect(ops.prepareMain('/repo')).rejects.toThrow(/in progress/) - // The refused attempt must not mark its worktree as merging. - expect(deps.dispatch).not.toHaveBeenCalledWith({ - type: 'prs/localMergeStarted', - payload: { path: '/wt/b' } - }) - // A different repo is unaffected. - await expect(ops.prepareMain('/other-repo')).resolves.toBe(STATUS) - gate.resolve(RESULT) - await first - // Lock released once the first settles. - await expect(ops.mergeLocal('/repo', 'other', 'squash', '/wt/b')).resolves.toBe(RESULT) - }) - - it('releases the lock after a failed prepare', async () => { - const deps = makeDeps({ prepareMainForMerge: vi.fn(async () => { throw new Error('dirty') }) }) - const ops = createLocalMergeOps(deps) - await expect(ops.prepareMain('/repo')).rejects.toThrow('dirty') - await expect(ops.mergeLocal('/repo', 'feat', 'squash')).resolves.toBe(RESULT) - }) -}) diff --git a/src/main/local-merge.ts b/src/main/local-merge.ts deleted file mode 100644 index 284cad2ae..000000000 --- a/src/main/local-merge.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { MainWorktreeStatus, MergeLocalResult, MergeStrategy } from './worktree' -import type { StateEvent } from '../shared/state' - -export interface LocalMergeDeps { - dispatch: (event: StateEvent) => void - getCurrentBranch: (worktreePath: string) => Promise - mergeWorktreeLocally: ( - repoRoot: string, - branch: string, - strategy: MergeStrategy - ) => Promise - prepareMainForMerge: (repoRoot: string) => Promise - getBranchSha: (repoRoot: string, branch: string) => Promise - /** Persist `branch` as merged at `sha` (config.locallyMerged). */ - recordLocallyMerged: (branch: string, sha: string) => void - refreshAll: () => void -} - -/** The "Merge Locally" operations that write to a repo's main worktree. - * - * Both run in that one checkout, so two at once (a double click, a second - * client, another worktree's panel) would fight over the same index: one - * operation per repo, the rest refused up front. */ -export function createLocalMergeOps(deps: LocalMergeDeps): { - prepareMain: (repoRoot: string) => Promise - mergeLocal: ( - repoRoot: string, - sourceBranch: string, - strategy: MergeStrategy, - worktreePath?: string - ) => Promise -} { - const busyRepos = new Set() - - function claim(repoRoot: string): void { - if (busyRepos.has(repoRoot)) { - throw new Error('Another merge operation on this repo is in progress.') - } - busyRepos.add(repoRoot) - } - - return { - async prepareMain(repoRoot) { - if (!repoRoot) throw new Error('No repo root provided') - claim(repoRoot) - try { - return await deps.prepareMainForMerge(repoRoot) - } finally { - busyRepos.delete(repoRoot) - } - }, - - async mergeLocal(repoRoot, sourceBranch, strategy, worktreePath) { - if (!repoRoot) throw new Error('No repo root provided') - claim(repoRoot) - // Only true once the merge SHA is persisted, so the optimistic - // mergedByPath flag matches what the poller will derive next time. - let merged = false - try { - // Inside the try so a throwing listener can't strand the lock. - if (worktreePath) { - deps.dispatch({ type: 'prs/localMergeStarted', payload: { path: worktreePath } }) - } - let branch = sourceBranch - if (worktreePath) { - const resolved = await deps.getCurrentBranch(worktreePath) - if (resolved) branch = resolved - } - const result = await deps.mergeWorktreeLocally(repoRoot, branch, strategy) - const sha = await deps.getBranchSha(repoRoot, branch) - if (sha) { - deps.recordLocallyMerged(branch, sha) - merged = true - } - deps.refreshAll() - return result - } finally { - busyRepos.delete(repoRoot) - if (worktreePath) { - deps.dispatch({ - type: 'prs/localMergeFinished', - payload: { path: worktreePath, merged } - }) - } - } - } - } -} diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 144be1a00..e97f459b0 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -149,8 +149,8 @@ export interface Config { // New worktrees are branched from: 'remote' = fetch origin then branch // from origin/, 'local' = branch from current HEAD. worktreeBase?: 'remote' | 'local' - // Default strategy for "Merge locally" action. Auto-updates to whatever - // was last used unless the user pinned one in Settings. + // How the PR panel's merge button merges on GitHub ('fast-forward' maps + // to GitHub's rebase method). mergeStrategy?: 'squash' | 'merge-commit' | 'fast-forward' // Density of each sidebar worktree row. 'comfy' (default) stacks the // detail cluster on a second line; 'compact' folds it onto the right of @@ -195,10 +195,11 @@ export interface Config { // Sidebar project drag order as section scope keys (see // SettingsState.sidebarProjectOrder). Absent until the user reorders. sidebarProjectOrder?: string[] - // Branches that have been merged locally via Ness, keyed by branch name. - // Value is the branch-tip SHA at merge time — if the branch later advances - // past this SHA, the flag is considered stale and the branch is no longer - // shown as merged. + // Branches merged by the since-removed "Merge Locally" action, keyed by + // branch name. Value is the branch-tip SHA at merge time — if the branch + // later advances past this SHA, the flag is considered stale and pruned. + // Nothing adds entries any more; the map is read only so worktrees merged + // that way keep grouping under Merged / Closed until they're removed. // Shell command to run after a worktree is created. Runs via login shell // with cwd=worktree and env vars HARNESS_WORKTREE_PATH, HARNESS_BRANCH, // HARNESS_REPO_ROOT. Failures are logged but don't block creation. diff --git a/src/main/repo-config.test.ts b/src/main/repo-config.test.ts index 6c47ff9d1..e964ec05b 100644 --- a/src/main/repo-config.test.ts +++ b/src/main/repo-config.test.ts @@ -132,3 +132,51 @@ describe('migrateRepoConfigFilename', () => { expect(loadRepoConfig(repo).setupCommand).toBe('current') }) }) + +// The Merge Locally panel was removed. Repo config files are usually +// committed, so ones written before then must keep loading, and we never +// rewrite them just because they carry its keys. +describe('repo configs from before Merge Locally was removed', () => { + const OLD = { + version: 1, + setupCommand: 'npm ci', + mergeStrategy: 'merge-commit', + hideMergePanel: true, + hiddenRightPanels: { merge: true, commits: true }, + rightPanelOrder: ['merge', 'pr', 'commits'], + someFutureKey: { nested: 1 } + } + + it('loads without throwing and keeps the fields still in use', () => { + write(NEW, OLD) + const cfg = loadRepoConfig(repo) + expect(cfg.setupCommand).toBe('npm ci') + expect(cfg.mergeStrategy).toBe('merge-commit') + }) + + it('loading does not touch the file on disk', () => { + write(LEGACY, OLD) + const before = readFileSync(join(repo, LEGACY), 'utf-8') + loadRepoConfig(repo) + expect(readFileSync(join(repo, LEGACY), 'utf-8')).toBe(before) + expect(existsSync(join(repo, NEW))).toBe(false) + }) + + it('drops the merge panel keys on the next write', () => { + write(NEW, OLD) + const saved = saveRepoConfig(repo, loadRepoConfig(repo)) + expect(saved.hiddenRightPanels).toEqual({ commits: true }) + expect(saved.rightPanelOrder).toEqual(['pr', 'commits']) + const onDisk = JSON.parse(readFileSync(join(repo, NEW), 'utf-8')) + expect(onDisk).not.toHaveProperty('hideMergePanel') + expect(onDisk.mergeStrategy).toBe('merge-commit') + }) + + it('an order of only the removed panel is dropped entirely', () => { + const saved = saveRepoConfig(repo, { + setupCommand: 'x', + rightPanelOrder: ['merge'] as unknown as never + }) + expect(saved).not.toHaveProperty('rightPanelOrder') + }) +}) diff --git a/src/main/repo-config.ts b/src/main/repo-config.ts index 26a95a63e..6a06f65ca 100644 --- a/src/main/repo-config.ts +++ b/src/main/repo-config.ts @@ -17,6 +17,8 @@ export type { RepoConfig } // everyone's git status for a change they didn't make. const cache = new Map() +const REMOVED_MERGE_PANEL_KEY = 'merge' + /** The config file this repo actually uses: the new name if present or if * the repo has no config yet, otherwise the legacy one it already has. */ export function repoConfigFilename(repoRoot: string): string { @@ -58,11 +60,15 @@ export function saveRepoConfig(repoRoot: string, next: RepoConfig): RepoConfig { if (setup) cleaned.setupCommand = setup if (teardown) cleaned.teardownCommand = teardown if (next.mergeStrategy) cleaned.mergeStrategy = next.mergeStrategy - // Migrate legacy hideMergePanel / hidePrPanel into hiddenRightPanels - // on write. Only the new field is persisted going forward. + // Migrate legacy hidePrPanel into hiddenRightPanels on write. Only the + // new field is persisted going forward. const hidden: Record = { ...(next.hiddenRightPanels || {}) } - if (next.hideMergePanel && hidden.merge === undefined) hidden.merge = true if (next.hidePrPanel && hidden.pr === undefined) hidden.pr = true + // The Merge Locally panel is gone. Files written before then may still + // carry its `hideMergePanel` / `hiddenRightPanels.merge` / order entry; + // they're ignored on read and dropped here, on the next write the user + // makes anyway — never rewritten on their own. + delete hidden[REMOVED_MERGE_PANEL_KEY] // Compact: drop `false` entries that match the default visibility // (i.e. NOT in DEFAULT_HIDDEN_RIGHT_PANELS). For keys that default to // hidden, `false` is a meaningful opt-in signal — keep it. @@ -73,7 +79,8 @@ export function saveRepoConfig(repoRoot: string, next: RepoConfig): RepoConfig { } if (Object.keys(hidden).length > 0) cleaned.hiddenRightPanels = hidden if (Array.isArray(next.rightPanelOrder) && next.rightPanelOrder.length > 0) { - cleaned.rightPanelOrder = [...next.rightPanelOrder] + const order = next.rightPanelOrder.filter((k) => (k as string) !== REMOVED_MERGE_PANEL_KEY) + if (order.length > 0) cleaned.rightPanelOrder = order } const hasAny = Object.keys(cleaned).some((k) => k !== 'version') diff --git a/src/main/worktree-main-status-cache.test.ts b/src/main/worktree-main-status-cache.test.ts deleted file mode 100644 index 0c362b70f..000000000 --- a/src/main/worktree-main-status-cache.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, it, expect, beforeEach, afterEach } from 'vitest' -/* These spawn real git. Under a full parallel suite run a handful of spawns - * can blow past vitest's 5s default, so every case here sets its own budget — - * a timeout in this file would otherwise read as a caching regression. */ -import { execFileSync } from 'child_process' -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs' -import { tmpdir } from 'os' -import { join } from 'path' -import { getMainWorktreeStatus, invalidateMainWorktreeStatus } from './worktree' - -function git(cwd: string, args: string[]): string { - return execFileSync('git', args, { - cwd, - env: { - ...process.env, - GIT_AUTHOR_NAME: 't', - GIT_AUTHOR_EMAIL: 't@t', - GIT_COMMITTER_NAME: 't', - GIT_COMMITTER_EMAIL: 't@t' - } - }).toString() -} - -const TIMEOUT = 60_000 - -describe('getMainWorktreeStatus caching', () => { - let repo: string - - beforeEach(() => { - invalidateMainWorktreeStatus() - repo = mkdtempSync(join(tmpdir(), 'harness-mainstatus-')) - git(repo, ['init', '-q', '-b', 'main']) - git(repo, ['config', 'commit.gpgsign', 'false']) - writeFileSync(join(repo, 'f.txt'), 'base\n') - git(repo, ['add', 'f.txt']) - git(repo, ['commit', '-q', '-m', 'base']) - }) - - afterEach(() => { - invalidateMainWorktreeStatus() - rmSync(repo, { recursive: true, force: true }) - }) - - // The switch-time shape: the panel asks directly while worktree:previewMerge - // asks internally, at the same instant. One underlying read, not two. - it('collapses concurrent callers onto a single read', async () => { - const [a, b] = await Promise.all([ - getMainWorktreeStatus(repo), - getMainWorktreeStatus(repo) - ]) - expect(a).toBe(b) - }, TIMEOUT) - - it('serves a later caller from cache within the TTL', async () => { - const first = await getMainWorktreeStatus(repo) - expect(await getMainWorktreeStatus(repo)).toBe(first) - }, TIMEOUT) - - it('re-reads after an explicit invalidation', async () => { - const first = await getMainWorktreeStatus(repo) - invalidateMainWorktreeStatus(repo) - const second = await getMainWorktreeStatus(repo) - expect(second).not.toBe(first) - expect(second).toEqual(first) - }, TIMEOUT) - - it('re-reads when forced, and picks up a change the cache would have hidden', async () => { - const clean = await getMainWorktreeStatus(repo) - expect(clean.isDirty).toBe(false) - expect(clean.ready).toBe(true) - - writeFileSync(join(repo, 'f.txt'), 'dirty\n') - // Unforced within the TTL still reports the stale answer — that's the - // trade the TTL makes, and why the merge gate forces. - expect((await getMainWorktreeStatus(repo)).isDirty).toBe(false) - - const forced = await getMainWorktreeStatus(repo, { force: true }) - expect(forced.isDirty).toBe(true) - expect(forced.ready).toBe(false) - }, TIMEOUT) - - it("keys by repo, so a second repo is not served the first one's answer", async () => { - const other = mkdtempSync(join(tmpdir(), 'harness-mainstatus-b-')) - try { - // `master` rather than an arbitrary name: getLocalBaseBranch only - // recognises main/master, and falls back to the literal 'main' for - // anything else — which would mask a key collision instead of exposing it. - git(other, ['init', '-q', '-b', 'master']) - git(other, ['config', 'commit.gpgsign', 'false']) - writeFileSync(join(other, 'g.txt'), 'x\n') - git(other, ['add', 'g.txt']) - git(other, ['commit', '-q', '-m', 'x']) - - const a = await getMainWorktreeStatus(repo) - const b = await getMainWorktreeStatus(other) - expect(a.path).not.toBe(b.path) - expect(a.baseBranch).toBe('main') - expect(b.baseBranch).toBe('master') - } finally { - rmSync(other, { recursive: true, force: true }) - } - }, TIMEOUT) - - it('does not cache a failure', async () => { - const missing = join(tmpdir(), 'harness-mainstatus-does-not-exist') - await expect(getMainWorktreeStatus(missing)).rejects.toThrow() - // A cached rejection here would poison the repo for the whole TTL. - await expect(getMainWorktreeStatus(missing)).rejects.toThrow() - }, TIMEOUT) -}) diff --git a/src/main/worktree.ts b/src/main/worktree.ts index 7d32572b8..0ee01f199 100644 --- a/src/main/worktree.ts +++ b/src/main/worktree.ts @@ -37,7 +37,7 @@ function readOnlyGitEnv(): NodeJS.ProcessEnv { /** Every read-only git spawn goes through here so the concurrency gate in * git-limiter.ts sees all of them. Gating at the leaf exec — rather than around * a whole helper — is what keeps callers that issue several reads in sequence - * (getMainWorktreeStatus, resolveDefaultBaseRef) from holding a permit while + * (resolveDefaultBaseRef) from holding a permit while * waiting for one, which would deadlock at the cap. Writes bypass this on * purpose; see the module comment in git-limiter.ts. */ function execGitRead( @@ -1331,26 +1331,6 @@ export async function getFileDiffSides( return finish(combineDiffSides(original, modified, deleted ? undefined : read.error)) } -export type MergeStrategy = 'squash' | 'merge-commit' | 'fast-forward' - -export interface MainWorktreeStatus { - path: string - currentBranch: string - baseBranch: string - isOnBase: boolean - isDirty: boolean - /** True when the worktree is ready to accept a merge without any fixups */ - ready: boolean -} - -/** Resolve the local base branch name (no remote prefix) — "main" or "master". */ -async function getLocalBaseBranch(repoRoot: string): Promise { - const ref = await getDefaultBaseRef(repoRoot) - const name = ref.startsWith('origin/') ? ref.slice('origin/'.length) : ref - if (!name || name === 'HEAD') return 'main' - return name -} - /** Get the current branch of a worktree, or empty string if detached. */ export async function getCurrentBranch(worktreePath: string): Promise { try { @@ -1450,271 +1430,6 @@ export async function renameWorktreeBranch( return { ok: true, oldBranch, branch: newBranch, renamed: true } } -// Main-worktree status is asked for far more often than it changes. It's keyed -// by repoRoot, not worktree, so switching between two worktrees of the same -// repo recomputes an identical answer — and a single switch asks for it twice -// over, because `worktree:previewMerge` needs it internally while the panel -// requests it directly in parallel. Each miss is four sequential git spawns, -// one of which is a full `git status` on the main checkout. -// -// An in-flight entry is what collapses the concurrent pair; the TTL is what -// covers flipping back and forth between worktrees. It's deliberately short — -// this answer gates the "main isn't ready" fixup button, so it should track -// reality at human timescale — and any Ness-side mutation of main busts it -// outright rather than waiting the TTL out. -// -// The TTL runs from when the read *settles*, not from when it was dispatched. -// Dispatch-time would be self-defeating on exactly the repos this exists for: -// where the four spawns take longer than the TTL, every entry would land -// already expired and the cache would never serve anyone. -const MAIN_STATUS_TTL_MS = 3000 -interface MainStatusEntry { - /** null while the read is still in flight — such an entry is always fresh, - * which is what makes concurrent callers join rather than each spawn git. */ - settledAt: number | null - promise: Promise -} -const mainStatusCache = new Map() - -export function invalidateMainWorktreeStatus(repoRoot?: string): void { - if (repoRoot === undefined) mainStatusCache.clear() - else mainStatusCache.delete(repoRoot) -} - -/** Report status of the main worktree for a local merge. */ -export async function getMainWorktreeStatus( - repoRoot: string, - opts: { force?: boolean } = {} -): Promise { - const hit = mainStatusCache.get(repoRoot) - if ( - !opts.force && - hit && - (hit.settledAt === null || Date.now() - hit.settledAt < MAIN_STATUS_TTL_MS) - ) { - return hit.promise - } - - const entry: MainStatusEntry = { - settledAt: null, - promise: readMainWorktreeStatus(repoRoot).then( - (value) => { - if (mainStatusCache.get(repoRoot) === entry) entry.settledAt = Date.now() - return value - }, - (err) => { - // Never let a failure stick around for the TTL — the next caller - // should get a real attempt, not a cached rejection. - if (mainStatusCache.get(repoRoot) === entry) mainStatusCache.delete(repoRoot) - throw err - } - ) - } - mainStatusCache.set(repoRoot, entry) - return entry.promise -} - -async function readMainWorktreeStatus(repoRoot: string): Promise { - const t0 = performance.now() - let walledExec = 0 - let cumExec = 0 - const execParts: number[] = [] - - const t1 = performance.now() - const trees = await listWorktrees(repoRoot) - const ms1 = performance.now() - t1 - walledExec += ms1; cumExec += ms1; execParts.push(ms1) - - const main = trees.find((t) => t.isMain) || trees[0] - const mainPath = main?.path || repoRoot - - const t2 = performance.now() - const baseBranch = await getLocalBaseBranch(repoRoot) - const ms2 = performance.now() - t2 - walledExec += ms2; cumExec += ms2; execParts.push(ms2) - - const t3 = performance.now() - const currentBranch = await getCurrentBranch(mainPath) - const ms3 = performance.now() - t3 - walledExec += ms3; cumExec += ms3; execParts.push(ms3) - - const t4 = performance.now() - const isDirty = await isWorktreeDirty(mainPath) - const ms4 = performance.now() - t4 - walledExec += ms4; cumExec += ms4; execParts.push(ms4) - - const isOnBase = currentBranch === baseBranch - logGitOp('getMainWorktreeStatus', {}, t0, walledExec, cumExec, 0, execParts) - return { - path: mainPath, - currentBranch, - baseBranch, - isOnBase, - isDirty, - ready: isOnBase && !isDirty - } -} - -/** Stash and/or checkout base in the main worktree so a merge can proceed. - * Stashing is auto-labeled so the user can find it later via `git stash list`. */ -export async function prepareMainForMerge(repoRoot: string): Promise { - const status = await getMainWorktreeStatus(repoRoot) - if (status.isDirty) { - log('worktree', `stashing dirty changes in main worktree ${status.path}`) - await execFileAsync( - 'git', - ['stash', 'push', '--include-untracked', '-m', 'harness: auto-stash before local merge'], - { cwd: status.path } - ) - } - if (!status.isOnBase) { - log('worktree', `checking out ${status.baseBranch} in main worktree ${status.path}`) - await execFileAsync('git', ['checkout', status.baseBranch], { cwd: status.path }) - } - return getMainWorktreeStatus(repoRoot, { force: true }) -} - -export interface MergeLocalResult { - ok: true - strategy: MergeStrategy - mergedBranch: string - baseBranch: string - mainPath: string -} - -/** Merge a worktree's branch into the local base branch inside the main worktree. - * Requires the main worktree to already be on base and clean — caller should - * run prepareMainForMerge first if needed. On conflict, aborts and throws. */ -export async function mergeWorktreeLocally( - repoRoot: string, - sourceBranch: string, - strategy: MergeStrategy -): Promise { - // Forced: this read is the gate on whether merging is safe at all, so it - // must reflect the repo right now rather than up to a TTL ago. - const status = await getMainWorktreeStatus(repoRoot, { force: true }) - if (!status.ready) { - throw new Error( - `Main worktree is not ready: ${status.isDirty ? 'has uncommitted changes' : `on ${status.currentBranch || 'detached HEAD'}, not ${status.baseBranch}`}` - ) - } - if (sourceBranch === status.baseBranch) { - throw new Error(`Cannot merge ${sourceBranch} into itself`) - } - - log('worktree', `merging ${sourceBranch} into ${status.baseBranch} (${strategy}) at ${status.path}`) - - try { - if (strategy === 'squash') { - await execFileAsync('git', ['merge', '--squash', sourceBranch], { cwd: status.path }) - // --squash stages the changes without committing. Commit them now. - await execFileAsync( - 'git', - ['commit', '-m', `${sourceBranch} (squashed)`], - { cwd: status.path } - ) - } else if (strategy === 'merge-commit') { - await execFileAsync( - 'git', - ['merge', '--no-ff', '-m', `Merge branch '${sourceBranch}'`, sourceBranch], - { cwd: status.path } - ) - } else { - await execFileAsync('git', ['merge', '--ff-only', sourceBranch], { cwd: status.path }) - } - } catch (err) { - // Extract stderr from the execFile error — it's where git's actual - // failure reason lives, and err.message only carries the command line. - const stderr = - err && typeof err === 'object' && 'stderr' in err - ? String((err as { stderr: unknown }).stderr || '').trim() - : '' - const stdout = - err && typeof err === 'object' && 'stdout' in err - ? String((err as { stdout: unknown }).stdout || '').trim() - : '' - const baseMessage = err instanceof Error ? err.message : String(err) - const detail = stderr || stdout || baseMessage - - log('worktree', `merge failed: ${detail}`) - - // Abort any partial merge/squash state so the user is left clean. - try { - await execFileAsync('git', ['merge', '--abort'], { cwd: status.path }) - } catch {} - // For --squash the failure is typically at the `git commit` step (e.g. - // nothing to commit because the branch is equivalent to base). In that - // case `merge --abort` is a no-op, so also reset any staged changes. - try { - await execFileAsync('git', ['reset', '--hard', 'HEAD'], { cwd: status.path }) - } catch {} - - // Friendlier message for the common "nothing to commit" case on squash - if (strategy === 'squash' && /nothing to commit/i.test(detail)) { - throw new Error( - `Nothing to merge — ${sourceBranch} has no changes relative to ${status.baseBranch}.` - ) - } - throw new Error(`Merge failed and was aborted: ${detail}`) - } finally { - // Main moved either way — a landed merge, or the abort/reset on the - // failure path. Dropped after the fact rather than before, so a read - // racing the merge can't repopulate the entry with mid-merge state. - invalidateMainWorktreeStatus(repoRoot) - } - - return { - ok: true, - strategy, - mergedBranch: sourceBranch, - baseBranch: status.baseBranch, - mainPath: status.path - } -} - -export interface MergeConflictPreview { - hasConflict: boolean - files: string[] - /** True if git merge-tree isn't supported by the installed git (pre-2.38). */ - unsupported?: boolean -} - -/** Preview a three-way merge of `sourceBranch` into `baseBranch` in-memory - * via `git merge-tree --write-tree`. Doesn't touch the working tree or any - * refs. Returns the list of conflicted file paths on conflict. */ -export async function previewMergeConflicts( - repoRoot: string, - sourceBranch: string, - baseBranch: string -): Promise { - try { - await execGitRead( - ['merge-tree', '--write-tree', '--name-only', baseBranch, sourceBranch], - { cwd: repoRoot } - ) - return { hasConflict: false, files: [] } - } catch (err) { - if (err && typeof err === 'object') { - const e = err as { code?: number; stdout?: string; stderr?: string; message?: string } - // git merge-tree prints the tree OID on line 1, then conflicted file - // paths on subsequent lines (with --name-only). Exit code 1 = conflicts. - if (e.code === 1) { - const lines = String(e.stdout || '').split('\n').map((s) => s.trim()).filter(Boolean) - // Drop the first line (tree OID) — the rest are file paths. - const files = lines.slice(1) - return { hasConflict: true, files } - } - // "unknown switch" / unsupported → older git - const stderr = String(e.stderr || e.message || '') - if (/unknown (option|switch)|usage: git merge-tree/i.test(stderr)) { - return { hasConflict: false, files: [], unsupported: true } - } - } - // Unknown error — treat as "can't tell", don't block the user - return { hasConflict: false, files: [], unsupported: true } - } -} - /** Resolve a branch ref to its current SHA, or null if it doesn't exist. */ export async function getBranchSha(repoRoot: string, branch: string): Promise { try { diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx index d3ab4ac1d..215ca8fd8 100644 --- a/src/renderer/App.tsx +++ b/src/renderer/App.tsx @@ -775,12 +775,6 @@ function DesktopApp(): JSX.Element { ? repoConfigs[activeRepoRoot] ?? null : null - // After a local merge, kick the poller so the merged flag and PR state - // propagate to the UI without waiting for the 5-min interval. - const refreshMergedStatus = useCallback(() => { - void backend.refreshPRsAll() - }, []) - // Ask main for a single-worktree PR refresh. Used by the activity observer // when a terminal enters the "waiting" state (likely just pushed). const fetchPRStatus = useCallback((wtPath: string) => { @@ -2285,8 +2279,6 @@ function DesktopApp(): JSX.Element { activeRepoConfig={activeRepoConfig} onRefreshPRs={fetchAllPRStatuses} onOpenGithubSettings={handleOpenGithubSettings} - onMerged={refreshMergedStatus} - onRemoveWorktree={handleDeleteWorktree} onOpenDiff={handleOpenDiff} onOpenCommitFileDiff={handleOpenCommitFileDiff} onOpenFile={handleOpenFile} diff --git a/src/renderer/build-backend.ts b/src/renderer/build-backend.ts index 34f1bf2ae..e17de9641 100644 --- a/src/renderer/build-backend.ts +++ b/src/renderer/build-backend.ts @@ -246,16 +246,6 @@ export function buildBackend( toHash: string, filePath: string ) => req('worktree:commitRangeFileDiffSides', worktreePath, fromHash, toHash, filePath), - getMainWorktreeStatus: (repoRoot: string) => req('worktree:mainStatus', repoRoot), - prepareMainForMerge: (repoRoot: string) => req('worktree:prepareMain', repoRoot), - previewMergeConflicts: (repoRoot: string, sourceBranch: string, worktreePath?: string) => - req('worktree:previewMerge', repoRoot, sourceBranch, worktreePath), - mergeWorktreeLocally: ( - repoRoot: string, - sourceBranch: string, - strategy: 'squash' | 'merge-commit' | 'fast-forward', - worktreePath?: string - ) => req('worktree:mergeLocal', repoRoot, sourceBranch, strategy, worktreePath), refreshPRsAll: () => req('prs:refreshAll'), refreshPRsAllIfStale: () => req('prs:refreshAllIfStale'), diff --git a/src/renderer/components/MobileRightPanel.tsx b/src/renderer/components/MobileRightPanel.tsx index 26fb445c8..7dad351df 100644 --- a/src/renderer/components/MobileRightPanel.tsx +++ b/src/renderer/components/MobileRightPanel.tsx @@ -1,7 +1,7 @@ import { useCallback } from 'react' import { useRepoConfigs, useSettings } from '../store' import { useBackend } from '../backend' -import { PRStatusPanel, MergeLocallyPanel } from './PRStatusPanel' +import { PRStatusPanel } from './PRStatusPanel' import { BranchCommitsPanel } from './BranchCommitsPanel' import { CostPanel } from './CostPanel' import type { Worktree, PRStatus } from '../types' @@ -14,7 +14,7 @@ interface MobileRightPanelProps { } // Fullscreen takeover that surfaces the useful slices of the desktop -// right panel — PR status, local merge, branch commits, cost. File +// right panel — PR status, branch commits, cost. File // panels (ChangedFiles / AllFiles) are intentionally omitted: their // primary interaction is "tap a file to open a diff tab", and mobile // can't render diff/file tabs meaningfully. @@ -35,15 +35,6 @@ export function MobileRightPanel({ void backend.refreshPRsAll() }, [backend]) - const handleRemoveWorktree = useCallback( - (path: string): void => { - if (!activeWorktree) return - void backend.removeWorktree(activeWorktree.repoRoot, path) - onClose() - }, - [activeWorktree, onClose, backend] - ) - return (
{!activeWorktree && ( @@ -61,13 +52,6 @@ export function MobileRightPanel({ onRefresh={handleRefresh} onConnectGithub={onClose} /> -
diff --git a/src/renderer/components/PRStatusPanel.tsx b/src/renderer/components/PRStatusPanel.tsx index 94fb16639..b104bbb28 100644 --- a/src/renderer/components/PRStatusPanel.tsx +++ b/src/renderer/components/PRStatusPanel.tsx @@ -1,6 +1,6 @@ import { useState, useEffect, useCallback, useRef } from 'react' -import { ExternalLink, GitMerge, GitMergeConflict, ChevronDown, Check, GitPullRequest, RefreshCw, Loader2, ArrowDown, CircleDot, CircleCheck, Bot } from 'lucide-react' -import { useCiNotify, useLocalMergeState, useRepoConfigs, useSettings } from '../store' +import { ExternalLink, GitMerge, GitMergeConflict, Check, GitPullRequest, RefreshCw, Loader2, ArrowDown, CircleDot, CircleCheck, Bot } from 'lucide-react' +import { useCiNotify, useRepoConfigs, useSettings } from '../store' import { isCiNotifyEnabled } from '../../shared/state/ci-notify' import { useBackend } from '../backend' import type { @@ -9,8 +9,6 @@ import type { CheckStatus, Worktree, MergeStrategy, - MainWorktreeStatus, - MergeConflictPreview, GitHubMergeMethod, MergePRResult } from '../types' @@ -29,386 +27,6 @@ function firstLine(summary: string | undefined): string { return '' } -const STRATEGY_BUTTON_LABELS: Record = { - squash: 'Squash and merge', - 'merge-commit': 'Create a merge commit', - 'fast-forward': 'Fast-forward merge' -} - -const STRATEGY_MENU_LABELS: Record = { - squash: 'Squash and merge', - 'merge-commit': 'Create a merge commit', - 'fast-forward': 'Fast-forward merge' -} - -/** How long after a worktree switch to wait before simulating the merge. - * Long enough that scrubbing through worktrees fires none of them, short - * enough that the conflict warning is there by the time anyone reads it. */ -const CONFLICT_PREVIEW_DELAY_MS = 500 - -const STRATEGY_DESCRIPTIONS: Record = { - squash: - 'The commits from this branch will be combined into one commit on the base branch.', - 'merge-commit': - 'All commits from this branch will be added to the base branch via a merge commit.', - 'fast-forward': - 'Only merge if the base can fast-forward (--ff-only). Fails on divergent history.' -} - -interface MergeLocallyPanelProps { - pr: PRStatus | null | undefined - worktree?: Worktree | null - hasGithubToken?: boolean | null - onMerged?: () => void | Promise - onRemoveWorktree?: (worktreePath: string) => void | Promise -} - -/** Renders the "Merge Locally" right-panel when it's applicable (no PR, not main branch, - * GitHub connected). Returns null otherwise. */ -export function MergeLocallyPanel({ - pr, - worktree, - hasGithubToken, - onMerged, - onRemoveWorktree -}: MergeLocallyPanelProps): JSX.Element | null { - const needsGithubToken = hasGithubToken === false - const show = !needsGithubToken && pr === null && worktree && !worktree.isMain - if (!show || !worktree) return null - return ( - - {/* Keyed so each worktree gets its own instance: a merge started in one - worktree must never settle into another's view — a stale "Merged" - there would offer to remove a worktree that was never merged. */} - - - ) -} - -function MergeLocallyBody({ - worktree, - onMerged, - onRemoveWorktree -}: { - worktree: Worktree - onMerged?: () => void | Promise - onRemoveWorktree?: (worktreePath: string) => void | Promise -}): JSX.Element { - const backend = useBackend() - const [mainStatus, setMainStatus] = useState(null) - const [conflictPreview, setConflictPreview] = useState(null) - const [busy, setBusy] = useState<'idle' | 'checking' | 'fixing' | 'merging'>('idle') - const [error, setError] = useState(null) - const [success, setSuccess] = useState(null) - const [dismissed, setDismissed] = useState(false) - const [menuOpen, setMenuOpen] = useState(false) - const menuRef = useRef(null) - // The in-flight (or settled) preview for the current worktree, so a merge - // can wait on it rather than racing the deferral below. - const previewRef = useRef | null>(null) - - // Effective merge strategy = repo override → global default. Both come - // from the main-process store, so this re-renders automatically when - // either changes. - const repoConfigs = useRepoConfigs() - const globalStrategy = useSettings().mergeStrategy - const strategy: MergeStrategy = - repoConfigs[worktree.repoRoot]?.mergeStrategy || globalStrategy - const strategyLoaded = true - - const { repoRoot, branch, path } = worktree - - // In-flight and merged both come from the prs slice, so they survive - // switching away and back (and show on every client) — otherwise coming - // back mid-merge would offer the merge button again. `mergedLocally` also - // covers worktrees merged in an earlier session: they open on the merged - // view with Remove, since merging them again is never what's wanted. - const { - merging: mergeInFlight, - repoBusy, - merged: mergedLocally - } = useLocalMergeState(path, repoRoot) - - const refreshStatus = useCallback(async () => { - setBusy('checking') - try { - setMainStatus(await backend.getMainWorktreeStatus(repoRoot)) - } catch (err) { - setError(err instanceof Error ? err.message : String(err)) - } finally { - setBusy('idle') - } - }, [backend, repoRoot]) - - useEffect(() => { - void refreshStatus() - }, [refreshStatus]) - - // The conflict preview is a real three-way merge simulation (`git merge-tree - // --write-tree`) answering a question the user hasn't asked yet — it only - // matters once they're looking at the merge button. Running it on the switch - // itself put it on the click-to-populated path, so it waits for the switch to - // settle instead, which also means a run of rapid switches fires none at all. - useEffect(() => { - setConflictPreview(null) - previewRef.current = null - let cancelled = false - const timer = setTimeout(() => { - const pending = backend - .previewMergeConflicts(repoRoot, branch, path) - .catch(() => null) - previewRef.current = pending - void pending.then((preview) => { - if (!cancelled) setConflictPreview(preview) - }) - }, CONFLICT_PREVIEW_DELAY_MS) - return () => { - cancelled = true - clearTimeout(timer) - } - }, [backend, repoRoot, branch, path]) - - // Close dropdown on outside click - useEffect(() => { - if (!menuOpen) return - const handler = (e: MouseEvent): void => { - if (menuRef.current && !menuRef.current.contains(e.target as Node)) { - setMenuOpen(false) - } - } - window.addEventListener('mousedown', handler) - return () => window.removeEventListener('mousedown', handler) - }, [menuOpen]) - - const handlePickStrategy = useCallback((s: MergeStrategy) => { - setMenuOpen(false) - // Persist as new default — "last used wins". The store dispatch - // re-renders us with the new strategy automatically. - void backend.setMergeStrategy(s) - }, []) - - const handleFix = useCallback(async () => { - setError(null) - setBusy('fixing') - try { - const status = await backend.prepareMainForMerge(repoRoot) - setMainStatus(status) - } catch (err) { - setError(err instanceof Error ? err.message : String(err)) - } finally { - setBusy('idle') - } - }, [backend, repoRoot]) - - const handleMerge = useCallback(async () => { - if (!mainStatus) return - setError(null) - setSuccess(null) - setBusy('merging') - try { - // The preview is deferred, so on a fast click it may not have been - // started yet. Settle it here rather than letting the deferral quietly - // downgrade the conflict guard to "whatever had landed by click time". - const preview = await (previewRef.current ?? - backend.previewMergeConflicts(repoRoot, branch, path).catch(() => null)) - if (preview?.hasConflict) { - setConflictPreview(preview) - setError('Resolve merge conflicts before merging.') - return - } - // Persist strategy on use too, in case the user never opened the dropdown. - void backend.setMergeStrategy(strategy) - const result = await backend.mergeWorktreeLocally(repoRoot, branch, strategy, path) - setSuccess(`Merged into ${result.baseBranch}`) - if (onMerged) await onMerged() - } catch (err) { - setError(err instanceof Error ? err.message : String(err)) - } finally { - setBusy('idle') - } - }, [backend, mainStatus, strategy, repoRoot, branch, path, onMerged]) - - const handleRemoveAfterMerge = useCallback(async () => { - if (!onRemoveWorktree) return - await onRemoveWorktree(worktree.path) - }, [onRemoveWorktree, worktree.path]) - - const ready = mainStatus?.ready === true - const needsFix = mainStatus && !mainStatus.ready - const hasConflict = conflictPreview?.hasConflict === true - const merging = busy === 'merging' || mergeInFlight - const successMessage = - success ?? - (mergedLocally && !dismissed && !merging && mainStatus - ? `Merged into ${mainStatus.baseBranch}` - : null) - - return ( -
- {!successMessage && ( - <> -
- Merge {worktree.branch} - {mainStatus && ( - <> - {' '}into{' '} - {mainStatus.baseBranch} - - )} -
- - {/* GitHub-style split button */} -
-
- - -
- - {menuOpen && ( -
- {(['squash', 'merge-commit', 'fast-forward'] as MergeStrategy[]).map( - (s) => { - const active = s === strategy - return ( - - ) - } - )} -
- )} -
- - {hasConflict && conflictPreview && ( -
-
- Merge conflict - {conflictPreview.files.length > 0 && ( - <> - {' '}in{' '} - - {conflictPreview.files.length === 1 - ? conflictPreview.files[0] - : `${conflictPreview.files.length} files`} - - - )} - . Resolve before merging. -
- {conflictPreview.files.length > 1 && ( -
    - {conflictPreview.files.map((f) => ( -
  • - {f} -
  • - ))} -
- )} -
- )} - - {needsFix && ( -
-
- Main worktree isn't ready: - {mainStatus.isDirty && ' has uncommitted changes'} - {!mainStatus.isOnBase && ( - <> - {mainStatus.isDirty ? ' and' : ''} on{' '} - - {mainStatus.currentBranch || 'detached HEAD'} - - , not {mainStatus.baseBranch} - - )} - . -
- -
- )} - - {error && ( -
{error}
- )} - - )} - - {successMessage && ( -
-
{successMessage}
- {onRemoveWorktree && ( - - )} - -
- )} -
- ) -} - const STATE_LABELS: Record = { open: 'Open', draft: 'Draft', diff --git a/src/renderer/components/RightColumn.tsx b/src/renderer/components/RightColumn.tsx index 00f2197dc..7a8314350 100644 --- a/src/renderer/components/RightColumn.tsx +++ b/src/renderer/components/RightColumn.tsx @@ -11,7 +11,7 @@ import { import { BUILD_CUSTOM_TOOL_BRANCH, BUILD_CUSTOM_TOOL_PROMPT } from '../../shared/tools' import { useWatchedQuery } from '../hooks/useWatchedQuery' import { CustomToolPanel } from './CustomToolPanel' -import { PRStatusPanel, MergeLocallyPanel } from './PRStatusPanel' +import { PRStatusPanel } from './PRStatusPanel' import { BranchCommitsPanel } from './BranchCommitsPanel' import { ChangedFilesPanel } from './ChangedFilesPanel' import { AllFilesPanel } from './AllFilesPanel' @@ -42,8 +42,6 @@ interface RightColumnProps { activeRepoConfig: RepoConfig | null onRefreshPRs: () => void onOpenGithubSettings: () => void - onMerged: () => void - onRemoveWorktree: (path: string) => void onOpenDiff: ChangedFilesPanelProps['onOpenDiff'] onOpenCommitFileDiff: (commitHash: string, shortHash: string, filePath: string) => void onOpenFile: AllFilesPanelProps['onOpenFile'] @@ -70,8 +68,6 @@ export const RightColumn = memo(function RightColumn({ activeRepoConfig, onRefreshPRs, onOpenGithubSettings, - onMerged, - onRemoveWorktree, onOpenDiff, onOpenCommitFileDiff, onOpenFile, @@ -104,11 +100,10 @@ export const RightColumn = memo(function RightColumn({ const handleChangeHidden = (next: HiddenRightPanels): void => { if (!activeRepoRoot) return - // Send the full hiddenRightPanels object; also null out legacy - // fields so old values don't leak back in via effective migration. + // Send the full hiddenRightPanels object; also null out the legacy + // field so an old value doesn't leak back in via effective migration. void backend.setRepoConfig(activeRepoRoot, { hiddenRightPanels: next, - hideMergePanel: null, hidePrPanel: null } as unknown as Partial) } @@ -138,17 +133,6 @@ export const RightColumn = memo(function RightColumn({ ) } switch (key) { - case 'merge': - return ( - w.path === activeWorktreeId) || null} - hasGithubToken={hasGithubToken} - onMerged={onMerged} - onRemoveWorktree={onRemoveWorktree} - /> - ) case 'pr': return ( = { - merge: 'Merge Locally', pr: 'PR Status', todos: 'Todos', agents: 'Agents', diff --git a/src/renderer/components/Settings.tsx b/src/renderer/components/Settings.tsx index 067ea842b..14cfaa130 100644 --- a/src/renderer/components/Settings.tsx +++ b/src/renderer/components/Settings.tsx @@ -3557,30 +3557,28 @@ export function Settings({ onClose, onOpenGuide, onOpenMyWeek, initialSection }: )}

- Used when you run "Merge locally" on a worktree. The dropdown on - that button also writes back to this setting so your most recent - choice becomes the new default. + How the merge button on a worktree's PR merges it on GitHub.

{( [ { id: 'squash' as const, - label: 'Squash', - description: - "Combine all branch commits into one commit on the base branch. GitHub's \"Squash and merge\"." + label: 'Squash and merge', + description: 'Combine all branch commits into one commit on the base branch.' }, { id: 'merge-commit' as const, label: 'Merge commit', - description: - 'Always create a merge commit (--no-ff), preserving the branch as a visible bubble in history.' + description: 'Add all branch commits to the base branch via a merge commit.' }, { + // Stored as 'fast-forward' for configs written by the old + // local merge; it maps to GitHub's rebase method. id: 'fast-forward' as const, - label: 'Fast-forward only', + label: 'Rebase and merge', description: - 'Only merge if the base can fast-forward (--ff-only). Fails on divergent history.' + 'Replay the branch commits onto the base branch. GitHub gives them new SHAs.' } ] ).map((opt) => { diff --git a/src/renderer/store.ts b/src/renderer/store.ts index 136f5f931..b9779cd3b 100644 --- a/src/renderer/store.ts +++ b/src/renderer/store.ts @@ -1147,25 +1147,6 @@ export function usePrs() { return useAppState((s) => s.prs) } -/** Local-merge state for the Merge Locally panel. `repoBusy` is true while - * any worktree of the repo is merging: they all merge into the same main - * checkout, so main refuses a second one and the panel shouldn't offer it. */ -export function useLocalMergeState( - worktreePath: string, - repoRoot: string -): { merging: boolean; repoBusy: boolean; merged: boolean } { - const merging = useAppState((s) => !!s.prs.mergingByPath[worktreePath]) - const repoBusy = useAppState((s) => { - // Usually empty, so this is a no-op outside an actual merge. - for (const path in s.prs.mergingByPath) { - if (s.worktrees.list.some((w) => w.path === path && w.repoRoot === repoRoot)) return true - } - return false - }) - const merged = useAppState((s) => !!s.prs.mergedByPath[worktreePath]) - return { merging, repoBusy, merged } -} - export function useOnboarding() { return useAppState((s) => s.onboarding) } diff --git a/src/renderer/types.ts b/src/renderer/types.ts index b49351239..9035b0638 100644 --- a/src/renderer/types.ts +++ b/src/renderer/types.ts @@ -220,29 +220,6 @@ export interface MergePRResult { sha?: string } -export interface MainWorktreeStatus { - path: string - currentBranch: string - baseBranch: string - isOnBase: boolean - isDirty: boolean - ready: boolean -} - -export interface MergeConflictPreview { - hasConflict: boolean - files: string[] - unsupported?: boolean -} - -export interface MergeLocalResult { - ok: true - strategy: MergeStrategy - mergedBranch: string - baseBranch: string - mainPath: string -} - export interface ElectronAPI { listWorktrees(repoRoot: string): Promise listBranches(repoRoot: string): Promise @@ -314,16 +291,6 @@ export interface ElectronAPI { listDir(path: string, opts?: { showHidden?: boolean }): Promise resolveHome(): Promise - getMainWorktreeStatus(repoRoot: string): Promise - prepareMainForMerge(repoRoot: string): Promise - previewMergeConflicts(repoRoot: string, sourceBranch: string, worktreePath?: string): Promise - mergeWorktreeLocally( - repoRoot: string, - sourceBranch: string, - strategy: MergeStrategy, - worktreePath?: string - ): Promise - refreshPRsAll(): Promise refreshPRsAllIfStale(): Promise refreshPRsOne(worktreePath: string): Promise diff --git a/src/shared/state/prs.test.ts b/src/shared/state/prs.test.ts index 01574963d..5c4c8a78c 100644 --- a/src/shared/state/prs.test.ts +++ b/src/shared/state/prs.test.ts @@ -91,28 +91,6 @@ describe('prsReducer', () => { expect(next.mergedByPath).toEqual({ '/a': false, '/c': true }) }) - it('localMergeStarted marks the path as merging', () => { - const next = apply(initialPRs, { type: 'prs/localMergeStarted', payload: { path: '/a' } }) - expect(next.mergingByPath).toEqual({ '/a': true }) - expect(apply(next, { type: 'prs/localMergeStarted', payload: { path: '/a' } })).toBe(next) - }) - - it('localMergeFinished clears merging and marks merged on success', () => { - const start: PRsState = { ...initialPRs, mergingByPath: { '/a': true, '/b': true } } - const ok = apply(start, { - type: 'prs/localMergeFinished', - payload: { path: '/a', merged: true } - }) - expect(ok.mergingByPath).toEqual({ '/b': true }) - expect(ok.mergedByPath).toEqual({ '/a': true }) - const failed = apply(start, { - type: 'prs/localMergeFinished', - payload: { path: '/a', merged: false } - }) - expect(failed.mergingByPath).toEqual({ '/b': true }) - expect(failed.mergedByPath).toBe(start.mergedByPath) - }) - it('loadingChanged toggles the flag', () => { const on = apply(initialPRs, { type: 'prs/loadingChanged', payload: true }) expect(on.loading).toBe(true) @@ -130,7 +108,6 @@ describe('prsReducer', () => { const start: PRsState = { byPath: { '/a': stubPR() }, mergedByPath: { '/a': true }, - mergingByPath: {}, loading: false } const next = apply(start, { type: 'prs/loadingChanged', payload: true }) diff --git a/src/shared/state/prs.ts b/src/shared/state/prs.ts index 0ed496e8a..5d1a96fd3 100644 --- a/src/shared/state/prs.ts +++ b/src/shared/state/prs.ts @@ -74,13 +74,12 @@ export interface PRStatus { export interface PRsState { /** PR status per worktree path. null = "we looked and there's no PR yet". */ byPath: Record - /** Locally-merged flag per worktree path. Replaced wholesale on poll. */ + /** Locally-merged flag per worktree path. Replaced wholesale on poll. + * Only ever true for worktrees merged by the since-removed "Merge Locally" + * action: nothing records new entries, so the persisted branch → SHA map + * behind it only shrinks (pruned once a branch moves or its worktree is + * removed). Kept so those worktrees don't jump back to Active. */ mergedByPath: Record - /** Worktree paths with a "Merge Locally" in flight. Lives in the slice, not - * the panel, so the in-flight state follows the worktree rather than - * whichever worktree the panel happens to be showing when it settles — and - * so every client sees it and can't start a second merge. */ - mergingByPath: Record /** True while a full refresh is in flight. */ loading: boolean } @@ -90,13 +89,10 @@ export type PRsEvent = | { type: 'prs/bulkStatusChanged'; payload: Record } | { type: 'prs/mergedChanged'; payload: Record } | { type: 'prs/loadingChanged'; payload: boolean } - | { type: 'prs/localMergeStarted'; payload: { path: string } } - | { type: 'prs/localMergeFinished'; payload: { path: string; merged: boolean } } export const initialPRs: PRsState = { byPath: {}, mergedByPath: {}, - mergingByPath: {}, loading: false } @@ -108,8 +104,8 @@ export function isPRMerged(pr: PRStatus | null | undefined): boolean { } /** Canonical "is this worktree merged?" check. A worktree counts as merged - * if the locally-merged poller flagged it (branch SHA matches a recorded - * merge SHA — works without a GitHub token), or its PR is in a terminal + * if the locally-merged poller flagged it (branch SHA still matches a SHA + * recorded by the old "Merge Locally" action), or its PR is in a terminal * state. Used by the activity deriver, the cleanup view, and boot-time * pane init (sleep-on-boot for merged worktrees). */ export function isWorktreeMerged(prs: PRsState, worktreePath: string): boolean { @@ -129,26 +125,6 @@ export function prsReducer(state: PRsState, event: PRsEvent): PRsState { return { ...state, mergedByPath: event.payload } case 'prs/loadingChanged': return { ...state, loading: event.payload } - case 'prs/localMergeStarted': { - if (state.mergingByPath[event.payload.path]) return state - return { - ...state, - mergingByPath: { ...state.mergingByPath, [event.payload.path]: true } - } - } - case 'prs/localMergeFinished': { - const { path, merged } = event.payload - const { [path]: _wasMerging, ...mergingByPath } = state.mergingByPath - void _wasMerging - // Mark merged immediately rather than waiting for the poller's next - // wholesale mergedChanged, so there's no window where the merge has - // landed but the panel offers the merge button again. - const mergedByPath = - merged && !state.mergedByPath[path] - ? { ...state.mergedByPath, [path]: true } - : state.mergedByPath - return { ...state, mergingByPath, mergedByPath } - } default: { const _exhaustive: never = event void _exhaustive diff --git a/src/shared/state/repo-configs.test.ts b/src/shared/state/repo-configs.test.ts index 8433ea751..125d5a3f2 100644 --- a/src/shared/state/repo-configs.test.ts +++ b/src/shared/state/repo-configs.test.ts @@ -37,7 +37,7 @@ describe('repoConfigsReducer', () => { } const updated: RepoConfig = { setupCommand: 'a-updated', - hideMergePanel: true + hidePrPanel: true } const next = repoConfigsReducer(start, { type: 'repoConfigs/changed', @@ -74,12 +74,7 @@ describe('repoConfigsReducer', () => { expect(next).toBe(start) }) - it('effectiveHiddenRightPanels migrates legacy hideMergePanel / hidePrPanel', () => { - expect(effectiveHiddenRightPanels({ hideMergePanel: true })).toEqual({ - scratchpad: true, - subscriptions: true, - merge: true - }) + it('effectiveHiddenRightPanels migrates legacy hidePrPanel', () => { expect(effectiveHiddenRightPanels({ hidePrPanel: true })).toEqual({ scratchpad: true, subscriptions: true, @@ -87,21 +82,25 @@ describe('repoConfigsReducer', () => { }) expect( effectiveHiddenRightPanels({ - hideMergePanel: true, - hiddenRightPanels: { pr: true, commits: true } + hidePrPanel: true, + hiddenRightPanels: { commits: true } }) - ).toEqual({ scratchpad: true, subscriptions: true, merge: true, pr: true, commits: true }) + ).toEqual({ scratchpad: true, subscriptions: true, pr: true, commits: true }) }) it('effectiveHiddenRightPanels prefers new field over legacy', () => { - // Legacy says "hide merge", new explicitly sets merge: false. - // effectiveHiddenRightPanels only adds legacy when new is undefined. expect( effectiveHiddenRightPanels({ - hideMergePanel: true, - hiddenRightPanels: { merge: false } + hidePrPanel: true, + hiddenRightPanels: { pr: false } }) - ).toEqual({ scratchpad: true, subscriptions: true, merge: false }) + ).toEqual({ scratchpad: true, subscriptions: true, pr: false }) + }) + + it('effectiveHiddenRightPanels ignores the removed Merge Locally panel flag', () => { + // Saved before the panel was removed; must not resurrect a "merge" key. + const legacy = { hideMergePanel: true } as unknown as RepoConfig + expect(effectiveHiddenRightPanels(legacy)).toEqual({ scratchpad: true, subscriptions: true }) }) it('effectiveHiddenRightPanels defaults scratchpad to hidden', () => { @@ -126,7 +125,6 @@ describe('repoConfigsReducer', () => { rightPanelOrder: [ 'cost', 'pr', - 'merge', 'todos', 'agents', 'commits', @@ -139,7 +137,6 @@ describe('repoConfigsReducer', () => { ).toEqual([ 'cost', 'pr', - 'merge', 'todos', 'agents', 'commits', @@ -160,7 +157,6 @@ describe('repoConfigsReducer', () => { expect(result[1]).toBe('pr') // Remaining keys in canonical order expect(result.slice(2)).toEqual([ - 'merge', 'commits', 'changedFiles', 'allFiles', @@ -173,6 +169,15 @@ describe('repoConfigsReducer', () => { expect(result).toHaveLength(DEFAULT_RIGHT_PANEL_ORDER.length) }) + it('effectiveRightPanelOrder drops the removed Merge Locally panel from a saved order', () => { + const result = effectiveRightPanelOrder({ + rightPanelOrder: ['merge', 'cost', 'pr'] as never + }) + expect(result).not.toContain('merge') + expect(result.slice(0, 2)).toEqual(['cost', 'pr']) + expect(result).toHaveLength(DEFAULT_RIGHT_PANEL_ORDER.length) + }) + it('effectiveRightPanelOrder deduplicates repeated keys', () => { const result = effectiveRightPanelOrder({ rightPanelOrder: ['pr', 'pr', 'merge'] as never diff --git a/src/shared/state/repo-configs.ts b/src/shared/state/repo-configs.ts index 46b7742dc..046994258 100644 --- a/src/shared/state/repo-configs.ts +++ b/src/shared/state/repo-configs.ts @@ -1,5 +1,4 @@ export type BuiltinRightPanelKey = - | 'merge' | 'pr' | 'todos' | 'agents' @@ -26,7 +25,6 @@ export function toolPanelKey(toolId: string): CustomToolPanelKey { } export const DEFAULT_RIGHT_PANEL_ORDER: BuiltinRightPanelKey[] = [ - 'merge', 'pr', 'commits', 'changedFiles', @@ -53,16 +51,16 @@ export interface RepoConfig { version?: number setupCommand?: string teardownCommand?: string + /** How the PR panel's merge button merges on GitHub. */ mergeStrategy?: 'squash' | 'merge-commit' | 'fast-forward' - /** @deprecated use hiddenRightPanels.merge. Migrated on load. */ - hideMergePanel?: boolean /** @deprecated use hiddenRightPanels.pr. Migrated on load. */ hidePrPanel?: boolean /** Per-panel visibility. A key set to true hides that panel. */ hiddenRightPanels?: HiddenRightPanels /** Order of right-column panels. Unknown / missing keys fall back to * DEFAULT_RIGHT_PANEL_ORDER (any key absent from the saved order is - * appended to the end in canonical order). */ + * appended to the end in canonical order). May still contain 'merge' + * from before the Merge Locally panel was removed; readers drop it. */ rightPanelOrder?: RightPanelKey[] } @@ -96,8 +94,7 @@ export function effectiveRightPanelOrder( return out } -/** Read an effective hidden map, migrating legacy hideMergePanel / - * hidePrPanel fields. Returns a fresh object — safe to mutate. +/** Read an effective hidden map, migrating the legacy hidePrPanel field. Returns a fresh object — safe to mutate. * * DEFAULT_HIDDEN_RIGHT_PANELS is merged UNDER the saved values, so once * the user explicitly toggles a default-hidden panel on, their choice wins. */ @@ -106,7 +103,6 @@ export function effectiveHiddenRightPanels(config: RepoConfig | null | undefined ...DEFAULT_HIDDEN_RIGHT_PANELS, ...(config?.hiddenRightPanels || {}) } - if (config?.hideMergePanel && out.merge === undefined) out.merge = true if (config?.hidePrPanel && out.pr === undefined) out.pr = true return out } From 513366108ced66455dea90e939bf0600baddbfa9 Mon Sep 17 00:00:00 2001 From: Mike Lyons Date: Thu, 26 Nov 2026 14:03:12 -0500 Subject: [PATCH 2/2] Move the locallyMerged comment above its field Co-Authored-By: Claude Opus 5.5 --- src/main/persistence.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index e97f459b0..9408485cf 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -195,11 +195,6 @@ export interface Config { // Sidebar project drag order as section scope keys (see // SettingsState.sidebarProjectOrder). Absent until the user reorders. sidebarProjectOrder?: string[] - // Branches merged by the since-removed "Merge Locally" action, keyed by - // branch name. Value is the branch-tip SHA at merge time — if the branch - // later advances past this SHA, the flag is considered stale and pruned. - // Nothing adds entries any more; the map is read only so worktrees merged - // that way keep grouping under Merged / Closed until they're removed. // Shell command to run after a worktree is created. Runs via login shell // with cwd=worktree and env vars HARNESS_WORKTREE_PATH, HARNESS_BRANCH, // HARNESS_REPO_ROOT. Failures are logged but don't block creation. @@ -207,6 +202,11 @@ export interface Config { // Shell command to run before a worktree is removed. Same execution model // as setup. Failures are logged but don't block removal. worktreeTeardownCommand?: string + // Branches merged by the since-removed "Merge Locally" action, keyed by + // branch name. Value is the branch-tip SHA at merge time — if the branch + // later advances past this SHA, the flag is considered stale and pruned. + // Nothing adds entries any more; the map is read only so worktrees merged + // that way keep grouping under Merged / Closed until they're removed. locallyMerged?: Record // When true, pass --name "repo/branch" to Claude so sessions are named by // their worktree rather than auto-summarized. Also sets the name visible