perf(worktrees): patch heads on HEAD-only watcher bursts instead of re-listing (#42941)

* perf(worktrees): patch heads on HEAD-only watcher bursts instead of re-listing

* fix(worktrees): fall back to re-list for headless or absorbed HEAD moves

* test(worktrees): cover orphan HEAD re-list fallback

* fix(worktrees): keep orphan fallback through merged scopes and patch hidden rows

* fix(worktrees): guard hidden-row head patches against stale listings and other hosts

* chore(worktrees): read detected rows through the selector; document test window cast

* chore(worktrees): read detected rows only through the selector

* fix(worktrees): skip the concurrent-head guard when no patch landed; keep pinned names on reattach
This commit is contained in:
Brennan Benson
2026-11-15 22:31:48 -08:00
committed by GitHub
parent 84f1c520a8
commit 5ff527c30b
21 changed files with 482 additions and 50 deletions
@@ -1,6 +1,7 @@
import type { BrowserWindow } from 'electron'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import { notifyWorktreesChanged } from './worktree-remote'
import { runWorktreeChangeInvalidators } from './worktrees/listing/worktree-change-invalidators'
type WorktreeCatalogRemoteClientNotifier = Pick<
OrcaRuntimeService,
@@ -20,6 +21,16 @@ export function notifyWatchedWorktreeCatalogChanged(
repoId: string
): void {
notifyWorktreesChanged(mainWindow, repoId)
notifyRemoteClientsOfWatchedCatalogChange(repoId)
}
/** Listed heads moved without structure: stale owners must rescan, but the local renderer patches its rows. */
export function notifyWatchedWorktreeHeadsMoved(repoId: string): void {
runWorktreeChangeInvalidators(repoId)
notifyRemoteClientsOfWatchedCatalogChange(repoId)
}
function notifyRemoteClientsOfWatchedCatalogChange(repoId: string): void {
try {
remoteClientNotifier?.notifyWorktreeCatalogChangedForRemoteClients(repoId)
} catch (error) {
@@ -17,6 +17,7 @@ export type WorktreeBaseCollectedChanges = {
structureRepoIds: string[]
gitStatusRepoIds: string[]
headIdentityRepoIds: string[]
headMoveRepoIds: string[]
headIdentityScope: WorktreeHeadIdentityScope
gitStatusScope: WorktreeHeadIdentityScope
}
@@ -31,6 +32,7 @@ type ChangeBuckets = {
structureRepoIds: Set<string>
gitStatusRepoIds: Set<string>
headIdentityRepoIds: Set<string>
headMoveRepoIds: Set<string>
headIdentityScope: WorktreeHeadIdentityScope
gitStatusScope: WorktreeHeadIdentityScope
}
@@ -40,6 +42,7 @@ function emptyBuckets(): ChangeBuckets {
structureRepoIds: new Set<string>(),
gitStatusRepoIds: new Set<string>(),
headIdentityRepoIds: new Set<string>(),
headMoveRepoIds: new Set<string>(),
headIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
gitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE
}
@@ -60,6 +63,9 @@ function addMatchingChange(
for (const repoId of change.headIdentityRepoIds) {
buckets.headIdentityRepoIds.add(repoId)
}
for (const repoId of change.headMoveRepoIds) {
buckets.headMoveRepoIds.add(repoId)
}
buckets.headIdentityScope = mergeHeadIdentityScopes(
buckets.headIdentityScope,
change.headIdentityScope
@@ -72,6 +78,7 @@ function toCollectedChanges(buckets: ChangeBuckets): WorktreeBaseCollectedChange
structureRepoIds: [...buckets.structureRepoIds],
gitStatusRepoIds: [...buckets.gitStatusRepoIds],
headIdentityRepoIds: [...buckets.headIdentityRepoIds],
headMoveRepoIds: [...buckets.headMoveRepoIds],
headIdentityScope: buckets.headIdentityScope,
gitStatusScope: buckets.gitStatusScope
}
@@ -22,6 +22,8 @@ export type WorktreeBaseChangeClass = {
gitStatusRepoIds: string[]
// Head moves refresh status plus head identity; index churn must stay status-only.
headIdentityRepoIds: string[]
// Linked HEAD leaf writes: listed heads moved without structure; identity reads replace the local re-list.
headMoveRepoIds: string[]
// Every classification states its scope; EMPTY proves no head moved.
headIdentityScope: WorktreeHeadIdentityScope
// Attribute status to worktrees; FULL means the change cannot be narrowed.
@@ -34,6 +36,8 @@ export type WorktreeBaseRepoWatchConfig = {
repoId: string
repoName: string
nestWorkspaces: boolean
// WSL-mirrored gitdir paths need not match listed rows, so identity patches cannot replace a re-list.
headMovesNeedListing?: boolean
}
export type WorktreeBaseWatchTarget = {
@@ -108,9 +112,9 @@ const GIT_COMMON_PRIMARY_STRUCTURAL_SCOPES = new Map<string, WorktreeHeadIdentit
['packed-refs', FULL_HEAD_IDENTITY_SCOPE],
['config.worktree', EMPTY_HEAD_IDENTITY_SCOPE]
])
const GIT_COMMON_LINKED_STRUCTURAL_FILES = new Set(['HEAD', 'gitdir', 'locked', 'config.worktree'])
// HEAD/gitdir affect identity; locked/config.worktree change structure without moving heads.
const GIT_COMMON_LINKED_HEAD_SOURCE_FILES = new Set(['HEAD', 'gitdir'])
const GIT_COMMON_LINKED_STRUCTURAL_FILES = new Set(['gitdir', 'locked', 'config.worktree'])
// gitdir affects identity; locked/config.worktree change structure without moving heads.
const GIT_COMMON_LINKED_HEAD_SOURCE_FILES = new Set(['gitdir'])
const GIT_COMMON_LINKED_STATUS_FILES = new Set(['index'])
// logs/HEAD captures amend/reset moves without index/HEAD leaf writes; status-only churn never appends it.
@@ -141,6 +145,7 @@ const NO_CHANGE: WorktreeBaseChangeClass = {
structureRepoIds: [],
gitStatusRepoIds: [],
headIdentityRepoIds: [],
headMoveRepoIds: [],
headIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
gitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE
}
@@ -153,6 +158,7 @@ function structuralChange(
structureRepoIds: repoIds,
gitStatusRepoIds: [],
headIdentityRepoIds: [],
headMoveRepoIds: [],
headIdentityScope,
gitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE
}
@@ -166,6 +172,7 @@ function gitStatusChange(
structureRepoIds: [],
gitStatusRepoIds: repoIds,
headIdentityRepoIds: [],
headMoveRepoIds: [],
headIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
gitStatusScope
}
@@ -173,12 +180,14 @@ function gitStatusChange(
function headIdentityChange(
repoIds: string[],
headIdentityScope: WorktreeHeadIdentityScope
headIdentityScope: WorktreeHeadIdentityScope,
headMoveRepoIds: string[] = []
): WorktreeBaseChangeClass {
return {
structureRepoIds: [],
gitStatusRepoIds: [],
headIdentityRepoIds: repoIds,
headMoveRepoIds,
headIdentityScope,
// Shared branch moves can change any checkout's local upstream; refs/heads are not polled directly.
gitStatusScope: FULL_HEAD_IDENTITY_SCOPE
@@ -233,6 +242,12 @@ function classifyGitCommonEvent(
)
}
if (parts.length === 3) {
if (parts[2] === 'HEAD') {
// A vanished HEAD may be a removal in progress; only writes keep the entry listed.
return event.type === 'delete'
? structuralChange(repoIds, headIdentityScopeForEntry(parts[1]))
: headIdentityChange(repoIds, headIdentityScopeForEntry(parts[1]), repoIds)
}
if (GIT_COMMON_LINKED_STRUCTURAL_FILES.has(parts[2])) {
return structuralChange(
repoIds,
@@ -0,0 +1,154 @@
import { execFileSync } from 'node:child_process'
import { mkdtempSync, realpathSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { collectLocalWorktreeBaseChanges } from './worktree-base-directory-change-collector'
import {
scheduleWorktreeBaseNotification,
type WorktreeBaseNotificationWatch
} from './worktree-base-directory-notifications'
import {
createWorktreeHeadIdentityRefreshState,
refreshWorktreeHeadIdentities
} from './worktree-head-identity-refresh'
import { EMPTY_HEAD_IDENTITY_SCOPE } from './worktree-head-identity-scope'
const REPO_ID = 'repo-1'
const tempDirs: string[] = []
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim()
}
function createRepoWithLinkedWorktree(): { commonDir: string; linkedPath: string } {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-head-move-')))
tempDirs.push(root)
const repoPath = join(root, 'repo')
const linkedPath = join(root, 'linked')
execFileSync('git', ['init', '-q', '-b', 'main', repoPath])
for (const [key, value] of [
['user.email', 'test@example.com'],
['user.name', 'Test'],
['commit.gpgsign', 'false']
]) {
git(repoPath, 'config', key, value)
}
git(repoPath, 'commit', '-q', '--allow-empty', '-m', 'one')
git(repoPath, 'worktree', 'add', '-q', '-b', 'feature', linkedPath)
return { commonDir: join(repoPath, '.git'), linkedPath }
}
function createWatch(
commonDir: string,
runtimeEnvironmentActive = false
): WorktreeBaseNotificationWatch & { sent: { channel: string; payload: unknown }[] } {
const sent: { channel: string; payload: unknown }[] = []
return {
key: `git-common:${commonDir}`,
kind: 'git-common',
path: commonDir,
repos: new Map([[REPO_ID, { repoId: REPO_ID, repoName: 'repo', nestWorkspaces: false }]]),
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the watcher only calls isDestroyed and webContents.send.
mainWindow: {
isDestroyed: () => false,
webContents: { send: (channel: string, payload: unknown) => sent.push({ channel, payload }) }
} as never,
notifyTimer: null,
pendingStructureRepoIds: new Set(),
pendingGitStatusRepoIds: new Set(),
pendingHeadIdentityRepoIds: new Set(),
pendingHeadMoveRepoIds: new Set(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
isRuntimeEnvironmentActive: () => runtimeEnvironmentActive,
disposed: false,
sent
}
}
async function flushLinkedHeadWrite(
watch: ReturnType<typeof createWatch>,
commonDir: string
): Promise<void> {
scheduleWorktreeBaseNotification(
watch,
collectLocalWorktreeBaseChanges(watch, [
{ type: 'update', path: join(commonDir, 'worktrees', 'linked', 'HEAD') }
])
)
// The debounce starts the identity read synchronously, so both settle together.
await vi.waitFor(() => {
expect(watch.notifyTimer).toBeNull()
expect(watch.headIdentityRefresh.inFlight).toBe(false)
})
}
function channels(watch: ReturnType<typeof createWatch>): string[] {
return watch.sent.map((entry) => entry.channel)
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
describe('linked HEAD-only watcher bursts', () => {
it('patches the moved head without re-listing the local catalog', async () => {
const { commonDir, linkedPath } = createRepoWithLinkedWorktree()
const watch = createWatch(commonDir)
await refreshWorktreeHeadIdentities(watch, watch.headIdentityRefresh, false)
git(linkedPath, 'checkout', '-q', '--detach')
git(linkedPath, 'commit', '-q', '--allow-empty', '-m', 'two')
const movedHead = git(linkedPath, 'rev-parse', 'HEAD')
await flushLinkedHeadWrite(watch, commonDir)
await vi.waitFor(() =>
expect(watch.sent).toContainEqual({
channel: 'worktrees:headIdentitiesChanged',
payload: {
repoId: REPO_ID,
identities: [{ worktreePath: linkedPath, head: movedHead, branch: null }]
}
})
)
expect(channels(watch)).toContain('worktrees:gitStatusMetadataChanged')
expect(channels(watch)).not.toContain('worktrees:changed')
})
it('re-lists when the renderer ignores head identities under a runtime environment', async () => {
const { commonDir, linkedPath } = createRepoWithLinkedWorktree()
const watch = createWatch(commonDir, true)
await refreshWorktreeHeadIdentities(watch, watch.headIdentityRefresh, false)
git(linkedPath, 'commit', '-q', '--allow-empty', '-m', 'two')
await flushLinkedHeadWrite(watch, commonDir)
expect(channels(watch)).toContain('worktrees:changed')
expect(channels(watch)).not.toContain('worktrees:headIdentitiesChanged')
})
it('falls back to a re-list when no baseline proves the move was published', async () => {
const { commonDir, linkedPath } = createRepoWithLinkedWorktree()
const watch = createWatch(commonDir)
git(linkedPath, 'commit', '-q', '--allow-empty', '-m', 'two')
await flushLinkedHeadWrite(watch, commonDir)
await vi.waitFor(() => expect(channels(watch)).toContain('worktrees:changed'))
})
it('re-lists when the moved HEAD has no commit to publish', async () => {
const { commonDir, linkedPath } = createRepoWithLinkedWorktree()
const watch = createWatch(commonDir)
await refreshWorktreeHeadIdentities(watch, watch.headIdentityRefresh, false)
git(linkedPath, 'switch', '-q', '--orphan', 'scratch')
await flushLinkedHeadWrite(watch, commonDir)
await vi.waitFor(() => expect(channels(watch)).toContain('worktrees:changed'))
})
})
@@ -17,10 +17,14 @@ import {
cachedWorktreePathsForScope
} from './worktree-head-identity-cached-paths'
import { invalidateGitStatusReads } from '../../../git/source-control/git-read-cache-invalidation'
import { notifyWorktreeGitStatusMetadataChanged } from '../../worktree-remote'
import {
notifyWorktreeGitStatusMetadataChanged,
notifyWorktreesChanged
} from '../../worktree-remote'
import {
notifyGitStatusChangedForRemoteClients,
notifyWatchedWorktreeCatalogChanged
notifyWatchedWorktreeCatalogChanged,
notifyWatchedWorktreeHeadsMoved
} from '../../watched-worktree-catalog-notification'
export type WorktreeBaseNotificationWatch = WorktreeBaseWatchTarget & {
@@ -29,9 +33,12 @@ export type WorktreeBaseNotificationWatch = WorktreeBaseWatchTarget & {
pendingStructureRepoIds: Set<string>
pendingGitStatusRepoIds: Set<string>
pendingHeadIdentityRepoIds: Set<string>
pendingHeadMoveRepoIds: Set<string>
pendingHeadIdentityScope: WorktreeHeadIdentityScope
pendingGitStatusScope: WorktreeHeadIdentityScope
headIdentityRefresh: WorktreeHeadIdentityRefreshState
// The renderer ignores head-identity events under a runtime environment; its local rows refresh only by re-list.
isRuntimeEnvironmentActive: () => boolean
disposed: boolean
}
@@ -41,6 +48,7 @@ export function clearPendingWorktreeBaseNotifications(watch: WorktreeBaseNotific
watch.pendingStructureRepoIds.clear()
watch.pendingGitStatusRepoIds.clear()
watch.pendingHeadIdentityRepoIds.clear()
watch.pendingHeadMoveRepoIds.clear()
watch.pendingHeadIdentityScope = EMPTY_HEAD_IDENTITY_SCOPE
watch.pendingGitStatusScope = EMPTY_HEAD_IDENTITY_SCOPE
}
@@ -49,6 +57,15 @@ export function supportsWorktreeHeadIdentityRefresh(watch: WorktreeBaseNotificat
return watch.kind === 'git-common'
}
// HEAD-only bursts can patch heads from spawn-free reads only where those reads reach the renderer's rows.
function headMovesNeedListing(watch: WorktreeBaseNotificationWatch): boolean {
return (
!supportsWorktreeHeadIdentityRefresh(watch) ||
watch.isRuntimeEnvironmentActive() ||
[...watch.repos.values()].some((config) => config.headMovesNeedListing === true)
)
}
// Structural and unattributed bursts may touch any checkout of this common dir, but no other repo's.
function changedWorktreePaths(
watch: WorktreeBaseNotificationWatch,
@@ -82,6 +99,9 @@ export function scheduleWorktreeBaseNotification(
for (const repoId of changes.headIdentityRepoIds ?? []) {
watch.pendingHeadIdentityRepoIds.add(repoId)
}
for (const repoId of changes.headMoveRepoIds ?? []) {
watch.pendingHeadMoveRepoIds.add(repoId)
}
// Unattributed bursts lose knowledge; widen to all heads rather than narrowing to none.
watch.pendingHeadIdentityScope = mergeHeadIdentityScopes(
watch.pendingHeadIdentityScope,
@@ -101,7 +121,15 @@ export function scheduleWorktreeBaseNotification(
clearPendingWorktreeBaseNotifications(watch)
return
}
if (watch.pendingHeadMoveRepoIds.size > 0 && headMovesNeedListing(watch)) {
for (const repoId of watch.pendingHeadMoveRepoIds) {
watch.pendingStructureRepoIds.add(repoId)
}
}
const pendingStructure = [...watch.pendingStructureRepoIds]
const headMoveRepoIds = [...watch.pendingHeadMoveRepoIds].filter(
(repoId) => !watch.pendingStructureRepoIds.has(repoId)
)
const hasHeadIdentity = watch.pendingHeadIdentityRepoIds.size > 0
const sourceControlRepoIds = new Set(
[...watch.pendingGitStatusRepoIds, ...watch.pendingHeadIdentityRepoIds].filter(
@@ -133,6 +161,10 @@ export function scheduleWorktreeBaseNotification(
notifyWorktreeGitStatusMetadataChanged(watch.mainWindow, repoId, gitStatusWorktreePaths)
notifyGitStatusChangedForRemoteClients(repoId, gitStatusWorktreePaths)
}
// Owners and remote clients re-read listed heads; the local renderer patches them from the identity read.
for (const repoId of headMoveRepoIds) {
notifyWatchedWorktreeHeadsMoved(repoId)
}
if (
supportsWorktreeHeadIdentityRefresh(watch) &&
(pendingStructure.length > 0 || hasHeadIdentity)
@@ -141,7 +173,15 @@ export function scheduleWorktreeBaseNotification(
watch,
watch.headIdentityRefresh,
emitHeadIdentities,
headIdentityScope
headIdentityScope,
headMoveRepoIds.length > 0
? () => {
// Owners and remote clients were already told; the local renderer re-lists unpublished heads.
for (const repoId of headMoveRepoIds) {
notifyWorktreesChanged(watch.mainWindow, repoId)
}
}
: undefined
)
}
}, WATCH_DEBOUNCE_MS)
@@ -85,7 +85,8 @@ async function maybeAddBaseTarget(
const config = {
repoId: repo.id,
repoName: getRuntimePathBasename(repo.path).replace(/\.git$/, ''),
nestWorkspaces: pathSettings.nestWorkspaces
nestWorkspaces: pathSettings.nestWorkspaces,
headMovesNeedListing: mirrorDistro !== undefined
}
// A root mirrored into WSL is a UNC path either way; probing the distro's home (which can kill a
// booting distro) would only lead to the same skip, so keep just the Git-common watch.
@@ -46,6 +46,7 @@ export function setWorktreeGitStatusRefWatch(
function createActiveWatch(
target: WorktreeBaseWatchTarget,
mainWindow: BrowserWindow,
store: Store,
subscription: ActiveWatch['subscription'],
gitStatusRefPaths: Set<string>
): ActiveWatch {
@@ -57,9 +58,12 @@ function createActiveWatch(
pendingStructureRepoIds: new Set(),
pendingGitStatusRepoIds: new Set(),
pendingHeadIdentityRepoIds: new Set(),
pendingHeadMoveRepoIds: new Set(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
isRuntimeEnvironmentActive: () =>
Boolean(store.getSettings().activeRuntimeEnvironmentId?.trim()),
gitStatusRefPaths,
watcherFailureRefresh: new WorktreeWatcherFailureRefreshCooldown(),
disposed: false
@@ -68,7 +72,8 @@ function createActiveWatch(
async function subscribeTarget(
target: WorktreeBaseWatchTarget,
mainWindow: BrowserWindow
mainWindow: BrowserWindow,
store: Store
): Promise<ActiveWatch> {
let activeWatch: ActiveWatch | null = null
const gitStatusRefPaths = new Set<string>()
@@ -102,7 +107,7 @@ async function subscribeTarget(
}
}
)
activeWatch = createActiveWatch(target, mainWindow, subscription, gitStatusRefPaths)
activeWatch = createActiveWatch(target, mainWindow, store, subscription, gitStatusRefPaths)
if (supportsWorktreeHeadIdentityRefresh(activeWatch)) {
// Baseline at subscribe time so the first later head signal cannot silently skip an external commit.
void refreshWorktreeHeadIdentities(activeWatch, activeWatch.headIdentityRefresh, false)
@@ -113,6 +118,7 @@ async function subscribeTarget(
async function replaceWatch(
target: WorktreeBaseWatchTarget,
mainWindow: BrowserWindow,
store: Store,
generation: number
): Promise<void> {
const previous = activeWatches.get(target.key)
@@ -123,7 +129,7 @@ async function replaceWatch(
return
}
try {
const activeWatch = await subscribeTarget(target, mainWindow)
const activeWatch = await subscribeTarget(target, mainWindow, store)
if (generation !== syncGeneration) {
activeWatch.disposed = true
await activeWatch.subscription.unsubscribe().catch((error) => {
@@ -178,7 +184,7 @@ export async function syncWorktreeBaseDirectoryWatchers(
if (generation !== syncGeneration) {
return
}
await replaceWatch(target, mainWindow, generation)
await replaceWatch(target, mainWindow, store, generation)
if (generation !== syncGeneration) {
return
}
@@ -38,6 +38,8 @@ export type GitCommonHeadIdentityRead = {
identities: WorktreeHeadIdentity[]
/** Incomplete listing/metadata reads cannot establish a full freshness checkpoint. */
complete: boolean
/** Entry keys read this pass without a head (unborn or invalid), so no identity can publish them. */
headlessEntryKeys: ReadonlySet<string>
}
/** ref → oid resolved during one pass; null means the ref no longer resolves. */
@@ -284,7 +286,11 @@ export async function readGitCommonHeadIdentities(
}
if (entryNames === null) {
// Failed initial listing must leave the memo unset for retry.
return { identities: cache.primary ? [cache.primary] : [], complete: false }
return {
identities: cache.primary ? [cache.primary] : [],
complete: false,
headlessEntryKeys: new Set()
}
}
let entryKeys = entryNames.map(headIdentityEntryKey)
@@ -305,6 +311,7 @@ export async function readGitCommonHeadIdentities(
const reads = await mapWithConcurrency(staleNames, HEAD_IDENTITY_READ_CONCURRENCY, (name) =>
readLinkedEntryIdentity(commonDirPath, name, packedRefs, resolved)
)
const headlessEntryKeys = new Set<string>()
staleNames.forEach((name, index) => {
const identity = reads[index]
if (identity === UNREADABLE) {
@@ -316,6 +323,7 @@ export async function readGitCommonHeadIdentities(
cache.entries.set(name, identity)
} else {
cache.entries.delete(name)
headlessEntryKeys.add(headIdentityEntryKey(name))
}
})
applyResolvedRefOids(cache, resolved)
@@ -331,6 +339,7 @@ export async function readGitCommonHeadIdentities(
}
return {
identities,
complete: !listingStale && cache.unverified.size === 0 && !cache.primaryUnverified
complete: !listingStale && cache.unverified.size === 0 && !cache.primaryUnverified,
headlessEntryKeys
}
}
@@ -20,6 +20,9 @@ type HeadIdentityWatchHost = {
disposed: boolean
}
// Keys stay with the callback: merging into a full scope drops entry names.
type UnverifiedHeadFallback = { entryKeys: ReadonlySet<string>; run: () => void }
export type WorktreeHeadIdentityRefreshState = {
/** worktreePath → `${head} ${branch}` from the last metadata-file read. */
baseline: Map<string, string> | null
@@ -28,6 +31,8 @@ export type WorktreeHeadIdentityRefreshState = {
inFlight: boolean
queuedScope: WorktreeHeadIdentityScope | null
queuedEmit: boolean
/** Callers whose freshness depends on the next pass publishing their entries' heads. */
queuedUnverified: UnverifiedHeadFallback[]
/** One-shot catch-up armed only by a scoped pass; see `scheduleRebaseline`. */
rebaselineTimer: ReturnType<typeof setTimeout> | null
}
@@ -43,6 +48,7 @@ export function createWorktreeHeadIdentityRefreshState(): WorktreeHeadIdentityRe
inFlight: false,
queuedScope: null,
queuedEmit: false,
queuedUnverified: [],
rebaselineTimer: null
}
}
@@ -92,16 +98,21 @@ function resolveScope(
: scope
}
/** Publish actual head moves; structural callers rebaseline silently because their catalog refresh carries the heads. */
/** Publish actual head moves; structural callers rebaseline silently because their catalog refresh carries the heads.
* `onUnverified` runs when this request's pass fails or cannot prove every head was published. */
export async function refreshWorktreeHeadIdentities(
host: HeadIdentityWatchHost,
state: WorktreeHeadIdentityRefreshState,
emit: boolean,
scope: WorktreeHeadIdentityScope = FULL_HEAD_IDENTITY_SCOPE
scope: WorktreeHeadIdentityScope = FULL_HEAD_IDENTITY_SCOPE,
onUnverified?: () => void
): Promise<void> {
if (host.disposed || host.mainWindow.isDestroyed()) {
return
}
if (onUnverified) {
state.queuedUnverified.push({ entryKeys: scope.entryNames, run: onUnverified })
}
if (state.inFlight) {
state.queuedScope = mergeHeadIdentityScopes(
state.queuedScope ?? EMPTY_HEAD_IDENTITY_SCOPE,
@@ -115,8 +126,11 @@ export async function refreshWorktreeHeadIdentities(
? mergeHeadIdentityScopes(state.queuedScope, scope)
: scope
const requestedEmit = emit || state.queuedEmit
const unverifiedCallbacks = state.queuedUnverified
state.queuedScope = null
state.queuedEmit = false
state.queuedUnverified = []
let read: { complete: boolean; headlessEntryKeys: ReadonlySet<string> } | null = null
// Promote before skipping empty scope so structural-only churn cannot starve full rereads.
const effectiveScope = resolveScope(state, requestedScope)
// Empty scopes prove no head moved; promoted structural passes stay silent because catalog notification covers every repo.
@@ -125,7 +139,7 @@ export async function refreshWorktreeHeadIdentities(
}
state.inFlight = true
try {
const { identities, complete } = await readGitCommonHeadIdentities(
const { identities, complete, headlessEntryKeys } = await readGitCommonHeadIdentities(
host.path,
state.cache,
effectiveScope
@@ -143,9 +157,10 @@ export async function refreshWorktreeHeadIdentities(
for (const identity of identities) {
nextBaseline.set(identity.worktreePath, headIdentitySignature(identity))
}
// Silent head-moving passes accompany structural catalog notification, which publishes the authoritative heads.
// Silent head-moving passes accompany structural catalog notification, which publishes the authoritative heads;
// an emitting request queued mid-pass would diff against this baseline, so publish its moves now.
const changed =
baseline && requestedEmit
baseline && (requestedEmit || state.queuedEmit)
? identities.filter(
(identity) => baseline.get(identity.worktreePath) !== headIdentitySignature(identity)
)
@@ -153,8 +168,14 @@ export async function refreshWorktreeHeadIdentities(
for (const repoId of changed.length > 0 ? host.repos.keys() : []) {
notifyWorktreeHeadIdentitiesChanged(host.mainWindow, repoId, changed)
}
if (baseline === null) {
// This first baseline absorbs moves queued mid-read, so their next pass cannot publish them either.
unverifiedCallbacks.push(...state.queuedUnverified.splice(0))
}
// Commit baseline after notification so a partial send failure retries instead of burying the move.
state.baseline = nextBaseline
// Without a prior baseline nothing was diffed, so no move could have been published.
read = baseline === null ? null : { complete, headlessEntryKeys }
} catch (error) {
console.warn(`[worktree-base-watcher] head identity read failed for ${host.path}:`, error)
// Failed reads invalidate partial memo state; force a full refresh next time.
@@ -162,6 +183,17 @@ export async function refreshWorktreeHeadIdentities(
state.lastFullReadAtMs = 0
} finally {
state.inFlight = false
if (!host.disposed && !host.mainWindow.isDestroyed()) {
for (const fallback of unverifiedCallbacks) {
// A headless entry (orphan branch) has no identity to publish.
if (
!read?.complete ||
[...fallback.entryKeys].some((key) => read?.headlessEntryKeys.has(key))
) {
fallback.run()
}
}
}
if (state.queuedScope && !host.disposed) {
// Keep queued scope for a later live-window call if this rerun cannot proceed.
void refreshWorktreeHeadIdentities(host, state, state.queuedEmit, state.queuedScope)
@@ -190,9 +190,11 @@ describe('external worktree discovery for paired clients', () => {
pendingStructureRepoIds: new Set<string>(),
pendingGitStatusRepoIds: new Set<string>(),
pendingHeadIdentityRepoIds: new Set<string>(),
pendingHeadMoveRepoIds: new Set<string>(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
isRuntimeEnvironmentActive: () => false,
disposed: false
}
vi.useFakeTimers()
@@ -378,9 +380,11 @@ describe('external worktree discovery for paired clients', () => {
pendingStructureRepoIds: new Set<string>(),
pendingGitStatusRepoIds: new Set<string>(),
pendingHeadIdentityRepoIds: new Set<string>(),
pendingHeadMoveRepoIds: new Set<string>(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
isRuntimeEnvironmentActive: () => false,
disposed: false
}
vi.useFakeTimers()
@@ -465,9 +469,11 @@ describe('external worktree discovery for paired clients', () => {
pendingStructureRepoIds: new Set<string>(),
pendingGitStatusRepoIds: new Set<string>(),
pendingHeadIdentityRepoIds: new Set<string>(),
pendingHeadMoveRepoIds: new Set<string>(),
pendingHeadIdentityScope: EMPTY_HEAD_IDENTITY_SCOPE,
pendingGitStatusScope: EMPTY_HEAD_IDENTITY_SCOPE,
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
isRuntimeEnvironmentActive: () => false,
disposed: false
}
vi.useFakeTimers()
@@ -4,6 +4,7 @@ import type { WorktreeChangeRefreshQueue } from '../worktree-change-refresh-queu
import { useAppStore } from '../../store'
import { adoptFromEndpoint } from '../../store/host-catalog/endpoint-catalog-adoption'
import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields'
import { patchDetectedWorktreeHeadIdentities } from '@/store/slices/worktrees/listing/detected-worktree-head-identity'
export function registerProjectCatalogIpcBridge(
unsubs: (() => void)[],
@@ -63,6 +64,9 @@ export function registerProjectCatalogIpcBridge(
getWorktreesForRepo: (repoId) => selectWorktreesByRepo(state)[repoId],
updateWorktreeGitIdentity: state.updateWorktreeGitIdentity
})
useAppStore.setState(
(s) => patchDetectedWorktreeHeadIdentities(s, data.repoId, data.identities) ?? s
)
})
)
}
@@ -11,7 +11,10 @@ export type WorktreeHeadIdentityApplyDeps = {
) => void
}
function findWorktreeByPath(worktrees: Worktree[], worktreePath: string): Worktree | undefined {
export function findWorktreeByPath<T extends Worktree>(
worktrees: readonly T[],
worktreePath: string
): T | undefined {
const exact = worktrees.find((worktree) => worktree.path === worktreePath)
if (exact) {
return exact
@@ -0,0 +1,91 @@
import type {
DetectedWorktree,
WorktreeHeadIdentity
} from '../../../../../../shared/worktree/types'
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host'
import type { AppState } from '../../../types'
import { findWorktreeByPath } from '../../../../hooks/worktree-head-identity-apply'
import { deriveGitIdentityDisplayName } from '../metadata/detached-head-display-name'
import { worktreeHostMatchOptions, worktreeMatchesHost } from './worktree-host-ownership'
import { selectDetectedWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields'
/** Head-only watcher bursts no longer re-list, so local detected rows take the same head patch as visible rows. */
export function patchDetectedWorktreeHeadIdentities(
state: Pick<AppState, 'repos' | 'detectedWorktreesByRepo'>,
repoId: string,
identities: readonly WorktreeHeadIdentity[]
): Pick<AppState, 'detectedWorktreesByRepo'> | null {
const detectedByRepo = selectDetectedWorktreesByRepo(state)
const detected = detectedByRepo[repoId]
if (!detected) {
return null
}
const options = worktreeHostMatchOptions(state, repoId, LOCAL_EXECUTION_HOST_ID)
// Why local only: the watcher reads this machine's checkouts, never a same-path twin on another host.
const localRows = detected.worktrees.filter((row) =>
worktreeMatchesHost(row, LOCAL_EXECUTION_HOST_ID, options)
)
let worktrees = detected.worktrees
for (const identity of identities) {
const row = findWorktreeByPath(localRows, identity.worktreePath)
const branch = identity.branch ?? ''
if (!row || (row.head === identity.head && row.branch === branch)) {
continue
}
const patched: DetectedWorktree = {
...row,
head: identity.head,
branch,
displayName: deriveGitIdentityDisplayName(row, row.id, branch, identity.branch)
}
worktrees = worktrees.map((candidate) => (candidate === row ? patched : candidate))
}
return worktrees === detected.worktrees
? null
: {
detectedWorktreesByRepo: {
...detectedByRepo,
[repoId]: { ...detected, worktrees }
}
}
}
/** A listing that started before a head patch must not roll that row's head, branch or derived name back. */
export function preserveConcurrentDetectedHeads(
merged: DetectedWorktree[],
requestStarted: readonly DetectedWorktree[] | undefined,
current: readonly DetectedWorktree[] | undefined,
matchesRefreshHost: (worktree: DetectedWorktree) => boolean
): DetectedWorktree[] {
if (!requestStarted || !current || requestStarted === current) {
return merged
}
const startedById = new Map(
requestStarted.filter(matchesRefreshHost).map((worktree) => [worktree.id, worktree])
)
const currentById = new Map(
current.filter(matchesRefreshHost).map((worktree) => [worktree.id, worktree])
)
let changed = false
const worktrees = merged.map((worktree) => {
const started = startedById.get(worktree.id)
const latest = currentById.get(worktree.id)
if (
!matchesRefreshHost(worktree) ||
!started ||
!latest ||
(latest.head === started.head && latest.branch === started.branch) ||
(worktree.head === latest.head && worktree.branch === latest.branch)
) {
return worktree
}
changed = true
return {
...worktree,
head: latest.head,
branch: latest.branch,
displayName: latest.displayName
}
})
return changed ? worktrees : merged
}
@@ -1,23 +1,40 @@
import type { ProjectHostSetup } from '../../../../../../shared/project/project-types'
import type { DetectedWorktreeListResult } from '../../../../../../shared/worktree/types'
import type {
DetectedWorktree,
DetectedWorktreeListResult
} from '../../../../../../shared/worktree/types'
import type { ExecutionHostId } from '../../../../../../shared/execution-host'
import { sanitizeHostedReviewLinksForBranchClears } from '../metadata/hosted-review-link-mutation'
import { mergeWorktreesForHost, withRepoHostOwnership } from './worktree-host-ownership'
import {
mergeWorktreesForHost,
withRepoHostOwnership,
worktreeMatchesHost
} from './worktree-host-ownership'
import { preserveConcurrentDetectedHeads } from './detected-worktree-head-identity'
import type { WorktreeHostMatchOptions } from './worktree-slice-types'
export function mergeDetectedWorktreesForHost(
current: DetectedWorktreeListResult | undefined,
refreshed: DetectedWorktreeListResult,
hostId: ExecutionHostId,
setup?: ProjectHostSetup,
listing: {
setup?: ProjectHostSetup
// Rows seen when the listing started, so a newer head patch survives an older listing.
requestStartedDetectedWorktrees?: readonly DetectedWorktree[]
},
options?: WorktreeHostMatchOptions
): DetectedWorktreeListResult {
// Why stamp first: a twin's review-clear tombstone matches rows by their owner stamp.
const refreshedForHost = sanitizeHostedReviewLinksForBranchClears(
refreshed.worktrees.map((worktree) => withRepoHostOwnership(worktree, hostId, setup)),
refreshed.worktrees.map((worktree) => withRepoHostOwnership(worktree, hostId, listing.setup)),
current?.worktrees
)
const worktrees = mergeWorktreesForHost(current?.worktrees, refreshedForHost, hostId, options)
const worktrees = preserveConcurrentDetectedHeads(
mergeWorktreesForHost(current?.worktrees, refreshedForHost, hostId, options),
listing.requestStartedDetectedWorktrees,
current?.worktrees,
(worktree) => worktreeMatchesHost(worktree, hostId, options)
)
if (
current &&
current.repoId === refreshed.repoId &&
@@ -16,7 +16,10 @@ import { mergeFetchedWorktrees } from './fetched-worktree-merge'
import { listingMetadataCoverage } from './workspace-metadata-coverage'
import { notifyRuntimeScopeForbiddenIfNeeded } from './runtime-scope-forbidden-toast'
import { mapReposForWorktreeRefresh } from './worktree-refresh-pool'
import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields'
import {
selectDetectedWorktreesByRepo,
selectWorktreesByRepo
} from '../../../workspaces/catalog/workspace-record-fields'
import { purgeHydratedWorktrees } from './hydrated-worktree-purge'
import type { WorktreeRefreshResult } from './worktree-refresh-result'
@@ -43,6 +46,8 @@ export function createFetchAllWorktrees(
try {
const requestStartedState = get()
const requestStartedWorktrees = selectWorktreesByRepo(requestStartedState)[repo.id]
const requestStartedDetectedWorktrees =
selectDetectedWorktreesByRepo(requestStartedState)[repo.id]?.worktrees
const setup = getProjectHostSetupForRepoHost(requestStartedState, repo.id, hostId)
const parsedHost = parseExecutionHostId(hostId)
const directSshAuthority =
@@ -71,6 +76,7 @@ export function createFetchAllWorktrees(
hostId,
ownerWasMissingAtStart: false,
requestStartedWorktrees,
requestStartedDetectedWorktrees,
setup,
refresh: metadata.refresh,
purgeRemovedWorktrees
@@ -1,3 +1,4 @@
import { selectDetectedWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields'
import type { WorktreeSlice } from '../worktree-slice-contract'
import {
appliedWorktreeCatalogVersionPatch,
@@ -27,6 +28,8 @@ export function createFetchDetectedWorktrees(
return async (repoId) => {
try {
const ownerState = get()
const requestStartedDetectedWorktrees =
selectDetectedWorktreesByRepo(ownerState)[repoId]?.worktrees
const hostId = repoHostId(ownerState, repoId)
const ownerWasMissingAtStart = !ownerState.repos.some((repo) => repo.id === repoId)
const setup = getProjectHostSetupForRepoHost(ownerState, repoId, hostId)
@@ -74,7 +77,7 @@ export function createFetchDetectedWorktrees(
s.detectedWorktreesByRepo[repoId],
refresh.result,
hostId,
setup,
{ setup, requestStartedDetectedWorktrees },
worktreeHostMatchOptions(s, repoId, hostId)
)
const versionPatch = appliedWorktreeCatalogVersionPatch(
@@ -23,7 +23,10 @@ import { mergeFetchedWorktrees } from './fetched-worktree-merge'
import { listingMetadataCoverage } from './workspace-metadata-coverage'
import { notifyRuntimeScopeForbiddenIfNeeded } from './runtime-scope-forbidden-toast'
import { refreshRemoteWorktreeLineageBestEffort } from '../metadata/worktree-lineage-refresh'
import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields'
import {
selectDetectedWorktreesByRepo,
selectWorktreesByRepo
} from '../../../workspaces/catalog/workspace-record-fields'
export function createFetchWorktrees(
set: WorktreeSliceSet,
@@ -52,6 +55,8 @@ export function createFetchWorktrees(
try {
const ownerState = get()
const requestStartedWorktrees = selectWorktreesByRepo(ownerState)[repoId]
const requestStartedDetectedWorktrees =
selectDetectedWorktreesByRepo(ownerState)[repoId]?.worktrees
const repoOwners = ownerState.repos.filter((repo) => repo.id === repoId)
const ownerWasMissingAtStart = repoOwners.length === 0
const hasLocalOwner = repoOwners.some(
@@ -107,6 +112,7 @@ export function createFetchWorktrees(
? ownerState.repos
: undefined,
requestStartedWorktrees,
requestStartedDetectedWorktrees,
setup,
refresh: metadata.refresh
})
@@ -216,7 +216,7 @@ export function mergeFetchedWorktrees(
s.detectedWorktreesByRepo[args.repoId],
refreshResult,
args.hostId,
args.setup,
args,
matchOptions
)
// Stored rows from a stopped WSL distro lack branch state the scanned rows already have.
@@ -2,6 +2,7 @@ import type { StateCreator } from 'zustand'
import type { AppState } from '../../../types'
import type { WorktreeSlice } from '../worktree-slice-contract'
import type {
DetectedWorktree,
DetectedWorktreeListResult,
GitPushTarget,
Worktree
@@ -97,6 +98,7 @@ export type FencedWorktreeMergeArgs = {
ownerWasMissingAtStart: boolean
missingDirectSshOwnerReposSnapshot?: AppState['repos']
requestStartedWorktrees: readonly Worktree[] | undefined
requestStartedDetectedWorktrees?: readonly DetectedWorktree[]
setup?: ProjectHostSetup
refresh: AdmittedDetectedWorktreeRefresh
purgeRemovedWorktrees?: boolean
@@ -1,3 +1,6 @@
import type { Worktree } from '../../../../../../shared/worktree/types'
import { branchName } from '@/lib/source-control/branches/branch-name'
export const detachedHeadAutoDerivedDisplayNames = new Map<string, string>()
export function setDetachedHeadAutoDerivedDisplayNameForTests(
@@ -16,3 +19,33 @@ export function getDetachedHeadAutoDerivedDisplayNameForTests(
export function forgetDetachedHeadAutoDerivedDisplayName(worktreeId: string): void {
detachedHeadAutoDerivedDisplayNames.delete(worktreeId)
}
/** Re-derive automatic titles on a branch/head patch the way a full listing would; records detach-time names. */
export function deriveGitIdentityDisplayName(
worktree: Worktree,
worktreeId: string,
nextBranch: string,
identityBranch: string | null | undefined
): string {
const currentBranchName = branchName(worktree.branch)
const wasAutoDerived =
worktree.displayNameMode === 'automatic' ||
(worktree.displayNameMode === undefined &&
worktree.cliProvenance?.kind !== 'created-by-cli' &&
worktree.displayName === currentBranchName)
const wasDetachedAutoDerived =
worktree.displayNameMode !== 'fixed' &&
worktree.branch === '' &&
nextBranch !== '' &&
detachedHeadAutoDerivedDisplayNames.get(worktreeId) === worktree.displayName
const nextDisplayName =
(wasAutoDerived || wasDetachedAutoDerived) && nextBranch
? branchName(nextBranch)
: worktree.displayName
if (identityBranch === null && wasAutoDerived) {
detachedHeadAutoDerivedDisplayNames.set(worktreeId, worktree.displayName)
} else if (identityBranch !== undefined) {
detachedHeadAutoDerivedDisplayNames.delete(worktreeId)
}
return nextDisplayName
}
@@ -4,8 +4,7 @@ import type { Worktree } from '../../../../../../shared/worktree/types'
import { normalizeWorkspaceAttachmentUpdate } from '../../../../../../shared/workspace-attachments/workspace-attachments'
import type { WorktreeSlice } from '../worktree-slice-contract'
import { getRepoIdFromWorktreeId } from '../../../../../../shared/worktree/id'
import { branchName } from '@/lib/source-control/branches/branch-name'
import { detachedHeadAutoDerivedDisplayNames } from './detached-head-display-name'
import { deriveGitIdentityDisplayName } from './detached-head-display-name'
import {
hostedReviewClearUpdates,
type HostedReviewClearUpdates
@@ -187,25 +186,12 @@ export function createUpdateWorktreeGitIdentity(
}
}
// Why: terminal branch switches only patch branch/head here; re-derive auto titles like full listing does.
const currentBranchName = branchName(worktree.branch)
const wasAutoDerived =
worktree.displayNameMode === 'automatic' ||
(worktree.displayNameMode === undefined &&
worktree.cliProvenance?.kind !== 'created-by-cli' &&
worktree.displayName === currentBranchName)
const wasDetachedAutoDerived =
worktree.branch === '' &&
nextBranch !== '' &&
detachedHeadAutoDerivedDisplayNames.get(worktreeId) === worktree.displayName
const nextDisplayName =
(wasAutoDerived || wasDetachedAutoDerived) && nextBranch
? branchName(nextBranch)
: worktree.displayName
if (identity.branch === null && wasAutoDerived) {
detachedHeadAutoDerivedDisplayNames.set(worktreeId, worktree.displayName)
} else if (identity.branch !== undefined) {
detachedHeadAutoDerivedDisplayNames.delete(worktreeId)
}
const nextDisplayName = deriveGitIdentityDisplayName(
worktree,
worktreeId,
nextBranch,
identity.branch
)
return {
...worktree,
head: nextHead,