diff --git a/src/main/ipc/watched-worktree-catalog-notification.ts b/src/main/ipc/watched-worktree-catalog-notification.ts index 20682591fc3..9ddf51520ab 100644 --- a/src/main/ipc/watched-worktree-catalog-notification.ts +++ b/src/main/ipc/watched-worktree-catalog-notification.ts @@ -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) { diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-change-collector.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-change-collector.ts index 7cd680bf626..59f17736ddf 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-change-collector.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-change-collector.ts @@ -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 gitStatusRepoIds: Set headIdentityRepoIds: Set + headMoveRepoIds: Set headIdentityScope: WorktreeHeadIdentityScope gitStatusScope: WorktreeHeadIdentityScope } @@ -40,6 +42,7 @@ function emptyBuckets(): ChangeBuckets { structureRepoIds: new Set(), gitStatusRepoIds: new Set(), headIdentityRepoIds: new Set(), + headMoveRepoIds: new Set(), 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 } diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.ts index 8088e0ced41..97d47b99b22 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-event-filter.ts @@ -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 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, + commonDir: string +): Promise { + 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): 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')) + }) +}) diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-notifications.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-notifications.ts index 47fa785b850..a52323c4172 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-notifications.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-notifications.ts @@ -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 pendingGitStatusRepoIds: Set pendingHeadIdentityRepoIds: Set + pendingHeadMoveRepoIds: Set 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) diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-watch-targets.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-watch-targets.ts index ca2414db2bc..ddb46ddc4a0 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-watch-targets.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-watch-targets.ts @@ -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. diff --git a/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts b/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts index 1677e017dbc..700fe09255f 100644 --- a/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts +++ b/src/main/ipc/worktrees/creation/worktree-base-directory-watcher.ts @@ -46,6 +46,7 @@ export function setWorktreeGitStatusRefWatch( function createActiveWatch( target: WorktreeBaseWatchTarget, mainWindow: BrowserWindow, + store: Store, subscription: ActiveWatch['subscription'], gitStatusRefPaths: Set ): 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 { let activeWatch: ActiveWatch | null = null const gitStatusRefPaths = new Set() @@ -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 { 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 } diff --git a/src/main/ipc/worktrees/creation/worktree-head-identity-reader.ts b/src/main/ipc/worktrees/creation/worktree-head-identity-reader.ts index 45e7eeca0ef..f79075f910d 100644 --- a/src/main/ipc/worktrees/creation/worktree-head-identity-reader.ts +++ b/src/main/ipc/worktrees/creation/worktree-head-identity-reader.ts @@ -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 } /** 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() 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 } } diff --git a/src/main/ipc/worktrees/creation/worktree-head-identity-refresh.ts b/src/main/ipc/worktrees/creation/worktree-head-identity-refresh.ts index c88ba1531a0..2c02a1c35c6 100644 --- a/src/main/ipc/worktrees/creation/worktree-head-identity-refresh.ts +++ b/src/main/ipc/worktrees/creation/worktree-head-identity-refresh.ts @@ -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; run: () => void } + export type WorktreeHeadIdentityRefreshState = { /** worktreePath → `${head} ${branch}` from the last metadata-file read. */ baseline: Map | 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 | 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 { 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 } | 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) diff --git a/src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts b/src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts index 035288f637b..8409ba8e343 100644 --- a/src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts +++ b/src/main/runtime/workspaces/catalog/external-worktree-paired-client-discovery.integration.test.ts @@ -190,9 +190,11 @@ describe('external worktree discovery for paired clients', () => { 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: () => false, disposed: false } vi.useFakeTimers() @@ -378,9 +380,11 @@ describe('external worktree discovery for paired clients', () => { 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: () => false, disposed: false } vi.useFakeTimers() @@ -465,9 +469,11 @@ describe('external worktree discovery for paired clients', () => { 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: () => false, disposed: false } vi.useFakeTimers() diff --git a/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts index 8981c5646f4..65a987d1186 100644 --- a/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/project-catalog-ipc-bridge.ts @@ -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 + ) }) ) } diff --git a/src/renderer/src/hooks/worktree-head-identity-apply.ts b/src/renderer/src/hooks/worktree-head-identity-apply.ts index 02e6b800b3e..386cfd78b98 100644 --- a/src/renderer/src/hooks/worktree-head-identity-apply.ts +++ b/src/renderer/src/hooks/worktree-head-identity-apply.ts @@ -11,7 +11,10 @@ export type WorktreeHeadIdentityApplyDeps = { ) => void } -function findWorktreeByPath(worktrees: Worktree[], worktreePath: string): Worktree | undefined { +export function findWorktreeByPath( + worktrees: readonly T[], + worktreePath: string +): T | undefined { const exact = worktrees.find((worktree) => worktree.path === worktreePath) if (exact) { return exact diff --git a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-head-identity.ts b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-head-identity.ts new file mode 100644 index 00000000000..f64e8302d1e --- /dev/null +++ b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-head-identity.ts @@ -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, + repoId: string, + identities: readonly WorktreeHeadIdentity[] +): Pick | 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 +} diff --git a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-host-merge.ts b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-host-merge.ts index 5ee6ed17b5e..c044fdc3f08 100644 --- a/src/renderer/src/store/slices/worktrees/listing/detected-worktree-host-merge.ts +++ b/src/renderer/src/store/slices/worktrees/listing/detected-worktree-host-merge.ts @@ -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 && diff --git a/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts b/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts index bbe2405acac..6cb9f416df0 100644 --- a/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts +++ b/src/renderer/src/store/slices/worktrees/listing/fetch-all-worktrees.ts @@ -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 diff --git a/src/renderer/src/store/slices/worktrees/listing/fetch-detected-worktrees.ts b/src/renderer/src/store/slices/worktrees/listing/fetch-detected-worktrees.ts index d884741e6cc..ec55c181a80 100644 --- a/src/renderer/src/store/slices/worktrees/listing/fetch-detected-worktrees.ts +++ b/src/renderer/src/store/slices/worktrees/listing/fetch-detected-worktrees.ts @@ -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( diff --git a/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts b/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts index 697e5491116..c66bcf4499b 100644 --- a/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts +++ b/src/renderer/src/store/slices/worktrees/listing/fetch-worktrees.ts @@ -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 }) diff --git a/src/renderer/src/store/slices/worktrees/listing/fetched-worktree-merge.ts b/src/renderer/src/store/slices/worktrees/listing/fetched-worktree-merge.ts index 07af938c4c6..dd37ba45472 100644 --- a/src/renderer/src/store/slices/worktrees/listing/fetched-worktree-merge.ts +++ b/src/renderer/src/store/slices/worktrees/listing/fetched-worktree-merge.ts @@ -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. diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts index 96d589ef5d3..cd246de3316 100644 --- a/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-slice-types.ts @@ -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 diff --git a/src/renderer/src/store/slices/worktrees/metadata/detached-head-display-name.ts b/src/renderer/src/store/slices/worktrees/metadata/detached-head-display-name.ts index db4016b4b6d..13a2496aafe 100644 --- a/src/renderer/src/store/slices/worktrees/metadata/detached-head-display-name.ts +++ b/src/renderer/src/store/slices/worktrees/metadata/detached-head-display-name.ts @@ -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() 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 +} diff --git a/src/renderer/src/store/slices/worktrees/metadata/worktree-git-identity-update.ts b/src/renderer/src/store/slices/worktrees/metadata/worktree-git-identity-update.ts index b4fcef76a21..d54b977bd8a 100644 --- a/src/renderer/src/store/slices/worktrees/metadata/worktree-git-identity-update.ts +++ b/src/renderer/src/store/slices/worktrees/metadata/worktree-git-identity-update.ts @@ -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,