mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Refuse unsafe branch switches and share one check across phone and desktop (#38744)
* fix(git): refuse unsafe branch switches in an existing workspace The phone's Switch branch ran `git checkout` with no checks: uncommitted files moved to the other branch, and a switch could land under a working agent or mid-rebase. One host check now covers every client: it refuses, with a plain reason, when files are uncommitted, a merge/rebase/ cherry-pick/revert is in progress, HEAD is detached or unborn, another git action is running, or an agent in the checkout is working or waiting for approval. Checks and the checkout run under a per-checkout lock. After a switch the host clears the old branch's review links and push target and tells every client, so a phone-only host stays correct, and records that the user chose the branch so first-work naming never renames it. The open Commits list follows the new branch. * fix(git): review round 1 repairs for the guarded branch switch - check out through the provider so the user's switch keeps the interactive git queue - a landed switch that Windows left files behind on now tells the user instead of reporting success - never let a Windows yes/no prompt hold the switch lock - refuse submodule edits that submodule ignore config hides from status - record the switch on the target host's metadata row and never fail a landed switch on bookkeeping - read workspace paths from their ids instead of scanning the catalog on every switch - admit agent rows like the sidebar roster (listed tab, or a live terminal by pane, tab or handle) - move the host-side switch hooks into their own module * test: type the new switch test fakes instead of casting them * fix(git): second repair round for the guarded branch switch - report files Windows left behind from git's own unlink warnings, not a status re-read, so ordinary branch differences and submodule commit changes are never called failures - the phone refreshes its branch and files after a switch that landed with a warning - refuse only edits inside a submodule its ignore config hides, never a commit mismatch alone, reading status without optional locks in the interactive queue - read the agent process probe when a switch runs, not while the runtime is constructed - check the agent's checkout path before terminal liveness and build the tab list once per switch - the runtime wiring test no longer reaches real git * fix(git): scope the switch's agent check to the checkout and keep landed-switch outcomes honest - find candidate agents by checkout path first; build terminal liveness once, only from this checkout's terminals and its workspaces' saved tabs; probe candidates together and re-read the snapshot once; no work for unrelated workspaces (contract test at N and 10N) - a checkout that fails after HEAD moved is recorded as landed; files left behind are named only when git reports it could not replace them, otherwise git's own error is shown - parse git's unlink warnings for paths with apostrophes - the phone keeps the refusal or warning visible while it reloads the branch - cover a submodule that is only at another commit * fix(git): name git's own error when a switch lands after a failing hook; use the shared unlink parser * fix(git): keep the switch's agent check flat for unrelated folder workspaces - read folder workspace directories once per switch instead of a linear search per row and terminal - re-read each candidate's current status by pane key instead of rebuilding the whole snapshot - skip the hidden-submodule status pass in repos without submodules - the cost contract covers folder workspaces, many in-checkout agents and PTY passes - a real-git test covers a switch that lands before a failing post-checkout hook * fix(git): never quote git's progress line as a landed switch's error; fixed clock in the cost test * fix(git): decide the hidden-submodule check from the index, not a visible .gitmodules * perf(git): read only index modes for the submodule shortcut so large repos stay under the output cap
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
import { createElement, useRef } from 'react'
|
||||
import { act, create } from 'react-test-renderer'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
// Mock native Flow/haptics imports, as the other runner tests do.
|
||||
vi.mock('react-native', () => ({
|
||||
Platform: { OS: 'ios', select: (options: Record<string, unknown>) => options.ios },
|
||||
StyleSheet: { create: (value: unknown) => value, hairlineWidth: 1 }
|
||||
}))
|
||||
vi.mock('expo-router', () => ({
|
||||
useRouter: () => ({
|
||||
back: () => undefined,
|
||||
push: () => undefined,
|
||||
replace: () => undefined,
|
||||
navigate: () => undefined,
|
||||
dismissTo: () => undefined,
|
||||
prefetch: () => undefined,
|
||||
canGoBack: () => false,
|
||||
setParams: () => undefined
|
||||
})
|
||||
}))
|
||||
vi.mock('../platform/haptics', () => ({
|
||||
triggerSuccess: () => undefined,
|
||||
triggerError: () => undefined,
|
||||
triggerSelection: () => undefined,
|
||||
triggerWarning: () => undefined,
|
||||
triggerImpact: () => undefined
|
||||
}))
|
||||
|
||||
import { useRouteHandoff } from '../navigation/route-handoff'
|
||||
import { useMobileSourceControlRunners } from './use-mobile-source-control-runners'
|
||||
|
||||
const REFUSAL = 'Commit or discard 2 changed files before switching branches.'
|
||||
|
||||
describe('phone Switch branch outcome', () => {
|
||||
it('keeps the host reason visible while it reloads the branch the checkout is on', async () => {
|
||||
const setActionError = vi.fn()
|
||||
const loadStatus = vi.fn().mockResolvedValue(true)
|
||||
const captured: { checkout: ((branch: string) => Promise<void>) | null } = { checkout: null }
|
||||
function Probe(): null {
|
||||
const router = useRouteHandoff()
|
||||
const mountedRef = useRef(true)
|
||||
const busyActionRef = useRef<string | null>(null)
|
||||
captured.checkout = useMobileSourceControlRunners({
|
||||
client: null,
|
||||
hostId: 'host-a',
|
||||
worktreeId: 'wt-1',
|
||||
status: null,
|
||||
commitMessage: '',
|
||||
stagedEntries: [],
|
||||
generatingMessage: false,
|
||||
stageablePaths: [],
|
||||
unstageablePaths: [],
|
||||
router,
|
||||
sendGitRequest: async () => {
|
||||
throw new Error(REFUSAL)
|
||||
},
|
||||
sendCommitRequest: vi.fn(),
|
||||
runGitSyncSteps: vi.fn(),
|
||||
loadStatus,
|
||||
mountedRef,
|
||||
busyActionRef,
|
||||
setBusyAction: vi.fn(),
|
||||
setActionError,
|
||||
setCommitMessage: vi.fn(),
|
||||
setGeneratingMessage: vi.fn(),
|
||||
setShowActionSheet: vi.fn(),
|
||||
setLocalBranches: vi.fn(),
|
||||
setShowBranchPicker: vi.fn(),
|
||||
recordCommitFailure: vi.fn()
|
||||
}).checkoutBranch
|
||||
return null
|
||||
}
|
||||
await act(async () => {
|
||||
create(createElement(Probe))
|
||||
})
|
||||
const checkout = captured.checkout
|
||||
if (!checkout) {
|
||||
throw new Error('the runners hook never rendered')
|
||||
}
|
||||
await act(async () => {
|
||||
await checkout('feature')
|
||||
})
|
||||
|
||||
expect(setActionError).toHaveBeenLastCalledWith(REFUSAL)
|
||||
expect(loadStatus).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ force: true, clearActionErrorOnSuccess: false })
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -83,7 +83,7 @@ export function useMobileSourceControlRunners(params: Params) {
|
||||
async (
|
||||
actionId: string,
|
||||
runner: () => Promise<void>,
|
||||
options?: { clearCommitMessage?: boolean }
|
||||
options?: { clearCommitMessage?: boolean; refreshOnError?: boolean }
|
||||
) => {
|
||||
if (busyActionRef.current) {
|
||||
return false
|
||||
@@ -110,6 +110,14 @@ export function useMobileSourceControlRunners(params: Params) {
|
||||
triggerError()
|
||||
const text = translate('sourceControl.runners.actionFailed', 'Source control action failed')
|
||||
setActionError(err instanceof Error ? err.message : text)
|
||||
if (options?.refreshOnError) {
|
||||
// Keep the reason visible: a successful reload clears the action error by default.
|
||||
await loadStatus({
|
||||
preserveReadyOnFailure: true,
|
||||
force: true,
|
||||
clearActionErrorOnSuccess: false
|
||||
})
|
||||
}
|
||||
return false
|
||||
} finally {
|
||||
if (busyActionRef.current === actionId) {
|
||||
@@ -269,9 +277,16 @@ export function useMobileSourceControlRunners(params: Params) {
|
||||
const checkoutBranch = useCallback(
|
||||
async (branch: string) => {
|
||||
setShowBranchPicker(false)
|
||||
await runGitAction('checkout', 'git.checkout', { branch })
|
||||
// A host can report a switch that landed with files left behind; show the branch it is on.
|
||||
await runGitWorkflow(
|
||||
'checkout',
|
||||
async () => {
|
||||
await sendGitRequest<unknown>('git.checkout', { branch })
|
||||
},
|
||||
{ refreshOnError: true }
|
||||
)
|
||||
},
|
||||
[runGitAction, setShowBranchPicker]
|
||||
[runGitWorkflow, sendGitRequest, setShowBranchPicker]
|
||||
)
|
||||
|
||||
const actionSheetRunners = useMobileSourceControlActionSheetRunners({
|
||||
|
||||
@@ -15,6 +15,7 @@ import { gitExecFileAsync } from '../git/runner'
|
||||
import { resolveLocalGitUsername } from '../git/git-username'
|
||||
import { resolveGitRouteForHost } from '../providers/execution-host-provider-dispatch'
|
||||
import { getRepoExecutionHostId } from '../../shared/execution-host'
|
||||
import { withCheckoutLock } from '../git/branch-switch'
|
||||
import {
|
||||
probeBranchUpstream,
|
||||
renameCurrentBranch,
|
||||
@@ -248,45 +249,56 @@ async function runAutoRename(
|
||||
return retryFailedGeneration(worktreeId, generated, deps, retry)
|
||||
}
|
||||
|
||||
// Generation can outlive a branch switch or publication.
|
||||
const branchNow = (await exec(['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim()
|
||||
if (branchNow !== currentBranch) {
|
||||
return retry(`branch changed during generation (${currentBranch} -> ${branchNow})`)
|
||||
}
|
||||
const postGenerationProbe = await probeBranchUpstream(exec)
|
||||
if (postGenerationProbe.outcome !== 'no-upstream') {
|
||||
return retry(
|
||||
postGenerationProbe.outcome === 'has-upstream'
|
||||
? `branch "${currentBranch}" was pushed during generation`
|
||||
: `upstream probe failed after generation: ${postGenerationProbe.message}`
|
||||
// An in-app branch switch can land during generation; recheck and rename under its lock.
|
||||
const renamed = await withCheckoutLock(worktreePath, async (): Promise<boolean | string> => {
|
||||
if (!deps.canRenameOrcaCreatedBranch(worktreeId)) {
|
||||
return stop('worktree is not eligible for auto-rename', true)
|
||||
}
|
||||
// Generation can outlive a branch switch or publication.
|
||||
const branchNow = (await exec(['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim()
|
||||
if (branchNow !== currentBranch) {
|
||||
return retry(`branch changed during generation (${currentBranch} -> ${branchNow})`)
|
||||
}
|
||||
const postGenerationProbe = await probeBranchUpstream(exec)
|
||||
if (postGenerationProbe.outcome !== 'no-upstream') {
|
||||
return retry(
|
||||
postGenerationProbe.outcome === 'has-upstream'
|
||||
? `branch "${currentBranch}" was pushed during generation`
|
||||
: `upstream probe failed after generation: ${postGenerationProbe.message}`
|
||||
)
|
||||
}
|
||||
|
||||
const username = (await resolveLocalGitUsername(repo.path)) || null
|
||||
// Models may echo the configured prefix; strip it before adding the prefix ourselves.
|
||||
const slug = stripConfiguredBranchPrefix(
|
||||
generated.slug,
|
||||
getConfiguredBranchPrefix(settings, username)
|
||||
)
|
||||
}
|
||||
if (!slug) {
|
||||
return stop('model produced only the configured prefix', true)
|
||||
}
|
||||
const newBranch = await resolveUniqueBranchName(
|
||||
exec,
|
||||
slug,
|
||||
// Use the nonthrowing builder so invalid prefixes follow this background task's stop/retry policy.
|
||||
(slugLeaf) => computeBranchName(slugLeaf, settings, username),
|
||||
currentBranch
|
||||
)
|
||||
if (!newBranch || newBranch === currentBranch) {
|
||||
return stop(`no distinct unique branch name for slug "${slug}"`, true)
|
||||
}
|
||||
|
||||
const username = (await resolveLocalGitUsername(repo.path)) || null
|
||||
// Models may echo the configured prefix; strip it before adding the prefix ourselves.
|
||||
const slug = stripConfiguredBranchPrefix(
|
||||
generated.slug,
|
||||
getConfiguredBranchPrefix(settings, username)
|
||||
)
|
||||
if (!slug) {
|
||||
return stop('model produced only the configured prefix', true)
|
||||
// Awaited name lookups can outlive the start of a WSL move.
|
||||
if (isWslMoveRepoBlocked(repo)) {
|
||||
return retry('a WSL move started before the branch rename')
|
||||
}
|
||||
await renameCurrentBranch(exec, newBranch)
|
||||
return newBranch
|
||||
})
|
||||
if (typeof renamed === 'boolean') {
|
||||
return renamed
|
||||
}
|
||||
const newBranch = await resolveUniqueBranchName(
|
||||
exec,
|
||||
slug,
|
||||
// Use the nonthrowing builder so invalid prefixes follow this background task's stop/retry policy.
|
||||
(slugLeaf) => computeBranchName(slugLeaf, settings, username),
|
||||
currentBranch
|
||||
)
|
||||
if (!newBranch || newBranch === currentBranch) {
|
||||
return stop(`no distinct unique branch name for slug "${slug}"`, true)
|
||||
}
|
||||
|
||||
// Awaited name lookups can outlive the start of a WSL move.
|
||||
if (isWslMoveRepoBlocked(repo)) {
|
||||
return retry('a WSL move started before the branch rename')
|
||||
}
|
||||
await renameCurrentBranch(exec, newBranch)
|
||||
const newBranch = renamed
|
||||
|
||||
// Collision suffixes belong in display and folder names too.
|
||||
const newBranchLeaf = newBranch.slice(newBranch.lastIndexOf('/') + 1)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { WorktreeMeta } from '../../shared/worktree/meta-types'
|
||||
import { firstWorkRenameDeps } from './first-work-rename-runtime'
|
||||
|
||||
const BASE_META: WorktreeMeta = {
|
||||
displayName: 'workspace',
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0,
|
||||
orcaCreationSource: 'desktop'
|
||||
}
|
||||
|
||||
function depsFor(meta: WorktreeMeta) {
|
||||
return firstWorkRenameDeps(
|
||||
{
|
||||
getSettings: vi.fn(),
|
||||
getRepo: vi.fn(),
|
||||
getRepos: vi.fn(),
|
||||
getWorktreeMeta: () => meta,
|
||||
setWorktreeMeta: vi.fn(),
|
||||
getFolderWorkspace: vi.fn(),
|
||||
updateFolderWorkspace: vi.fn()
|
||||
},
|
||||
{
|
||||
getCommitMessageAgentEnvironmentResolvers: vi.fn(),
|
||||
notifyFolderWorkspaceChanged: vi.fn(),
|
||||
notifyBranchRenamed: vi.fn(),
|
||||
notifyWorktreeFolderRenamed: vi.fn()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
describe('first-work branch rename eligibility', () => {
|
||||
it('never renames a branch the user switched to or created in Orca', () => {
|
||||
expect(depsFor(BASE_META).canRenameOrcaCreatedBranch('repo::/w')).toBe(true)
|
||||
expect(
|
||||
depsFor({ ...BASE_META, branchNameIsUserChosen: true }).canRenameOrcaCreatedBranch('repo::/w')
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { parseWorkspaceKey } from '../../shared/workspace-scope'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host'
|
||||
import { getRepoIdFromWorktreeId } from '../../shared/worktree/id'
|
||||
import type { FirstWorkBranchRenameDeps } from './first-work-branch-rename'
|
||||
import { rememberBranchRenameFailureOutput } from './branch-rename-failure-output'
|
||||
@@ -24,7 +25,9 @@ export function firstWorkRenameDeps(
|
||||
| 'getFolderWorkspace'
|
||||
| 'updateFolderWorkspace'
|
||||
> &
|
||||
Partial<Pick<Store, 'migrateWorktreeIdentity' | 'getWorktreeIdForTab'>>,
|
||||
Partial<
|
||||
Pick<Store, 'migrateWorktreeIdentity' | 'getWorktreeIdForTab' | 'getWorktreeMetaForHost'>
|
||||
>,
|
||||
runtime: Pick<
|
||||
OrcaRuntimeService,
|
||||
| 'getCommitMessageAgentEnvironmentResolvers'
|
||||
@@ -63,9 +66,16 @@ export function firstWorkRenameDeps(
|
||||
: store.getWorktreeMeta(worktreeId)?.pendingFirstAgentMessageRename === true
|
||||
},
|
||||
canRenameOrcaCreatedBranch: (worktreeId) => {
|
||||
const meta = store.getWorktreeMeta(worktreeId)
|
||||
// Renames run on this host only, so read this host's row, not a same-id twin's.
|
||||
const meta =
|
||||
store.getWorktreeMetaForHost?.(worktreeId, LOCAL_EXECUTION_HOST_ID) ??
|
||||
store.getWorktreeMeta(worktreeId)
|
||||
// A creature-like name alone cannot prove Orca owns the branch.
|
||||
return !!meta?.orcaCreationSource && meta.preserveBranchOnDelete !== true
|
||||
return (
|
||||
!!meta?.orcaCreationSource &&
|
||||
meta.preserveBranchOnDelete !== true &&
|
||||
meta.branchNameIsUserChosen !== true
|
||||
)
|
||||
},
|
||||
setDisplayName: (worktreeId, displayName) => {
|
||||
rememberBranchRenameFailureOutput(worktreeId, null)
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { runProcess } from '@orca/process-host'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { installRealWorkerThreadChildProcesses } from '../worker-thread-child-process/worker-thread-child-process-real.test-fixtures'
|
||||
import { switchBranchGuarded, type BranchSwitchDeps } from './branch-switch'
|
||||
import { checkoutBranch } from './checkout'
|
||||
import { getStatus } from './source-control/status-read'
|
||||
|
||||
let directory: string
|
||||
|
||||
async function git(...args: string[]): Promise<string> {
|
||||
const result = await runProcess({ program: 'git', args, cwd: directory })
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr)
|
||||
}
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
function deps(agentBlocker: string | null = null): BranchSwitchDeps {
|
||||
return {
|
||||
getStatus: () => getStatus(directory, { includeLineStats: false }),
|
||||
checkout: () => checkoutBranch(directory, 'feature'),
|
||||
getAgentBlocker: async () => agentBlocker
|
||||
}
|
||||
}
|
||||
|
||||
async function currentBranch(): Promise<string> {
|
||||
return git('symbolic-ref', '--short', 'HEAD')
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), 'orca-branch-switch-'))
|
||||
await git('init', '-q')
|
||||
await git('symbolic-ref', 'HEAD', 'refs/heads/main')
|
||||
await git('config', 'user.name', 'Audit')
|
||||
await git('config', 'user.email', 'audit@example.test')
|
||||
await git('config', 'commit.gpgsign', 'false')
|
||||
await git('config', 'core.hooksPath', '')
|
||||
await writeFile(join(directory, 'file.txt'), 'base\n')
|
||||
await git('add', 'file.txt')
|
||||
await git('commit', '-qm', 'base')
|
||||
await git('branch', 'feature')
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('switchBranchGuarded', () => {
|
||||
it('switches a clean checkout and reports the branch it left', async () => {
|
||||
const result = await switchBranchGuarded(directory, 'feature', {}, deps())
|
||||
|
||||
expect(result).toEqual({ branch: 'feature', previousBranch: 'main' })
|
||||
expect(await currentBranch()).toBe('feature')
|
||||
})
|
||||
|
||||
it('refuses uncommitted and untracked changes instead of carrying them across', async () => {
|
||||
await writeFile(join(directory, 'new.txt'), 'draft\n')
|
||||
|
||||
await expect(switchBranchGuarded(directory, 'feature', {}, deps())).rejects.toThrow(
|
||||
'Commit or discard 1 changed file (new.txt) before switching branches.'
|
||||
)
|
||||
expect(await currentBranch()).toBe('main')
|
||||
})
|
||||
|
||||
it('refuses while a revert is in progress', async () => {
|
||||
await writeFile(join(directory, 'file.txt'), 'changed\n')
|
||||
await git('commit', '-qam', 'change')
|
||||
await writeFile(join(directory, 'file.txt'), 'conflict\n')
|
||||
await git('commit', '-qam', 'conflict')
|
||||
await expect(git('revert', '--no-edit', 'HEAD~1')).rejects.toThrow()
|
||||
|
||||
await expect(switchBranchGuarded(directory, 'feature', {}, deps())).rejects.toThrow(
|
||||
'Finish or abort the revert in progress before switching branches.'
|
||||
)
|
||||
expect(await currentBranch()).toBe('main')
|
||||
})
|
||||
|
||||
it('refuses edits inside a submodule that ignore config hides, but not a commit mismatch alone', async () => {
|
||||
const library = await mkdtemp(join(tmpdir(), 'orca-branch-switch-lib-'))
|
||||
try {
|
||||
await runProcess({ program: 'git', args: ['init', '-q'], cwd: library })
|
||||
await writeFile(join(library, 'lib.txt'), 'lib\n')
|
||||
await runProcess({ program: 'git', args: ['add', 'lib.txt'], cwd: library })
|
||||
await runProcess({
|
||||
program: 'git',
|
||||
args: ['-c', 'user.name=A', '-c', 'user.email=a@a.test', 'commit', '-qm', 'lib'],
|
||||
cwd: library
|
||||
})
|
||||
await git('-c', 'protocol.file.allow=always', 'submodule', 'add', '-q', library, 'lib')
|
||||
await git('config', '-f', '.gitmodules', 'submodule.lib.ignore', 'all')
|
||||
await git('add', '.gitmodules')
|
||||
await git('commit', '-qm', 'add lib')
|
||||
await git('branch', '-f', 'feature')
|
||||
|
||||
await writeFile(join(directory, 'lib', 'lib.txt'), 'edited\n')
|
||||
await expect(switchBranchGuarded(directory, 'feature', {}, deps())).rejects.toThrow(
|
||||
'Commit, stash or clean the changes inside submodule lib before switching branches.'
|
||||
)
|
||||
expect(await currentBranch()).toBe('main')
|
||||
|
||||
// Sparse checkout can omit `.gitmodules` while git still hides the submodule.
|
||||
await git('config', 'submodule.lib.ignore', 'all')
|
||||
await git('update-index', '--skip-worktree', '.gitmodules')
|
||||
await rm(join(directory, '.gitmodules'))
|
||||
await expect(switchBranchGuarded(directory, 'feature', {}, deps())).rejects.toThrow(
|
||||
'Commit, stash or clean the changes inside submodule lib before switching branches.'
|
||||
)
|
||||
expect(await currentBranch()).toBe('main')
|
||||
|
||||
// A submodule merely at another commit has nothing a switch could lose.
|
||||
const submodule = join(directory, 'lib')
|
||||
await runProcess({ program: 'git', args: ['checkout', '--', 'lib.txt'], cwd: submodule })
|
||||
await runProcess({
|
||||
program: 'git',
|
||||
args: [
|
||||
'-c',
|
||||
'user.name=A',
|
||||
'-c',
|
||||
'user.email=a@a.test',
|
||||
'commit',
|
||||
'--allow-empty',
|
||||
'-qm',
|
||||
'moved'
|
||||
],
|
||||
cwd: submodule
|
||||
})
|
||||
await switchBranchGuarded(directory, 'feature', {}, deps())
|
||||
expect(await currentBranch()).toBe('feature')
|
||||
} finally {
|
||||
await rm(library, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('records a switch that landed before a failing post-checkout hook and names the hook error', async () => {
|
||||
const hooks = join(directory, '.hooks')
|
||||
await mkdir(hooks)
|
||||
await writeFile(
|
||||
join(hooks, 'post-checkout'),
|
||||
'#!/bin/sh\necho "hook check failed" >&2\nexit 1\n'
|
||||
)
|
||||
await chmod(join(hooks, 'post-checkout'), 0o755)
|
||||
await git('config', 'core.hooksPath', hooks)
|
||||
await writeFile(join(directory, '.git', 'info', 'exclude'), '.hooks/\n')
|
||||
const onSwitched = vi.fn()
|
||||
|
||||
await expect(
|
||||
switchBranchGuarded(directory, 'feature', {}, { ...deps(), onSwitched })
|
||||
).rejects.toThrow('Switched to feature, but git reported an error: hook check failed')
|
||||
expect(await currentBranch()).toBe('feature')
|
||||
expect(onSwitched).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('refuses with the agent reason when the checkout is otherwise clean', async () => {
|
||||
await expect(
|
||||
switchBranchGuarded(directory, 'feature', {}, deps('Claude is working in this workspace.'))
|
||||
).rejects.toThrow('Claude is working in this workspace.')
|
||||
expect(await currentBranch()).toBe('main')
|
||||
})
|
||||
|
||||
it('is a no-op on the current branch, even with changes or a working agent', async () => {
|
||||
await writeFile(join(directory, 'new.txt'), 'draft\n')
|
||||
|
||||
const result = await switchBranchGuarded(directory, 'main', {}, deps('busy'))
|
||||
|
||||
expect(result.previousBranch).toBeNull()
|
||||
})
|
||||
|
||||
it('serializes concurrent switches so only one checks a clean tree and moves HEAD', async () => {
|
||||
const outcomes = await Promise.allSettled([
|
||||
switchBranchGuarded(directory, 'feature', {}, deps()),
|
||||
switchBranchGuarded(directory, 'feature', {}, deps())
|
||||
])
|
||||
|
||||
expect(outcomes.map((outcome) => outcome.status)).toEqual(['fulfilled', 'fulfilled'])
|
||||
const results = outcomes.map((outcome) =>
|
||||
outcome.status === 'fulfilled' ? outcome.value : null
|
||||
)
|
||||
expect(results.map((result) => result?.previousBranch)).toEqual(['main', null])
|
||||
})
|
||||
})
|
||||
|
||||
installRealWorkerThreadChildProcesses()
|
||||
@@ -0,0 +1,256 @@
|
||||
import { access } from 'node:fs/promises'
|
||||
import * as path from 'node:path'
|
||||
import type { GitStatusResult } from '../../shared/git/status/git-status-types'
|
||||
import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path'
|
||||
import { isGitWorktreeMutationInFlight } from './command-runner/git-worktree-mutation-state'
|
||||
import { resolveGitDir } from './source-control/resolve-git-dir'
|
||||
import { gitOptionsForWorktree, type GitRuntimeOptions } from './git-runtime-options'
|
||||
import { gitExecFileAsync, gitOptionalLocksDisabledEnv } from './runner'
|
||||
import { parseCheckoutSkippedPaths } from './checkout-skipped-paths'
|
||||
import { readGitCommandFailureStderr } from '../../shared/git/commands/git-command-failure-text'
|
||||
|
||||
/** A switch Orca refused before touching the checkout; the message is shown to the user as-is. */
|
||||
export class BranchSwitchRefusedError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'BranchSwitchRefusedError'
|
||||
}
|
||||
}
|
||||
|
||||
/** The switch landed, but git reported a problem (files left behind, a failed hook); shown as-is. */
|
||||
export class BranchSwitchLandedWithWarningError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.name = 'BranchSwitchLandedWithWarningError'
|
||||
}
|
||||
}
|
||||
|
||||
function filesLeftBehindMessage(branch: string, skippedPaths: readonly string[]): string {
|
||||
const files = skippedPaths.length === 1 ? '1 file' : `${skippedPaths.length} files`
|
||||
const pronoun = skippedPaths.length === 1 ? 'it' : 'them'
|
||||
return `Switched to ${branch}, but ${files} kept the old branch's content because another program has ${pronoun} open (${skippedPaths[0]}). Close that program, then discard the changes Orca shows for ${pronoun} to finish the switch.`
|
||||
}
|
||||
|
||||
/** Git's own progress lines on stderr; never the reason a switch reported an error. */
|
||||
const GIT_CHECKOUT_PROGRESS =
|
||||
/^(Switched to( a new)? branch|Already on|Your branch|Previous HEAD position|HEAD is now at)\b/
|
||||
|
||||
/** Prefer git's own error line; else the last line that is not git progress (a hook's output). */
|
||||
function gitFailureLine(stderr: string): string | null {
|
||||
const lines = stderr
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !GIT_CHECKOUT_PROGRESS.test(line))
|
||||
return lines.find((line) => /^(error|fatal):/.test(line)) ?? lines.at(-1) ?? null
|
||||
}
|
||||
|
||||
async function readCurrentBranch(
|
||||
worktreePath: string,
|
||||
options: GitRuntimeOptions
|
||||
): Promise<string | null> {
|
||||
try {
|
||||
const { stdout } = await gitExecFileAsync(
|
||||
['symbolic-ref', '--quiet', '--short', 'HEAD'],
|
||||
gitOptionsForWorktree(worktreePath, options)
|
||||
)
|
||||
return stdout.trim() || null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export type BranchSwitchDeps = {
|
||||
/** Status as the panel reads it, so Orca's own shared-path symlinks don't count as changes. */
|
||||
getStatus: () => Promise<GitStatusResult>
|
||||
/** The provider's checkout, so the user's switch keeps the interactive git queue. */
|
||||
checkout: () => Promise<{ skippedPaths: string[] }>
|
||||
/** A user-facing reason when an agent is working in this checkout, else null. */
|
||||
getAgentBlocker: () => Promise<string | null>
|
||||
/** Record the user's choice before the lock lets a queued first-work rename look at the branch. */
|
||||
onSwitched?: () => void
|
||||
}
|
||||
|
||||
export type BranchSwitchResult = {
|
||||
branch: string
|
||||
/** The live branch the checkout left, or null when it was already on `branch`. */
|
||||
previousBranch: string | null
|
||||
}
|
||||
|
||||
const checkoutLocks = new Map<string, Promise<unknown>>()
|
||||
|
||||
/** Serialize check-then-move of a checkout's branch: switches from any client and first-work renames. */
|
||||
export async function withCheckoutLock<T>(worktreePath: string, run: () => Promise<T>): Promise<T> {
|
||||
const key = normalizeRuntimePathForComparison(worktreePath)
|
||||
const previous = checkoutLocks.get(key) ?? Promise.resolve()
|
||||
const current = previous.catch(() => {}).then(run)
|
||||
const settled = current.catch(() => {})
|
||||
checkoutLocks.set(key, settled)
|
||||
try {
|
||||
return await current
|
||||
} finally {
|
||||
if (checkoutLocks.get(key) === settled) {
|
||||
checkoutLocks.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function exists(target: string): Promise<boolean> {
|
||||
try {
|
||||
await access(target)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function changedFilesReason(status: GitStatusResult): string {
|
||||
const count = status.statusLength ?? status.entries.length
|
||||
const first = status.entries[0]
|
||||
const submodule = status.entries.find((entry) => entry.submodule)
|
||||
if (submodule) {
|
||||
return `Commit, stash or clean the changes inside submodule ${submodule.path} before switching branches.`
|
||||
}
|
||||
if (first && first.path.startsWith('.orca/browser-downloads/')) {
|
||||
return `Move or delete the downloaded file ${first.path} before switching branches.`
|
||||
}
|
||||
const files = count === 1 ? `1 changed file (${first?.path ?? ''})` : `${count} changed files`
|
||||
return `Commit or discard ${files} before switching branches.`
|
||||
}
|
||||
|
||||
/** Submodule `ignore` config hides edits from the panel's status; refuse only on edits inside one. */
|
||||
async function firstHiddenSubmoduleEdit(
|
||||
worktreePath: string,
|
||||
options: GitRuntimeOptions
|
||||
): Promise<string | null> {
|
||||
const execution = {
|
||||
...gitOptionsForWorktree(worktreePath, { ...options, admissionTier: 'interactive' }),
|
||||
env: gitOptionalLocksDisabledEnv()
|
||||
}
|
||||
// No gitlink in the index, nothing hidden: skip a second working-tree walk on every switch.
|
||||
// The index decides, not `.gitmodules` on disk (sparse checkout can omit it while git still
|
||||
// reads submodule config from the index). Modes only keep large indexes under the output cap;
|
||||
// a failed, overflowing or too-old-git read probes anyway.
|
||||
const index = await gitExecFileAsync(
|
||||
['ls-files', '-z', '--format=%(objectmode)'],
|
||||
execution
|
||||
).catch(() => null)
|
||||
if (index !== null && !index.stdout.split('\0').includes('160000')) {
|
||||
return null
|
||||
}
|
||||
const { stdout } = await gitExecFileAsync(
|
||||
['status', '--porcelain=v2', '--untracked-files=no', '--ignore-submodules=none'],
|
||||
execution
|
||||
)
|
||||
for (const line of stdout.split('\n')) {
|
||||
// `1 XY S<c><m><u> …`: m means tracked edits inside (untracked ones are not listed here and a
|
||||
// switch cannot lose them); a commit mismatch alone is left alone, since checkout never
|
||||
// touches a submodule's working tree.
|
||||
const fields = line.split(' ')
|
||||
const sub = fields[2] ?? ''
|
||||
if (
|
||||
(fields[0] === '1' || fields[0] === '2') &&
|
||||
sub.startsWith('S') &&
|
||||
/[MU]/.test(sub.slice(2))
|
||||
) {
|
||||
return fields
|
||||
.slice(fields[0] === '1' ? 8 : 9)
|
||||
.join(' ')
|
||||
.split('\t')[0]
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function readRefusal(
|
||||
worktreePath: string,
|
||||
branch: string,
|
||||
options: GitRuntimeOptions,
|
||||
deps: BranchSwitchDeps
|
||||
): Promise<{ refusal: string | null; previousBranch: string | null }> {
|
||||
const status = await deps.getStatus()
|
||||
if (status.readError !== undefined) {
|
||||
return {
|
||||
refusal: `Orca couldn't read this checkout's changes, so it didn't switch branches. ${status.readError}`,
|
||||
previousBranch: null
|
||||
}
|
||||
}
|
||||
const current = status.branch?.replace(/^refs\/heads\//, '')
|
||||
if (current === branch) {
|
||||
return { refusal: null, previousBranch: null }
|
||||
}
|
||||
const refuse = (refusal: string | null) => ({ refusal, previousBranch: current ?? null })
|
||||
if (status.head === '(initial)') {
|
||||
return refuse('Make a first commit on this branch before switching branches.')
|
||||
}
|
||||
if (current === undefined) {
|
||||
return refuse(
|
||||
'This checkout is on a detached commit. Switch branches from a terminal so commits made here are not lost.'
|
||||
)
|
||||
}
|
||||
const revertInProgress = await exists(
|
||||
path.join(await resolveGitDir(worktreePath, options), 'REVERT_HEAD')
|
||||
)
|
||||
const operation = status.conflictOperation !== 'unknown' ? status.conflictOperation : null
|
||||
if (operation ?? revertInProgress) {
|
||||
return refuse(
|
||||
`Finish or abort the ${operation ?? 'revert'} in progress before switching branches.`
|
||||
)
|
||||
}
|
||||
if (await isGitWorktreeMutationInFlight(worktreePath, options)) {
|
||||
return refuse(
|
||||
'Another git action is still running in this checkout. Try again when it finishes.'
|
||||
)
|
||||
}
|
||||
if (status.entries.length > 0) {
|
||||
return refuse(changedFilesReason(status))
|
||||
}
|
||||
const hiddenSubmodule = await firstHiddenSubmoduleEdit(worktreePath, options)
|
||||
if (hiddenSubmodule) {
|
||||
return refuse(
|
||||
`Commit, stash or clean the changes inside submodule ${hiddenSubmodule} before switching branches.`
|
||||
)
|
||||
}
|
||||
return refuse(await deps.getAgentBlocker())
|
||||
}
|
||||
|
||||
/** Switch an existing local branch in place, refusing when the checkout is not safe to switch. */
|
||||
export async function switchBranchGuarded(
|
||||
worktreePath: string,
|
||||
branch: string,
|
||||
options: GitRuntimeOptions,
|
||||
deps: BranchSwitchDeps
|
||||
): Promise<BranchSwitchResult> {
|
||||
return withCheckoutLock(worktreePath, async () => {
|
||||
const { refusal, previousBranch } = await readRefusal(worktreePath, branch, options, deps)
|
||||
if (refusal !== null) {
|
||||
throw new BranchSwitchRefusedError(refusal)
|
||||
}
|
||||
if (previousBranch === null) {
|
||||
return { branch, previousBranch }
|
||||
}
|
||||
let skippedPaths: string[]
|
||||
try {
|
||||
;({ skippedPaths } = await deps.checkout())
|
||||
} catch (error) {
|
||||
// Git can exit non-zero after HEAD already moved (a file it could not replace, a failing
|
||||
// post-checkout hook); that switch landed and must be recorded.
|
||||
if ((await readCurrentBranch(worktreePath, options)) !== branch) {
|
||||
throw error
|
||||
}
|
||||
deps.onSwitched?.()
|
||||
const stderr = readGitCommandFailureStderr(error) ?? ''
|
||||
const failed = parseCheckoutSkippedPaths(stderr)
|
||||
const detail = gitFailureLine(stderr) ?? 'a post-checkout hook or git step failed'
|
||||
throw new BranchSwitchLandedWithWarningError(
|
||||
failed.length > 0
|
||||
? filesLeftBehindMessage(branch, failed)
|
||||
: `Switched to ${branch}, but git reported an error: ${detail}`
|
||||
)
|
||||
}
|
||||
deps.onSwitched?.()
|
||||
if (skippedPaths.length > 0) {
|
||||
throw new BranchSwitchLandedWithWarningError(filesLeftBehindMessage(branch, skippedPaths))
|
||||
}
|
||||
return { branch, previousBranch }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseCheckoutSkippedPaths } from './checkout-skipped-paths'
|
||||
|
||||
describe('parseCheckoutSkippedPaths', () => {
|
||||
it('reads every path git could not replace, apostrophes included', () => {
|
||||
const stderr = [
|
||||
"warning: unable to unlink 'public/logo.png': Permission denied",
|
||||
"error: unable to unlink old ''draft.txt': Invalid argument",
|
||||
"warning: unable to unlink 'it's.md': Permission denied",
|
||||
"Switched to branch 'feature'"
|
||||
].join('\n')
|
||||
|
||||
expect(parseCheckoutSkippedPaths(stderr)).toEqual(['public/logo.png', "'draft.txt", "it's.md"])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Git for Windows reports a file another program holds open this way (possibly still exiting 0). */
|
||||
const UNLINK_FAILURE = /unable to unlink (?:old )?'(.*)': [^\n]*$/gm
|
||||
|
||||
/** Paths git could not replace, from checkout stderr; git quotes them raw, apostrophes included. */
|
||||
export function parseCheckoutSkippedPaths(stderr: string): string[] {
|
||||
return [...new Set([...stderr.matchAll(UNLINK_FAILURE)].map((match) => match[1]))]
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { GitRuntimeOptions } from './git-runtime-options'
|
||||
import { gitOptionsForWorktree } from './git-runtime-options'
|
||||
import { gitExecFileAsync } from './runner'
|
||||
import { gitEnvWithoutYesNoPrompt } from './command-runner/git-no-prompt-env'
|
||||
import { parseCheckoutSkippedPaths } from './checkout-skipped-paths'
|
||||
import { runWithGitReadCacheInvalidation } from './source-control/git-read-cache-invalidation'
|
||||
|
||||
/** Reject empty and option-like names here too: relay callers can bypass RPC schema validation. */
|
||||
@@ -15,11 +17,16 @@ export async function checkoutBranch(
|
||||
worktreePath: string,
|
||||
branch: string,
|
||||
options: GitRuntimeOptions = {}
|
||||
): Promise<void> {
|
||||
): Promise<{ skippedPaths: string[] }> {
|
||||
assertValidBranchName(branch)
|
||||
await runWithGitReadCacheInvalidation(() =>
|
||||
gitExecFileAsync(['checkout', branch, '--'], gitOptionsForWorktree(worktreePath, options))
|
||||
const { stderr } = await runWithGitReadCacheInvalidation(() =>
|
||||
gitExecFileAsync(['checkout', branch, '--'], {
|
||||
...gitOptionsForWorktree(worktreePath, options),
|
||||
// A locked file must fail the checkout, not open a prompt while the switch lock is held.
|
||||
...gitEnvWithoutYesNoPrompt()
|
||||
})
|
||||
)
|
||||
return { skippedPaths: parseCheckoutSkippedPaths(stderr) }
|
||||
}
|
||||
|
||||
/** for-each-ref avoids localized branch decoration; return the current branch first. */
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Git for Windows may invoke GIT_ASK_YESNO for locked files; Orca's own git actions never launch that prompt. */
|
||||
export function gitEnvWithoutYesNoPrompt(): { env?: NodeJS.ProcessEnv } {
|
||||
const inherited = Object.keys(process.env).filter((key) => key.toUpperCase() === 'GIT_ASK_YESNO')
|
||||
if (inherited.length === 0) {
|
||||
return {}
|
||||
}
|
||||
const env = { ...process.env }
|
||||
for (const key of inherited) {
|
||||
delete env[key]
|
||||
}
|
||||
return { env }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { lstat } from 'node:fs/promises'
|
||||
import { gitEnvWithoutYesNoPrompt } from '../../command-runner/git-no-prompt-env'
|
||||
import { pruneGitWorktrees } from './worktree-prune-guard'
|
||||
import type { RemoveWorktreeResult } from '../../../../shared/worktree/create-types'
|
||||
import { assertWorktreeUnlockedForRemoval } from '../../../../shared/worktree/removal'
|
||||
@@ -73,7 +74,7 @@ async function performRemoveWorktree(
|
||||
const execOptions = {
|
||||
...gitExecOptions(repoPath, options),
|
||||
...(options.checkoutDeleteSignal ? { signal: options.checkoutDeleteSignal } : {}),
|
||||
...removalGitEnv(),
|
||||
...gitEnvWithoutYesNoPrompt(),
|
||||
admissionExempt: true as const
|
||||
}
|
||||
const args = [...longPathArgs, 'worktree', 'remove']
|
||||
@@ -191,19 +192,6 @@ async function localBranchExists(
|
||||
}
|
||||
}
|
||||
|
||||
// Git for Windows may invoke GIT_ASK_YESNO for locked files; removal must never launch a prompt.
|
||||
function removalGitEnv(): { env?: NodeJS.ProcessEnv } {
|
||||
const inherited = Object.keys(process.env).filter((key) => key.toUpperCase() === 'GIT_ASK_YESNO')
|
||||
if (inherited.length === 0) {
|
||||
return {}
|
||||
}
|
||||
const env = { ...process.env }
|
||||
for (const key of inherited) {
|
||||
delete env[key]
|
||||
}
|
||||
return { env }
|
||||
}
|
||||
|
||||
// Git for Windows can exit 0 leaving junctions and parent directories; finish that accepted delete.
|
||||
async function removeCheckoutLeftByGit(
|
||||
worktreePath: string,
|
||||
|
||||
@@ -64,7 +64,8 @@ export type IGitProvider = {
|
||||
detectConflictOperation(worktreePath: string): Promise<GitConflictOperation>
|
||||
abortMerge(worktreePath: string): Promise<void>
|
||||
abortRebase(worktreePath: string): Promise<void>
|
||||
checkoutBranch(worktreePath: string, branch: string): Promise<void>
|
||||
/** `skippedPaths`: files git could not replace (held open on Windows) though the switch landed. */
|
||||
checkoutBranch(worktreePath: string, branch: string): Promise<{ skippedPaths: string[] }>
|
||||
listLocalBranches(worktreePath: string): Promise<{ current: string | null; branches: string[] }>
|
||||
getBranchCompare(
|
||||
worktreePath: string,
|
||||
|
||||
@@ -30,6 +30,10 @@ import type { ResolvedWorktree } from '../workspaces/catalog/runtime-worktree-pa
|
||||
import type { Repo } from '../../../shared/repo-types'
|
||||
import { isWslMoveWorktreeBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff'
|
||||
import { worktreeRowTarget } from '../../persistence/host-qualified-worktree-meta'
|
||||
import {
|
||||
createBranchSwitchHost,
|
||||
storeBackedBranchSwitchSources
|
||||
} from '../integrations/git/runtime-branch-switch-host'
|
||||
import type { RuntimeRepoSelector } from '../workspaces/catalog/runtime-repo-selector'
|
||||
import type { LayoutApplyReply } from '../../../shared/workspace-layout/workspace-layout-command-types'
|
||||
import type { WindowLayoutCommand } from '../terminal/layout/runtime-layout-apply'
|
||||
@@ -201,9 +205,25 @@ export abstract class OrcaRuntimeWithFileCommands extends OrcaRuntimeWithPreserv
|
||||
return
|
||||
}
|
||||
store.setWorktreeMeta(target, { pushTarget })
|
||||
}
|
||||
},
|
||||
...createBranchSwitchHost({
|
||||
getStore: () => this.store,
|
||||
readAgentRows: () => this.getAgentStatusSnapshotFn?.() ?? [],
|
||||
readAgentPaneRows: (paneKey) => this.getAgentStatusSnapshotForPaneFn?.(paneKey) ?? [],
|
||||
ptys: () => this.ptysById.values(),
|
||||
paneOf: (pty) => this.paneOfPty(pty),
|
||||
terminalHandlesOf: (ptyId) => this.getExistingTerminalHandlesForPtyId(ptyId),
|
||||
hasSyncedTab: (tabId) => this.tabs.has(tabId),
|
||||
...storeBackedBranchSwitchSources(() => this.store),
|
||||
probeProcess: (paneKey) => this.checkHookAgentPresenceFn?.(paneKey) ?? Promise.resolve(null),
|
||||
notifyBranchChanged: (repoId) => this.notifyBranchRenamed(repoId)
|
||||
})
|
||||
})
|
||||
|
||||
protected abstract getExistingTerminalHandlesForPtyId(ptyId: string): string[]
|
||||
|
||||
abstract notifyBranchRenamed(repoId: string): void
|
||||
|
||||
/** Remote views consume raw bytes even with a hidden desktop; resync daemon marks so those streams are never thinned. */
|
||||
onRemoteTerminalViewPresenceChanged: ((ptyId: string) => void) | null = null
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness'
|
||||
import { findAgentSwitchBlocker } from './branch-switch-agent-blocker'
|
||||
|
||||
type Row = ReturnType<Parameters<typeof findAgentSwitchBlocker>[0]['readRows']>[number]
|
||||
|
||||
const NOW = 10 * AGENT_STATUS_STALE_AFTER_MS
|
||||
const paths: Record<string, string> = {
|
||||
'repo::/work/app': '/work/app',
|
||||
'repo::/work/other': '/work/other'
|
||||
}
|
||||
|
||||
function row(overrides: Partial<Row> = {}): Row {
|
||||
return {
|
||||
paneKey: 'tab-1:pane-1',
|
||||
worktreeId: 'repo::/work/app',
|
||||
state: 'working',
|
||||
agentType: 'claude',
|
||||
receivedAt: NOW - 1000,
|
||||
connectionId: null,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function blocker(rows: Row[], verdict: 'live' | 'exited' | null = null) {
|
||||
return findAgentSwitchBlocker({
|
||||
checkoutPath: '/work/app',
|
||||
readRows: () => rows,
|
||||
readPaneRows: (paneKey) => rows.filter((candidate) => candidate.paneKey === paneKey),
|
||||
pathOfWorktree: (id) => paths[id],
|
||||
buildTerminalLiveness: () => () => true,
|
||||
probeProcess: async () => verdict,
|
||||
now: () => NOW
|
||||
})
|
||||
}
|
||||
|
||||
describe('findAgentSwitchBlocker', () => {
|
||||
it('names a working agent in this checkout and ignores other checkouts', async () => {
|
||||
await expect(blocker([row()])).resolves.toBe(
|
||||
'Claude is working in this workspace. Wait for it to finish or stop it, then switch branches.'
|
||||
)
|
||||
await expect(blocker([row({ worktreeId: 'repo::/work/other' })])).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('keeps refusing past the freshness window while the agent process is verified live', async () => {
|
||||
const silent = row({ receivedAt: NOW - 2 * AGENT_STATUS_STALE_AFTER_MS })
|
||||
|
||||
await expect(blocker([silent], 'live')).resolves.toBe(
|
||||
'Claude last reported work in this workspace and is still running. Stop or exit it, then switch branches.'
|
||||
)
|
||||
await expect(blocker([silent], null)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('releases on a verified exit or a finished turn', async () => {
|
||||
await expect(blocker([row()], 'exited')).resolves.toBeNull()
|
||||
await expect(blocker([row({ state: 'done' })], 'live')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
|
||||
import { isFreshNonDoneAgentStatus } from '../../../../shared/agent-status/contracts/agent-status-freshness'
|
||||
import type { AgentProcessVerdict } from '../../../../shared/agent-status/process/agent-process-presence'
|
||||
import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label'
|
||||
import { isPathInsideOrEqual } from '../../../../shared/cross-platform-path'
|
||||
import { isLocalHookConnectionId } from '../../../../shared/wsl-hook-relay-contract'
|
||||
|
||||
export type AgentSwitchRow = Pick<
|
||||
AgentStatusIpcPayload,
|
||||
| 'paneKey'
|
||||
| 'tabId'
|
||||
| 'terminalHandle'
|
||||
| 'worktreeId'
|
||||
| 'connectionId'
|
||||
| 'state'
|
||||
| 'workingMode'
|
||||
| 'agentType'
|
||||
| 'receivedAt'
|
||||
| 'evidenceObservedAt'
|
||||
| 'restoredUnconfirmed'
|
||||
| 'providerSessionOnly'
|
||||
| 'structuredHost'
|
||||
>
|
||||
|
||||
type TerminalRef = Pick<AgentSwitchRow, 'paneKey' | 'tabId' | 'terminalHandle'>
|
||||
|
||||
type BlockerArgs = {
|
||||
checkoutPath: string
|
||||
readRows: () => readonly AgentSwitchRow[]
|
||||
/** The rows the host holds for one pane right now, read by key. */
|
||||
readPaneRows: (paneKey: string) => readonly AgentSwitchRow[]
|
||||
pathOfWorktree: (worktreeId: string) => string | undefined
|
||||
/** Built once per switch from this checkout's candidates: is a terminal row's terminal still live? */
|
||||
buildTerminalLiveness: (candidates: readonly AgentSwitchRow[]) => (row: TerminalRef) => boolean
|
||||
probeProcess: (paneKey: string) => Promise<AgentProcessVerdict | null>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
/** A busy agent of this host whose workspace is the checkout or a folder inside it. */
|
||||
function isBusyInCheckout(row: AgentSwitchRow, args: BlockerArgs): boolean {
|
||||
if (row.state === 'done' || row.restoredUnconfirmed === true || row.providerSessionOnly) {
|
||||
return false
|
||||
}
|
||||
// Relayed rows describe another machine's checkout, even when the path text matches.
|
||||
if (!isLocalHookConnectionId(row.connectionId)) {
|
||||
return false
|
||||
}
|
||||
const path = row.worktreeId ? args.pathOfWorktree(row.worktreeId) : undefined
|
||||
return path !== undefined && isPathInsideOrEqual(args.checkoutPath, path)
|
||||
}
|
||||
|
||||
function isRecent(row: AgentSwitchRow, now: number): boolean {
|
||||
return isFreshNonDoneAgentStatus(
|
||||
{
|
||||
state: row.state,
|
||||
updatedAt: row.receivedAt,
|
||||
evidenceObservedAt: row.evidenceObservedAt,
|
||||
restoredUnconfirmed: row.restoredUnconfirmed,
|
||||
...(row.structuredHost === 'owned' ? { structuredHostOwned: true as const } : {})
|
||||
},
|
||||
now
|
||||
)
|
||||
}
|
||||
|
||||
function blockerMessage(row: AgentSwitchRow, onlyProcessIsLive: boolean): string {
|
||||
const agent = formatAgentTypeLabel(row.agentType)
|
||||
if (onlyProcessIsLive) {
|
||||
return `${agent} last reported work in this workspace and is still running. Stop or exit it, then switch branches.`
|
||||
}
|
||||
if (row.workingMode === 'monitoring') {
|
||||
return `${agent} is running a background task in this workspace. Stop it or wait for it to finish, then switch branches.`
|
||||
}
|
||||
if (row.state !== 'working') {
|
||||
return `${agent} is waiting for your approval in this workspace. Answer or stop it, then switch branches.`
|
||||
}
|
||||
return `${agent} is working in this workspace. Wait for it to finish or stop it, then switch branches.`
|
||||
}
|
||||
|
||||
/**
|
||||
* Switching files under a busy agent breaks its work. A busy row blocks while its evidence is
|
||||
* recent, or while Orca verifies that exact agent process is still running (a long silent tool).
|
||||
* A verified exit, or a newer row that is no longer busy here, releases it. Only this checkout's
|
||||
* rows reach liveness, probes and the keyed re-read; the snapshot is walked once per switch.
|
||||
*/
|
||||
export async function findAgentSwitchBlocker(args: BlockerArgs): Promise<string | null> {
|
||||
const now = args.now ?? Date.now
|
||||
const candidates = args.readRows().filter((row) => isBusyInCheckout(row, args))
|
||||
if (candidates.length === 0) {
|
||||
return null
|
||||
}
|
||||
const isLive = args.buildTerminalLiveness(candidates)
|
||||
// Like the sidebar: a closed terminal's row no longer describes a running agent.
|
||||
const admitted = (row: AgentSwitchRow): boolean =>
|
||||
isBusyInCheckout(row, args) &&
|
||||
(row.structuredHost !== undefined || row.tabId === undefined || isLive(row))
|
||||
const probed = candidates.filter(admitted)
|
||||
const verdicts = await Promise.all(
|
||||
probed.map((row) => args.probeProcess(row.paneKey).catch(() => null))
|
||||
)
|
||||
// The probes are async; only each pane's current row decides, judged again in full.
|
||||
for (const [index, row] of probed.entries()) {
|
||||
const verdict = verdicts[index]
|
||||
const latest = args.readPaneRows(row.paneKey).find(admitted)
|
||||
if (verdict === 'exited' || !latest) {
|
||||
continue
|
||||
}
|
||||
const recent = isRecent(latest, now())
|
||||
if (recent || verdict === 'live') {
|
||||
return blockerMessage(latest, !recent)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentSwitchRow } from './branch-switch-agent-blocker'
|
||||
import { createBranchSwitchHost } from './runtime-branch-switch-host'
|
||||
|
||||
const CHECKOUT = '/work/app'
|
||||
|
||||
type Pty = { ptyId: string; worktreeId: string; connected: true }
|
||||
|
||||
function row(key: string, worktreeId: string): AgentSwitchRow {
|
||||
return {
|
||||
paneKey: `tab-${key}:pane-1`,
|
||||
tabId: `tab-${key}`,
|
||||
worktreeId,
|
||||
connectionId: null,
|
||||
state: 'working',
|
||||
agentType: 'claude',
|
||||
// Expired evidence: the cost is the same whichever rows would block.
|
||||
receivedAt: 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unrelated workspaces: N busy agents in worktrees and N in folder workspaces, each with a
|
||||
* connected terminal and a saved tab. `candidates` busy agents sit in the switched checkout.
|
||||
*/
|
||||
function hostWith(unrelated: number, candidates: number) {
|
||||
const rows: AgentSwitchRow[] = []
|
||||
const ptys: Pty[] = []
|
||||
const tabsByWorktree: Record<string, { id: string }[]> = {}
|
||||
const folders = new Map<string, string>()
|
||||
for (let index = 0; index < unrelated; index++) {
|
||||
for (const workspaceId of [`repo::/work/other-${index}`, `folder:f-${index}`]) {
|
||||
const key = `${workspaceId}#${index}`
|
||||
rows.push(row(key, workspaceId))
|
||||
ptys.push({ ptyId: `pty-${key}`, worktreeId: workspaceId, connected: true })
|
||||
tabsByWorktree[workspaceId] = [{ id: `tab-${key}` }]
|
||||
}
|
||||
folders.set(`f-${index}`, `/work/folder-${index}`)
|
||||
}
|
||||
for (let index = 0; index < candidates; index++) {
|
||||
// Unknown processes: every candidate is judged and none blocks.
|
||||
rows.push(row(`app-${index}`, `repo::${CHECKOUT}`))
|
||||
ptys.push({ ptyId: `pty-app-${index}`, worktreeId: `repo::${CHECKOUT}`, connected: true })
|
||||
}
|
||||
const counts = {
|
||||
readRows: vi.fn(() => rows),
|
||||
readPaneRows: vi.fn((paneKey: string) =>
|
||||
rows.filter((candidate) => candidate.paneKey === paneKey)
|
||||
),
|
||||
ptys: vi.fn(() => ptys),
|
||||
paneOf: vi.fn((pty: Pty) => ({ tabId: `tab-${pty.ptyId.slice(4)}`, paneKey: null })),
|
||||
terminalHandlesOf: vi.fn(() => []),
|
||||
savedTabIds: vi.fn((workspaceIds: ReadonlySet<string>) =>
|
||||
[...workspaceIds].flatMap((id) => (tabsByWorktree[id] ?? []).map((tab) => tab.id))
|
||||
),
|
||||
folderWorkspacePaths: vi.fn(() => folders),
|
||||
probeProcess: vi.fn(async () => null)
|
||||
}
|
||||
const host = createBranchSwitchHost<Pty>({
|
||||
getStore: () => null,
|
||||
readAgentRows: counts.readRows,
|
||||
readAgentPaneRows: counts.readPaneRows,
|
||||
ptys: counts.ptys,
|
||||
paneOf: counts.paneOf,
|
||||
terminalHandlesOf: counts.terminalHandlesOf,
|
||||
hasSyncedTab: () => false,
|
||||
savedTabIds: counts.savedTabIds,
|
||||
folderWorkspacePaths: counts.folderWorkspacePaths,
|
||||
probeProcess: counts.probeProcess,
|
||||
notifyBranchChanged: () => {}
|
||||
})
|
||||
return { host, counts }
|
||||
}
|
||||
|
||||
async function operations(unrelated: number, candidates: number) {
|
||||
const { host, counts } = hostWith(unrelated, candidates)
|
||||
await host.getAgentSwitchBlocker(CHECKOUT)
|
||||
return {
|
||||
readRows: counts.readRows.mock.calls.length,
|
||||
paneReads: counts.readPaneRows.mock.calls.length,
|
||||
ptyPasses: counts.ptys.mock.calls.length,
|
||||
paneOf: counts.paneOf.mock.calls.length,
|
||||
handles: counts.terminalHandlesOf.mock.calls.length,
|
||||
savedTabReads: counts.savedTabIds.mock.calls.length,
|
||||
folderReads: counts.folderWorkspacePaths.mock.calls.length,
|
||||
probes: counts.probeProcess.mock.calls.length
|
||||
}
|
||||
}
|
||||
|
||||
// Bound, from what the answer needs: each of this checkout's agents must be judged once against
|
||||
// its current row. The snapshot and the PTY list have no path index, so each is walked once to
|
||||
// find this checkout's members, and folder directories are read once. Every heavier step (pane
|
||||
// lookup, handles, saved-tab reads, probes, current-row reads) is per candidate or per in-checkout
|
||||
// terminal, so it scales with this checkout's agents and never with unrelated workspaces.
|
||||
describe('branch switch agent check cost', () => {
|
||||
it('does no per-terminal, session or probe work for unrelated workspaces', async () => {
|
||||
for (const unrelated of [50, 500]) {
|
||||
expect(await operations(unrelated, 0)).toEqual({
|
||||
readRows: 1,
|
||||
paneReads: 0,
|
||||
ptyPasses: 0,
|
||||
paneOf: 0,
|
||||
handles: 0,
|
||||
savedTabReads: 0,
|
||||
folderReads: 1,
|
||||
probes: 0
|
||||
})
|
||||
for (const candidates of [5, 50]) {
|
||||
expect(await operations(unrelated, candidates)).toEqual({
|
||||
readRows: 1,
|
||||
paneReads: candidates,
|
||||
ptyPasses: 1,
|
||||
paneOf: candidates,
|
||||
handles: candidates,
|
||||
savedTabReads: 1,
|
||||
folderReads: 1,
|
||||
probes: candidates
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,159 @@
|
||||
import type { AgentProcessVerdict } from '../../../../shared/agent-status/process/agent-process-presence'
|
||||
import type { Worktree } from '../../../../shared/worktree/types'
|
||||
import {
|
||||
CLEARED_HOSTED_REVIEW_LINK_UPDATES,
|
||||
HOSTED_REVIEW_LINK_KEYS
|
||||
} from '../../../../shared/worktree/hosted-review-links'
|
||||
import { parseWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import { splitWorktreeIdForFilesystem } from '../../../../shared/worktree/id'
|
||||
import { isWslMoveWorktreeBlocked } from '../../../persistence/moving-wsl-projects/wsl-move-background-backoff'
|
||||
import { worktreeRowTarget } from '../../../persistence/host-qualified-worktree-meta'
|
||||
import type { RuntimeStore } from '../../runtime-store-contract'
|
||||
import { findAgentSwitchBlocker, type AgentSwitchRow } from './branch-switch-agent-blocker'
|
||||
import { isPathInsideOrEqual } from '../../../../shared/cross-platform-path'
|
||||
import type { RuntimeGitCommandHost } from './runtime-git-command-target'
|
||||
|
||||
type ConnectedPty = { ptyId: string; worktreeId: string; connected: boolean }
|
||||
|
||||
export type BranchSwitchHostSources<P extends ConnectedPty> = {
|
||||
getStore: () => RuntimeStore | null
|
||||
readAgentRows: () => readonly AgentSwitchRow[]
|
||||
readAgentPaneRows: (paneKey: string) => readonly AgentSwitchRow[]
|
||||
ptys: () => Iterable<P>
|
||||
paneOf: (pty: P) => { tabId: string | null; paneKey: string | null }
|
||||
terminalHandlesOf: (ptyId: string) => readonly string[]
|
||||
hasSyncedTab: (tabId: string) => boolean
|
||||
/** Tab ids saved in these workspaces' sessions on any host. */
|
||||
savedTabIds: (workspaceIds: ReadonlySet<string>) => Iterable<string>
|
||||
probeProcess: (paneKey: string) => Promise<AgentProcessVerdict | null>
|
||||
notifyBranchChanged: (repoId: string) => void
|
||||
/** Every folder workspace's directory by id; read at most once per switch. */
|
||||
folderWorkspacePaths: () => ReadonlyMap<string, string>
|
||||
}
|
||||
|
||||
type WorkspacePathOf = (workspaceId: string) => string | undefined
|
||||
|
||||
/** The saved-session and folder sources, read from the store only when a switch needs them. */
|
||||
export function storeBackedBranchSwitchSources(
|
||||
getStore: () => RuntimeStore | null
|
||||
): Pick<BranchSwitchHostSources<ConnectedPty>, 'savedTabIds' | 'folderWorkspacePaths'> {
|
||||
return {
|
||||
savedTabIds: (workspaceIds) => {
|
||||
const store = getStore()
|
||||
return (store?.getWorkspaceSessionHostIds?.() ?? []).flatMap((hostId) => {
|
||||
const tabsByWorktree = store?.getWorkspaceSession?.(hostId)?.tabsByWorktree ?? {}
|
||||
return [...workspaceIds].flatMap((id) => (tabsByWorktree[id] ?? []).map((tab) => tab.id))
|
||||
})
|
||||
},
|
||||
folderWorkspacePaths: () =>
|
||||
new Map(
|
||||
(getStore()?.getFolderWorkspaces?.() ?? []).map((folder) => [folder.id, folder.folderPath])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve workspace directories without a catalog scan, reading folder workspaces once if needed. */
|
||||
function createWorkspacePathOf(
|
||||
sources: Pick<BranchSwitchHostSources<ConnectedPty>, 'folderWorkspacePaths'>
|
||||
): WorkspacePathOf {
|
||||
let folders: ReadonlyMap<string, string> | null = null
|
||||
return (workspaceId) => {
|
||||
const scope = parseWorkspaceKey(workspaceId)
|
||||
if (scope?.type === 'folder') {
|
||||
return (folders ??= sources.folderWorkspacePaths()).get(scope.folderWorkspaceId)
|
||||
}
|
||||
// A worktree id spells its checkout path.
|
||||
return splitWorktreeIdForFilesystem(scope?.type === 'worktree' ? scope.worktreeId : workspaceId)
|
||||
?.worktreePath
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sidebar roster's admission, built once per switch from this checkout only: a tab saved in
|
||||
* the candidates' workspace sessions or synced here, or a connected terminal of this checkout
|
||||
* matched by pane, tab or handle.
|
||||
*/
|
||||
function buildTerminalLiveness<P extends ConnectedPty>(
|
||||
sources: BranchSwitchHostSources<P>,
|
||||
checkoutPath: string,
|
||||
candidates: readonly AgentSwitchRow[],
|
||||
workspacePathOf: WorkspacePathOf
|
||||
): (row: Pick<AgentSwitchRow, 'paneKey' | 'tabId' | 'terminalHandle'>) => boolean {
|
||||
const paneKeys = new Set<string>()
|
||||
const tabIds = new Set<string>()
|
||||
const handles = new Set<string>()
|
||||
for (const pty of sources.ptys()) {
|
||||
const path = pty.connected ? workspacePathOf(pty.worktreeId) : undefined
|
||||
if (path === undefined || !isPathInsideOrEqual(checkoutPath, path)) {
|
||||
continue
|
||||
}
|
||||
const pane = sources.paneOf(pty)
|
||||
if (pane.paneKey) {
|
||||
paneKeys.add(pane.paneKey)
|
||||
}
|
||||
if (pane.tabId) {
|
||||
tabIds.add(pane.tabId)
|
||||
}
|
||||
for (const handle of sources.terminalHandlesOf(pty.ptyId)) {
|
||||
handles.add(handle)
|
||||
}
|
||||
}
|
||||
const workspaceIds = new Set(
|
||||
candidates.flatMap((row) => (row.worktreeId ? [row.worktreeId] : []))
|
||||
)
|
||||
for (const tabId of sources.savedTabIds(workspaceIds)) {
|
||||
tabIds.add(tabId)
|
||||
}
|
||||
return (row) =>
|
||||
paneKeys.has(row.paneKey) ||
|
||||
(row.tabId !== undefined && (tabIds.has(row.tabId) || sources.hasSyncedTab(row.tabId))) ||
|
||||
(row.terminalHandle !== undefined && handles.has(row.terminalHandle))
|
||||
}
|
||||
|
||||
/** Host side of an in-app branch switch: the agent refusal and what a landed switch records. */
|
||||
export function createBranchSwitchHost<P extends ConnectedPty>(
|
||||
sources: BranchSwitchHostSources<P>
|
||||
): Required<Pick<RuntimeGitCommandHost, 'getAgentSwitchBlocker' | 'recordBranchSwitched'>> {
|
||||
return {
|
||||
getAgentSwitchBlocker: async (checkoutPath) => {
|
||||
const workspacePathOf = createWorkspacePathOf(sources)
|
||||
return findAgentSwitchBlocker({
|
||||
checkoutPath,
|
||||
readRows: sources.readAgentRows,
|
||||
readPaneRows: sources.readAgentPaneRows,
|
||||
pathOfWorktree: workspacePathOf,
|
||||
buildTerminalLiveness: (candidates) =>
|
||||
buildTerminalLiveness(sources, checkoutPath, candidates, workspacePathOf),
|
||||
probeProcess: sources.probeProcess
|
||||
})
|
||||
},
|
||||
// Watchers only cover desktop-hosted local repos, so Orca's own switch updates every client
|
||||
// itself; the user's choice also ends first-work automatic branch naming.
|
||||
recordBranchSwitched: (worktree: Pick<Worktree, 'id' | 'hostId' | 'repoId'>) => {
|
||||
const store = sources.getStore()
|
||||
try {
|
||||
const target = store ? worktreeRowTarget(store, worktree) : undefined
|
||||
if (!store || !target || isWslMoveWorktreeBlocked(target.id, target.hostId)) {
|
||||
throw new Error('no metadata owner')
|
||||
}
|
||||
// Read the row this write targets; the unqualified getter may return a same-id twin's.
|
||||
const meta =
|
||||
store.getWorktreeMetaForHost?.(target.id, target.hostId) ??
|
||||
store.getWorktreeMeta(target.id)
|
||||
const hasBranchScopedLinks =
|
||||
meta !== undefined &&
|
||||
(HOSTED_REVIEW_LINK_KEYS.some((key) => meta[key] != null) ||
|
||||
meta.pushTarget !== undefined)
|
||||
store.setWorktreeMeta(target, {
|
||||
...(hasBranchScopedLinks ? CLEARED_HOSTED_REVIEW_LINK_UPDATES : {}),
|
||||
branchNameIsUserChosen: true
|
||||
})
|
||||
} catch (error) {
|
||||
// The switch already landed; bookkeeping must not turn it into a failure. First-work
|
||||
// naming then behaves as before.
|
||||
console.warn('[branch-switch] could not record the switch for', worktree.id, error)
|
||||
}
|
||||
sources.notifyBranchChanged(worktree.repoId)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,10 @@ export type RuntimeGitCommandHost = {
|
||||
/** `undefined` keeps cached metadata; `null` is the authoritative unlinked answer. */
|
||||
getWorktreeLinkedIssue?(worktreeId: string): number | null | undefined
|
||||
getWorktreeLinkedIssueMeta?(worktreeId: string): PullRequestLinkedIssueMeta | null | undefined
|
||||
/** A user-facing reason when an agent is working in the checkout at this path, else null. */
|
||||
getAgentSwitchBlocker?(worktreePath: string): Promise<string | null>
|
||||
/** Clear the old branch's review links and push target, then publish the new branch to every client. */
|
||||
recordBranchSwitched?(worktree: Pick<Worktree, 'id' | 'hostId' | 'repoId'>): void
|
||||
/** Persist lazily created push remotes for orphan cleanup (#17842); sync materialization skips Store to avoid ownership/refspec side effects (#17828). */
|
||||
persistMaterializedPushTarget?(
|
||||
worktree: Pick<Worktree, 'id' | 'hostId'>,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
} from '../../../../shared/git/history/git-history-types'
|
||||
import type { GitMutationInFlight } from '../../../../shared/git/commands/git-mutation-in-flight'
|
||||
import { isGitWorktreeMutationInFlight } from '../../../git/command-runner/git-worktree-mutation-state'
|
||||
import { switchBranchGuarded } from '../../../git/branch-switch'
|
||||
import type {
|
||||
GitConflictOperation,
|
||||
GitStagingArea,
|
||||
@@ -98,8 +99,24 @@ export class RuntimeGitStatusCommands {
|
||||
branch: string
|
||||
): Promise<RuntimeGitCheckoutResult> {
|
||||
const target = await this.host.resolveRuntimeGitTarget(worktreeSelector)
|
||||
await requireRuntimeGitProvider(target).checkoutBranch(target.worktree.path, branch)
|
||||
return { ok: true, branch }
|
||||
const provider = requireRuntimeGitProvider(target)
|
||||
const worktreePath = target.worktree.path
|
||||
const result = await switchBranchGuarded(
|
||||
worktreePath,
|
||||
branch,
|
||||
localGitOptionsForTarget(target),
|
||||
{
|
||||
getStatus: () =>
|
||||
provider.getStatus(worktreePath, {
|
||||
admissionTier: 'interactive',
|
||||
includeLineStats: false
|
||||
}),
|
||||
checkout: () => provider.checkoutBranch(worktreePath, branch),
|
||||
getAgentBlocker: async () => this.host.getAgentSwitchBlocker?.(worktreePath) ?? null,
|
||||
onSwitched: () => this.host.recordBranchSwitched?.(target.worktree)
|
||||
}
|
||||
)
|
||||
return { ok: true, branch: result.branch }
|
||||
}
|
||||
|
||||
async listRuntimeGitLocalBranches(worktreeSelector: string): Promise<RuntimeGitLocalBranches> {
|
||||
|
||||
@@ -43,6 +43,21 @@ vi.mock('../git/source-control/status-read', async (importOriginal) => ({
|
||||
getStatus: mocks.getStatus
|
||||
}))
|
||||
|
||||
// The guard has its own real-git tests; here only the runtime's wiring to the provider matters.
|
||||
vi.mock('../git/branch-switch', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
switchBranchGuarded: async (
|
||||
_path: string,
|
||||
branch: string,
|
||||
_options: unknown,
|
||||
deps: { checkout: () => Promise<unknown>; onSwitched?: () => void }
|
||||
) => {
|
||||
await deps.checkout()
|
||||
deps.onSwitched?.()
|
||||
return { branch, previousBranch: 'main' }
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('../git/checkout', () => ({
|
||||
checkoutBranch: mocks.checkoutBranch,
|
||||
listLocalBranches: mocks.listLocalBranches
|
||||
@@ -176,7 +191,7 @@ describe('RuntimeGitCommands', () => {
|
||||
}),
|
||||
getRuntimeSettings: () => ({}) as GlobalSettings
|
||||
})
|
||||
mocks.checkoutBranch.mockResolvedValue(undefined)
|
||||
mocks.checkoutBranch.mockResolvedValue({ skippedPaths: [] })
|
||||
|
||||
await expect(commands.checkoutRuntimeGitBranch('id:wt-1', 'feature/x')).resolves.toEqual({
|
||||
ok: true,
|
||||
|
||||
@@ -100,6 +100,7 @@ export function useSourceControlFileListing({
|
||||
activeRepoTarget,
|
||||
activeWorktreeId,
|
||||
worktreePath,
|
||||
branchName,
|
||||
compareBaseRef,
|
||||
isFolder,
|
||||
isBranchVisible,
|
||||
|
||||
+1
@@ -21,6 +21,7 @@ const props = (overrides: Partial<Props> = {}): Props => ({
|
||||
activeRepoTarget: { kind: 'local' },
|
||||
activeWorktreeId: 'wt-1',
|
||||
worktreePath: '\\\\wsl.localhost\\Ubuntu\\repo',
|
||||
branchName: 'main',
|
||||
compareBaseRef: 'main',
|
||||
isFolder: false,
|
||||
isBranchVisible: true,
|
||||
|
||||
@@ -17,6 +17,7 @@ export function useSourceControlGitHistory({
|
||||
activeRepoTarget,
|
||||
activeWorktreeId,
|
||||
worktreePath,
|
||||
branchName,
|
||||
compareBaseRef,
|
||||
isFolder,
|
||||
isBranchVisible,
|
||||
@@ -27,6 +28,7 @@ export function useSourceControlGitHistory({
|
||||
activeRepoTarget: RuntimeClientTarget | null
|
||||
activeWorktreeId: string | null
|
||||
worktreePath: string | null
|
||||
branchName: string
|
||||
compareBaseRef: string | null
|
||||
isFolder: boolean
|
||||
isBranchVisible: boolean
|
||||
@@ -172,6 +174,8 @@ export function useSourceControlGitHistory({
|
||||
}, [
|
||||
// History uses compareBaseRef, which can move independently of effectiveBaseRef.
|
||||
activeWorktreeId,
|
||||
// A branch switch keeps the workspace and path; the open list must follow the new branch.
|
||||
branchName,
|
||||
compareBaseRef,
|
||||
isBranchVisible,
|
||||
isFolder,
|
||||
|
||||
+15
@@ -44,6 +44,7 @@ function Probe(props: {
|
||||
activeRepoTarget?: RuntimeClientTarget
|
||||
worktreeId?: string | null
|
||||
worktreePath?: string
|
||||
branchName?: string
|
||||
compareBaseRef?: string | null
|
||||
isFolder?: boolean
|
||||
isBranchVisible?: boolean
|
||||
@@ -55,6 +56,7 @@ function Probe(props: {
|
||||
activeRepoTarget: props.activeRepoTarget ?? { kind: 'local' },
|
||||
activeWorktreeId: props.worktreeId === undefined ? 'A' : props.worktreeId,
|
||||
worktreePath: props.worktreePath ?? '/a',
|
||||
branchName: props.branchName ?? 'main',
|
||||
compareBaseRef: props.compareBaseRef === undefined ? 'origin/main' : props.compareBaseRef,
|
||||
isFolder: props.isFolder ?? false,
|
||||
isBranchVisible: props.isBranchVisible ?? true,
|
||||
@@ -79,6 +81,19 @@ afterEach(() => {
|
||||
latest = null
|
||||
})
|
||||
|
||||
describe('useSourceControlGitHistory branch switch', () => {
|
||||
it('reloads the open list when the same workspace switches branches', async () => {
|
||||
const root = await mount({ branchName: 'main' })
|
||||
await flush()
|
||||
await act(async () => {
|
||||
root.render(<Probe branchName="feature" />)
|
||||
})
|
||||
await flush()
|
||||
|
||||
expect(mocks.getRuntimeGitHistory).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSourceControlGitHistory stale completion', () => {
|
||||
it('drops a stale response for a worktree the user already left and returned to', async () => {
|
||||
const firstA = deferred<GitHistoryResult>()
|
||||
|
||||
@@ -81,6 +81,8 @@ export type WorktreeMeta = {
|
||||
baseRef?: string
|
||||
/** True when Orca checked out a pre-existing local branch that delete must not prune. */
|
||||
preserveBranchOnDelete?: boolean
|
||||
/** The user switched to or created the current branch in Orca, so first-work naming must not rename it. */
|
||||
branchNameIsUserChosen?: boolean
|
||||
/** See {@link Worktree.pushTarget}. Persisted so refreshed worktree lists keep the target. */
|
||||
pushTarget?: GitPushTarget
|
||||
/** Explicit marker stamped when Orca creates the worktree. */
|
||||
|
||||
Reference in New Issue
Block a user