Prevent index churn from refreshing worktrees (#8431)

* Prevent index churn from refreshing worktrees

* Cover IPC contract in worktree reliability gate

* Refresh background worktree heads without re-entering structural fanout

External commits, amends, and soft resets in non-active worktrees now reach
store rows through spawn-free Git metadata reads diffed in the watcher's
existing debounce, emitted only on real head moves. HEAD reflog appends become
status-only triggers, config.worktree becomes structural for sparse-flag
freshness, and the non-darwin poller gains a periodic ungated index re-stat
so in-place rewrites on coarse-mtime filesystems cannot be missed forever.

* Reject unsafe symref paths and validate object ids in the head reader

Ref content comes from repo files an attacker can craft. Backslash segments
traverse on Windows where join treats them as separators, and colons are
forbidden in Git ref names; both now fail isSafeRefName before any path is
built. Resolved values are additionally emitted only when they match a hex
SHA-1/SHA-256 object id, so no file content can leak through the identity
event even in principle.

---------

Co-authored-by: Brennan Benson <brennanbenson@Brennans-MacBook-Pro.local>
Co-authored-by: Brennan Benson <>
This commit is contained in:
Brennan Benson
2026-07-12 23:43:33 -07:00
committed by GitHub
co-authored by Brennan Benson Brennan Benson
parent 43e481b1c3
commit db9421dd3c
25 changed files with 1759 additions and 147 deletions
+144
View File
@@ -16,6 +16,150 @@
}
},
"gates": [
{
"id": "git-worktree.refresh-event-semantics",
"title": "Index-only Git metadata cannot trigger structural worktree refresh fanout",
"maturity": "experimental",
"protection": "partial",
"owner": "terminal-runtime",
"layer": "main-preload-renderer-contract",
"surfaces": [
"terminal input availability",
"worktree discovery",
"Source Control status refresh"
],
"platforms": [
"macos",
"linux",
"windows"
],
"providers": [
"local",
"ssh"
],
"coveredPlatforms": [
"macos"
],
"coveredProviders": [
"local",
"ssh"
],
"coverageNotes": "Local deterministic evidence covers git-common classification, desktop watcher debounce counts, non-overlapping poller semantics, macOS native-watch fallback, preload cleanup, and Source Control active-visible repo filtering. Linux/Windows are covered at the shared poller layer by forcing the non-darwin path; live platform runs remain gaps.",
"motivatingLinks": [
"https://github.com/stablyai/orca/pull/7086"
],
"invariant": "Index-only Git activity below the common Git directory must not emit worktrees:changed, invalidate worktree caches, or trigger fetchWorktrees fanout; structural add/remove/HEAD/gitdir/locked/config.worktree changes must still refresh worktrees and nudge Source Control; external head moves (commit, amend, reset) must reach background worktree rows through spawn-free metadata reads, never through structural fanout.",
"oracle": "Classify exact git-common paths as structural, status-only, or ignored; count notifications from debounced watcher events; force the Linux/Windows poll path to emit allowlisted leaf events, detect linked HEAD rewrites independent of entry-directory mtime, and surface in-place index rewrites via the backstop re-stat; diff head identities from metadata-file reads and notify only real head moves; assert Source Control subscribes to both structural and status-only signals with active-repo and visibility filters.",
"commands": [
"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktree-base-directory-event-filter.test.ts src/main/ipc/worktree-base-directory-watcher.test.ts src/main/ipc/worktree-base-directory-poller.test.ts src/main/ipc/worktree-head-identity-reader.test.ts src/renderer/src/hooks/worktree-head-identity-apply.test.ts src/renderer/src/components/right-sidebar/git-status-push-signal-refresh.test.ts src/renderer/src/hooks/useIpcEvents.test.ts"
],
"testFiles": [
"src/main/ipc/worktree-base-directory-event-filter.test.ts",
"src/main/ipc/worktree-base-directory-watcher.test.ts",
"src/main/ipc/worktree-base-directory-poller.test.ts",
"src/main/ipc/worktree-head-identity-reader.test.ts",
"src/renderer/src/hooks/worktree-head-identity-apply.test.ts",
"src/renderer/src/components/right-sidebar/git-status-push-signal-refresh.test.ts",
"src/renderer/src/hooks/useIpcEvents.test.ts"
],
"assertionRefs": [
{
"file": "src/main/ipc/worktree-base-directory-event-filter.test.ts",
"assertions": [
"primary HEAD and packed-refs classify as structural while primary index classifies as status-only",
"linked HEAD/gitdir/locked classify as structural while linked index classifies as status-only",
"HEAD reflog appends classify as status-only for linked and primary checkouts while per-ref reflogs stay ignored",
"config.worktree classifies as structural at both linked and primary levels",
"ignored common-dir churn, spaces, Windows separators, and outside-root paths do not match structurally"
]
},
{
"file": "src/main/ipc/worktree-base-directory-watcher.test.ts",
"assertions": [
"linked index bursts produce zero notifyWorktreesChanged calls and one debounced status-only notification",
"linked HEAD and locked metadata still produce a structural worktree notification",
"status-only head moves emit head identities without structural fanout and only when heads actually changed",
"structural notifications re-baseline head identities silently and SSH watches never read identities",
"SSH-shaped index renames are status-only while overflow remains conservatively structural"
]
},
{
"file": "src/main/ipc/worktree-base-directory-poller.test.ts",
"assertions": [
"non-darwin git-common polling emits entry create/delete and allowlisted HEAD/index leaf events",
"linked HEAD rewrites are detected even after restoring the entry-directory mtime",
"linked and primary HEAD reflog appends emit despite bumping no watched leaf or entry dir",
"in-place index rewrites surface through the periodic backstop re-stat",
"primary checkout HEAD changes and macOS narrow watch/fallback behavior still emit"
]
},
{
"file": "src/renderer/src/components/right-sidebar/git-status-push-signal-refresh.test.ts",
"assertions": [
"Source Control nudges only for the active visible repo on structural and status-only signals",
"preload subscriptions and terminal command-finished listeners are cleaned up"
]
},
{
"file": "src/main/ipc/worktree-head-identity-reader.test.ts",
"assertions": [
"loose-ref, packed-refs, detached, unborn, and relative-gitdir layouts resolve or skip without spawning Git",
"traversal-shaped or backslash/colon symrefs are rejected before any path join and only hex object ids are ever emitted"
]
},
{
"file": "src/renderer/src/hooks/worktree-head-identity-apply.test.ts",
"assertions": [
"head identities patch matching rows by path (including Windows separator/casing drift) and skip unknown rows"
]
},
{
"file": "src/renderer/src/hooks/useIpcEvents.test.ts",
"assertions": [
"renderer preload API fixtures include the status-metadata and head-identity subscription contracts"
]
}
],
"evidenceRuns": [
{
"date": "2026-07-12",
"runner": "local",
"platform": "macos",
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktree-base-directory-event-filter.test.ts src/main/ipc/worktree-base-directory-watcher.test.ts src/main/ipc/worktree-base-directory-poller.test.ts src/main/ipc/worktree-head-identity-reader.test.ts src/renderer/src/hooks/worktree-head-identity-apply.test.ts src/renderer/src/components/right-sidebar/git-status-push-signal-refresh.test.ts src/renderer/src/hooks/useIpcEvents.test.ts",
"result": "passed",
"durationSeconds": 3.12,
"summary": "7 files and 130 tests passed locally, adding head-identity emit-on-change without structural fanout, reflog status triggers, config.worktree structural classification, the in-place index backstop, and the spawn-free head reader with symref traversal rejection and hex-object-id output validation."
}
],
"runtimeBudget": {
"p95Seconds": 10,
"scope": "focused main/preload/renderer unit and polling tests"
},
"flakeHistory": {
"status": "unknown",
"evidence": "New experimental deterministic gate with one local macOS run; needs CI soak before promotion."
},
"redGreenEvidence": {
"status": "partial",
"evidence": "The watcher count assertions fail against the old single-signal classifier because linked index events call notifyWorktreesChanged. Saved CI red/green artifacts are still needed before blocking promotion."
},
"performanceBudget": {
"required": true,
"evidence": "Index-only bursts produce zero structural notifications, so renderer fetchWorktrees and detected-worktree cache invalidation are not reached. The non-darwin poller stays bounded and non-overlapping, compares HEAD/gitdir/locked signatures every tick, and gates linked index inspection behind the entry-directory signature. A 30-second live Electron run with 2,000 external linked-status calls delivered 50 ordered input chunks and recorded zero Orca-owned git worktree spawns across six diagnostic windows; a locked create/delete positive control still caused structural refreshes."
},
"promotionCriteria": [
"Run in soak for at least 100 consecutive passes or 14 days across required CI platforms.",
"Attach live Electron main-thread diagnostic evidence for repeated linked-worktree index rewrites while typing.",
"Add Linux/Windows live watcher evidence if shared poller-layer coverage diverges from platform behavior."
],
"knownGaps": [
"The live Electron diagnostic and screenshot evidence must remain attached to the motivating PR for durable review.",
"Linux and Windows are forced through the shared non-darwin poller in unit tests but are not live-tested here.",
"Git loose ref watching remains outside this incident fix by design.",
"SSH watches classify head-move triggers but skip the metadata-read identity diff; remote background-worktree heads still wait on a structural event or activation."
],
"demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if index-only churn can emit worktrees:changed, or if structural add/remove/HEAD/lock changes fail to converge."
},
{
"id": "editor.live-log-append-stability",
"title": "Long live session logs retain their Monaco viewport while appending",
+4 -1
View File
@@ -115,7 +115,10 @@ describe('registerSettingsHandlers', () => {
registerSettingsHandlers(store as never)
const handler = handleMock.mock.calls.find(
(call) => call[0] === 'settings:update-pr-bot-author-override'
)?.[1] as (event: typeof settingsInvokeEvent, args: { author: string; isBot: boolean }) => unknown
)?.[1] as (
event: typeof settingsInvokeEvent,
args: { author: string; isBot: boolean }
) => unknown
const result = handler(settingsInvokeEvent, { author: ' Bob ', isBot: true })
@@ -0,0 +1,95 @@
import type { FsChangeEvent } from '../../shared/types'
import {
classifyWorktreeBaseChange,
type WorktreeBaseWatchTarget
} from './worktree-base-directory-event-filter'
type WorktreeBaseWatcherEvent = {
type: 'create' | 'update' | 'delete'
path: string
}
export type WorktreeBaseCollectedChanges = {
overflow: boolean
structureRepoIds: string[]
gitStatusRepoIds: string[]
}
function emptyChanges(): WorktreeBaseCollectedChanges {
return { overflow: false, structureRepoIds: [], gitStatusRepoIds: [] }
}
function addMatchingChange(
target: WorktreeBaseWatchTarget,
event: WorktreeBaseWatcherEvent,
structureRepoIds: Set<string>,
gitStatusRepoIds: Set<string>
): void {
const change = classifyWorktreeBaseChange(target, event)
for (const repoId of change.structureRepoIds) {
structureRepoIds.add(repoId)
}
for (const repoId of change.gitStatusRepoIds) {
gitStatusRepoIds.add(repoId)
}
}
function toCollectedChanges(
structureRepoIds: Set<string>,
gitStatusRepoIds: Set<string>
): WorktreeBaseCollectedChanges {
return {
overflow: false,
structureRepoIds: [...structureRepoIds],
gitStatusRepoIds: [...gitStatusRepoIds]
}
}
export function collectLocalWorktreeBaseChanges(
target: WorktreeBaseWatchTarget,
events: WorktreeBaseWatcherEvent[]
): WorktreeBaseCollectedChanges {
const structureRepoIds = new Set<string>()
const gitStatusRepoIds = new Set<string>()
for (const event of events) {
addMatchingChange(target, event, structureRepoIds, gitStatusRepoIds)
}
return toCollectedChanges(structureRepoIds, gitStatusRepoIds)
}
export function collectRemoteWorktreeBaseChanges(
target: WorktreeBaseWatchTarget,
events: FsChangeEvent[]
): WorktreeBaseCollectedChanges {
const structureRepoIds = new Set<string>()
const gitStatusRepoIds = new Set<string>()
for (const event of events) {
if (event.kind === 'overflow') {
return { ...emptyChanges(), overflow: true }
}
if (event.kind === 'rename') {
if (event.oldAbsolutePath) {
addMatchingChange(
target,
{ type: 'delete', path: event.oldAbsolutePath },
structureRepoIds,
gitStatusRepoIds
)
}
addMatchingChange(
target,
{ type: 'create', path: event.absolutePath },
structureRepoIds,
gitStatusRepoIds
)
continue
}
addMatchingChange(
target,
{ type: event.kind, path: event.absolutePath },
structureRepoIds,
gitStatusRepoIds
)
}
return toCollectedChanges(structureRepoIds, gitStatusRepoIds)
}
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest'
import { join } from 'node:path'
import { join, win32 } from 'node:path'
import {
classifyWorktreeBaseChange,
matchingWorktreeBaseRepoIds,
type WorktreeBaseWatchTarget
} from './worktree-base-directory-event-filter'
@@ -17,29 +18,121 @@ function makeGitCommonTarget(): WorktreeBaseWatchTarget {
}
describe('matchingWorktreeBaseRepoIds (git-common)', () => {
it('matches linked-worktree metadata under worktrees/', () => {
it('classifies linked-worktree structural metadata under worktrees/', () => {
const target = makeGitCommonTarget()
expect(
matchingWorktreeBaseRepoIds(target, {
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'worktrees', 'wt-a', 'HEAD')
})
).toEqual(['repo-1'])
).toEqual({ structureRepoIds: ['repo-1'], gitStatusRepoIds: [] })
expect(
classifyWorktreeBaseChange(target, {
type: 'create',
path: join(COMMON_DIR, 'worktrees', 'wt-b')
})
).toEqual({ structureRepoIds: ['repo-1'], gitStatusRepoIds: [] })
expect(
matchingWorktreeBaseRepoIds(target, {
type: 'create',
type: 'delete',
path: join(COMMON_DIR, 'worktrees', 'wt-b')
})
).toEqual(['repo-1'])
})
it('matches primary-checkout branch/index metadata at the common-dir top level', () => {
it('classifies primary-checkout branch metadata as structural and index as status-only', () => {
const target = makeGitCommonTarget()
for (const file of ['HEAD', 'packed-refs', 'index']) {
for (const file of ['HEAD', 'packed-refs']) {
expect(
matchingWorktreeBaseRepoIds(target, { type: 'update', path: join(COMMON_DIR, file) })
).toEqual(['repo-1'])
classifyWorktreeBaseChange(target, { type: 'update', path: join(COMMON_DIR, file) })
).toEqual({ structureRepoIds: ['repo-1'], gitStatusRepoIds: [] })
}
expect(
classifyWorktreeBaseChange(target, { type: 'update', path: join(COMMON_DIR, 'index') })
).toEqual({ structureRepoIds: [], gitStatusRepoIds: ['repo-1'] })
})
it('classifies linked-worktree index as status-only', () => {
const target = makeGitCommonTarget()
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'worktrees', 'wt-a', 'index')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: ['repo-1'] })
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'worktrees', 'wt-a', 'index.lock')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: [] })
})
it('classifies HEAD reflog appends as status-only for linked and primary checkouts', () => {
const target = makeGitCommonTarget()
// commit --amend / reset --soft move HEAD without touching index or HEAD.
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'worktrees', 'wt-a', 'logs', 'HEAD')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: ['repo-1'] })
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'logs', 'HEAD')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: ['repo-1'] })
// Per-ref reflogs churn on fetches and stay ignored.
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'logs', 'refs', 'heads', 'main')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: [] })
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'worktrees', 'wt-a', 'logs', 'refs', 'heads', 'main')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: [] })
})
it('classifies worktree-scoped config as structural for sparse-flag freshness', () => {
const target = makeGitCommonTarget()
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: join(COMMON_DIR, 'worktrees', 'wt-a', 'config.worktree')
})
).toEqual({ structureRepoIds: ['repo-1'], gitStatusRepoIds: [] })
expect(
classifyWorktreeBaseChange(target, {
type: 'create',
path: join(COMMON_DIR, 'config.worktree')
})
).toEqual({ structureRepoIds: ['repo-1'], gitStatusRepoIds: [] })
})
it('classifies Windows-shaped linked metadata paths', () => {
const commonDir = win32.join('C:\\', 'repos', 'project', '.git')
const target: WorktreeBaseWatchTarget = {
...makeGitCommonTarget(),
key: `git-common:local:${commonDir}`,
path: commonDir
}
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: win32.join(commonDir, 'worktrees', 'wt a', 'gitdir')
})
).toEqual({ structureRepoIds: ['repo-1'], gitStatusRepoIds: [] })
expect(
classifyWorktreeBaseChange(target, {
type: 'update',
path: win32.join(commonDir, 'worktrees', 'wt a', 'index')
})
).toEqual({ structureRepoIds: [], gitStatusRepoIds: ['repo-1'] })
})
it('ignores non-status common-dir churn', () => {
@@ -8,6 +8,11 @@ type WorktreeBaseWatcherEvent = {
path: string
}
export type WorktreeBaseChangeClass = {
structureRepoIds: string[]
gitStatusRepoIds: string[]
}
export type WorktreeBaseWatchKind = 'base' | 'git-common'
export type WorktreeBaseRepoWatchConfig = {
@@ -85,29 +90,95 @@ function matchingBaseRepoIds(
// Why: branch switches and commits in the primary checkout rewrite these
// top-level common-dir files; matching them keeps root-checkout branch/status
// as fresh as linked worktrees. Deeper churn (objects, refs, logs) is ignored.
const GIT_COMMON_PRIMARY_METADATA_FILES = new Set(['HEAD', 'packed-refs', 'index'])
// `config.worktree` is structural because it is the only file whose write
// flips `git worktree list`'s sparse flag, and no status/commit path touches
// it — so it cannot re-open the index-churn fanout this classifier closes.
const GIT_COMMON_PRIMARY_STRUCTURAL_FILES = new Set(['HEAD', 'packed-refs', 'config.worktree'])
const GIT_COMMON_PRIMARY_STATUS_FILES = new Set(['index'])
const GIT_COMMON_LINKED_STRUCTURAL_FILES = new Set(['HEAD', 'gitdir', 'locked', 'config.worktree'])
const GIT_COMMON_LINKED_STATUS_FILES = new Set(['index'])
// `logs/HEAD` is the status-only trigger for head moves that rewrite no
// watched leaf (commit --amend, reset --soft): every ref update through a
// checkout appends there, while `git status` churn never touches it.
function isHeadLogParts(parts: string[], offset: number): boolean {
return parts.length === offset + 2 && parts[offset] === 'logs' && parts[offset + 1] === 'HEAD'
}
function allRepoIds(target: WorktreeBaseWatchTarget): string[] {
return [...target.repos.keys()]
}
// Why: Git records linked worktrees under the common dir's `worktrees`
// metadata, which is lower churn than watching checkout contents.
function matchingGitCommonRepoIds(target: WorktreeBaseWatchTarget, eventPath: string): string[] {
const parts = pathRelativeToWorktreeWatchRoot(target.path, eventPath)
function classifyGitCommonEvent(
target: WorktreeBaseWatchTarget,
event: WorktreeBaseWatcherEvent
): WorktreeBaseChangeClass {
const parts = pathRelativeToWorktreeWatchRoot(target.path, event.path)
if (!parts) {
return []
return { structureRepoIds: [], gitStatusRepoIds: [] }
}
if (
parts[0] !== 'worktrees' &&
!(parts.length === 1 && GIT_COMMON_PRIMARY_METADATA_FILES.has(parts[0]))
) {
return []
const repoIds = allRepoIds(target)
if (parts.length === 1) {
if (parts[0] === 'worktrees') {
return { structureRepoIds: repoIds, gitStatusRepoIds: [] }
}
if (GIT_COMMON_PRIMARY_STRUCTURAL_FILES.has(parts[0])) {
return { structureRepoIds: repoIds, gitStatusRepoIds: [] }
}
if (GIT_COMMON_PRIMARY_STATUS_FILES.has(parts[0])) {
return { structureRepoIds: [], gitStatusRepoIds: repoIds }
}
return { structureRepoIds: [], gitStatusRepoIds: [] }
}
return [...target.repos.keys()]
if (parts[0] !== 'worktrees') {
if (isHeadLogParts(parts, 0)) {
return { structureRepoIds: [], gitStatusRepoIds: repoIds }
}
return { structureRepoIds: [], gitStatusRepoIds: [] }
}
if (parts.length === 2) {
return event.type === 'update'
? { structureRepoIds: [], gitStatusRepoIds: [] }
: { structureRepoIds: repoIds, gitStatusRepoIds: [] }
}
if (parts.length === 3) {
if (GIT_COMMON_LINKED_STRUCTURAL_FILES.has(parts[2])) {
return { structureRepoIds: repoIds, gitStatusRepoIds: [] }
}
if (GIT_COMMON_LINKED_STATUS_FILES.has(parts[2])) {
return { structureRepoIds: [], gitStatusRepoIds: repoIds }
}
}
if (isHeadLogParts(parts, 2)) {
return { structureRepoIds: [], gitStatusRepoIds: repoIds }
}
return { structureRepoIds: [], gitStatusRepoIds: [] }
}
function classifyBaseEvent(
target: WorktreeBaseWatchTarget,
event: WorktreeBaseWatcherEvent
): WorktreeBaseChangeClass {
return {
structureRepoIds: matchingBaseRepoIds(target, event.path, event.type),
gitStatusRepoIds: []
}
}
export function classifyWorktreeBaseChange(
target: WorktreeBaseWatchTarget,
event: WorktreeBaseWatcherEvent
): WorktreeBaseChangeClass {
return target.kind === 'git-common'
? classifyGitCommonEvent(target, event)
: classifyBaseEvent(target, event)
}
export function matchingWorktreeBaseRepoIds(
target: WorktreeBaseWatchTarget,
event: WorktreeBaseWatcherEvent
): string[] {
return target.kind === 'git-common'
? matchingGitCommonRepoIds(target, event.path)
: matchingBaseRepoIds(target, event.path, event.type)
return classifyWorktreeBaseChange(target, event).structureRepoIds
}
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdtemp, mkdir, realpath, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, mkdir, realpath, rm, stat, utimes, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import {
@@ -171,7 +171,7 @@ describe('worktree base directory poller', () => {
expect(fullScans.length).toBeGreaterThan(0)
})
it('reports git-common worktrees metadata adds, updates, and removals via polling', async () => {
it('reports git-common entry creates, allowlisted leaf updates, and removals via polling', async () => {
const commonDir = await makeRoot()
const received: WorktreeBasePollEvent[][] = []
const target = makeTarget('git-common', commonDir)
@@ -190,12 +190,16 @@ describe('worktree base directory poller', () => {
flat.some((event) => event.type === 'create' && event.path === entry)
)
// HEAD/gitdir metadata writes land as new files in the entry dir, which
// bumps the entry dir mtime the poller compares.
await new Promise((resolve) => setTimeout(resolve, 10))
await writeFile(join(entry, 'HEAD'), 'ref: refs/heads/main')
await waitForEvents(received, (flat) =>
flat.some((event) => event.type === 'update' && event.path === entry)
flat.some((event) => event.type === 'create' && event.path === join(entry, 'HEAD'))
)
await new Promise((resolve) => setTimeout(resolve, 10))
await writeFile(join(entry, 'index'), 'status')
await waitForEvents(received, (flat) =>
flat.some((event) => event.type === 'create' && event.path === join(entry, 'index'))
)
await rm(entry, { recursive: true })
@@ -204,6 +208,106 @@ describe('worktree base directory poller', () => {
)
})
it('detects linked HEAD rewrites even when the entry directory mtime is restored', async () => {
const commonDir = await makeRoot()
const entry = join(commonDir, 'worktrees', 'external-head')
await mkdir(entry, { recursive: true })
await writeFile(join(entry, 'HEAD'), 'ref: refs/heads/main')
const received: WorktreeBasePollEvent[][] = []
const target = makeTarget('git-common', commonDir)
const poller = await startWorktreeBaseDirectoryPoller(
target,
() => target.repos,
(events) => received.push(events),
{ pollIntervalMs: POLL_MS, platform: 'linux' }
)
cleanups.push(() => poller.unsubscribe())
const before = await stat(entry)
await new Promise((resolve) => setTimeout(resolve, 10))
await writeFile(join(entry, 'HEAD'), 'ref: refs/heads/next')
await utimes(entry, before.atime, before.mtime)
await waitForEvents(received, (flat) =>
flat.some((event) => event.type === 'update' && event.path === join(entry, 'HEAD'))
)
})
it('reports linked HEAD reflog appends that bump no watched leaf or entry dir', async () => {
const commonDir = await makeRoot()
const entry = join(commonDir, 'worktrees', 'external-amend')
await mkdir(join(entry, 'logs'), { recursive: true })
await writeFile(join(entry, 'logs', 'HEAD'), 'baseline\n')
const received: WorktreeBasePollEvent[][] = []
const target = makeTarget('git-common', commonDir)
const poller = await startWorktreeBaseDirectoryPoller(
target,
() => target.repos,
(events) => received.push(events),
{ pollIntervalMs: POLL_MS, platform: 'linux' }
)
cleanups.push(() => poller.unsubscribe())
// commit --amend appends to the reflog inside logs/ — the entry dir mtime
// never moves, so the leaf must be stat'd directly.
await new Promise((resolve) => setTimeout(resolve, 10))
await writeFile(join(entry, 'logs', 'HEAD'), 'baseline\namended\n')
await waitForEvents(received, (flat) =>
flat.some((event) => event.type === 'update' && event.path === join(entry, 'logs', 'HEAD'))
)
})
it('surfaces in-place index rewrites through the backstop re-stat', async () => {
const commonDir = await makeRoot()
const entry = join(commonDir, 'worktrees', 'external-inplace')
await mkdir(entry, { recursive: true })
await writeFile(join(entry, 'index'), 'index-v1')
const received: WorktreeBasePollEvent[][] = []
const target = makeTarget('git-common', commonDir)
const poller = await startWorktreeBaseDirectoryPoller(
target,
() => target.repos,
(events) => received.push(events),
{ pollIntervalMs: POLL_MS, platform: 'linux' }
)
cleanups.push(() => poller.unsubscribe())
// An in-place rewrite leaves the entry-dir signature untouched, so only
// the periodic ungated re-stat can observe it.
await new Promise((resolve) => setTimeout(resolve, 10))
await writeFile(join(entry, 'index'), 'index-v2-longer')
await waitForEvents(received, (flat) =>
flat.some((event) => event.type === 'update' && event.path === join(entry, 'index'))
)
})
it('reports primary-checkout HEAD reflog appends via polling', async () => {
const commonDir = await makeRoot()
await mkdir(join(commonDir, 'logs'), { recursive: true })
await writeFile(join(commonDir, 'logs', 'HEAD'), 'baseline\n')
const received: WorktreeBasePollEvent[][] = []
const target = makeTarget('git-common', commonDir)
const poller = await startWorktreeBaseDirectoryPoller(
target,
() => target.repos,
(events) => received.push(events),
{ pollIntervalMs: POLL_MS, platform: 'linux' }
)
cleanups.push(() => poller.unsubscribe())
await new Promise((resolve) => setTimeout(resolve, 10))
await writeFile(join(commonDir, 'logs', 'HEAD'), 'baseline\namended\n')
await waitForEvents(received, (flat) =>
flat.some(
(event) => event.type === 'update' && event.path === join(commonDir, 'logs', 'HEAD')
)
)
})
it('reports primary-checkout HEAD changes via polling', async () => {
const commonDir = await makeRoot()
const received: WorktreeBasePollEvent[][] = []
@@ -14,6 +14,8 @@ vi.mock('./worktree-base-directory-poller', () => ({
}))
vi.mock('./worktree-remote', () => ({
notifyWorktreeGitStatusMetadataChanged: vi.fn(),
notifyWorktreeHeadIdentitiesChanged: vi.fn(),
notifyWorktreesChanged: vi.fn()
}))
@@ -21,8 +23,17 @@ vi.mock('../providers/ssh-filesystem-dispatch', () => ({
getSshFilesystemProvider: vi.fn()
}))
vi.mock('./worktree-head-identity-reader', () => ({
readGitCommonHeadIdentities: vi.fn(async () => [])
}))
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { notifyWorktreesChanged } from './worktree-remote'
import {
notifyWorktreeGitStatusMetadataChanged,
notifyWorktreeHeadIdentitiesChanged,
notifyWorktreesChanged
} from './worktree-remote'
import { readGitCommonHeadIdentities } from './worktree-head-identity-reader'
import { startWorktreeBaseDirectoryPoller } from './worktree-base-directory-poller'
import {
disposeWorktreeBaseDirectoryWatchers,
@@ -83,6 +94,7 @@ describe('worktree base directory watcher', () => {
watcherCallbacks.clear()
unsubscribeMocks.clear()
vi.mocked(getSshFilesystemProvider).mockReturnValue(undefined)
vi.mocked(readGitCommonHeadIdentities).mockResolvedValue([])
vi.mocked(startWorktreeBaseDirectoryPoller).mockImplementation(
async (target, _getRepos, onEvents) => {
const unsubscribe = vi.fn(async () => {})
@@ -151,6 +163,140 @@ describe('worktree base directory watcher', () => {
expect(notifyWorktreesChanged).toHaveBeenCalledWith(expect.anything(), 'repo-1')
})
it('debounces linked index bursts as status-only without structural notification', async () => {
await syncWorktreeBaseDirectoryWatchers(makeStore([makeRepo()]) as never, makeWindow() as never)
emit(PROJECT_GIT_COMMON_DIR, [
{ type: 'create', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'index') },
{ type: 'update', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'index') },
{ type: 'delete', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'index') }
])
await vi.advanceTimersByTimeAsync(300)
expect(notifyWorktreesChanged).not.toHaveBeenCalled()
expect(notifyWorktreeGitStatusMetadataChanged).toHaveBeenCalledTimes(1)
expect(notifyWorktreeGitStatusMetadataChanged).toHaveBeenCalledWith(expect.anything(), 'repo-1')
})
it('keeps linked HEAD and lock metadata structural', async () => {
await syncWorktreeBaseDirectoryWatchers(makeStore([makeRepo()]) as never, makeWindow() as never)
emit(PROJECT_GIT_COMMON_DIR, [
{ type: 'update', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'HEAD') },
{ type: 'create', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'locked') }
])
await vi.advanceTimersByTimeAsync(300)
expect(notifyWorktreesChanged).toHaveBeenCalledTimes(1)
expect(notifyWorktreesChanged).toHaveBeenCalledWith(expect.anything(), 'repo-1')
expect(notifyWorktreeGitStatusMetadataChanged).not.toHaveBeenCalled()
})
it('emits head identities for status-only head moves without structural fanout', async () => {
const linkedWorktree = absolutePath('workspace', 'worktrees', 'project', 'external-5104')
vi.mocked(readGitCommonHeadIdentities).mockResolvedValue([
{ worktreePath: linkedWorktree, head: 'aaa111', branch: 'refs/heads/feature' }
])
await syncWorktreeBaseDirectoryWatchers(makeStore([makeRepo()]) as never, makeWindow() as never)
await vi.advanceTimersByTimeAsync(0)
// External commit --amend: only logs/HEAD moves, no index write.
vi.mocked(readGitCommonHeadIdentities).mockResolvedValue([
{ worktreePath: linkedWorktree, head: 'bbb222', branch: 'refs/heads/feature' }
])
emit(PROJECT_GIT_COMMON_DIR, [
{
type: 'update',
path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'logs', 'HEAD')
}
])
await vi.advanceTimersByTimeAsync(300)
await vi.advanceTimersByTimeAsync(0)
expect(notifyWorktreesChanged).not.toHaveBeenCalled()
expect(notifyWorktreeGitStatusMetadataChanged).toHaveBeenCalledTimes(1)
expect(notifyWorktreeHeadIdentitiesChanged).toHaveBeenCalledTimes(1)
expect(notifyWorktreeHeadIdentitiesChanged).toHaveBeenCalledWith(expect.anything(), 'repo-1', [
{ worktreePath: linkedWorktree, head: 'bbb222', branch: 'refs/heads/feature' }
])
})
it('does not emit head identities when a status-only burst leaves heads unchanged', async () => {
const linkedWorktree = absolutePath('workspace', 'worktrees', 'project', 'external-5104')
vi.mocked(readGitCommonHeadIdentities).mockResolvedValue([
{ worktreePath: linkedWorktree, head: 'aaa111', branch: 'refs/heads/feature' }
])
await syncWorktreeBaseDirectoryWatchers(makeStore([makeRepo()]) as never, makeWindow() as never)
await vi.advanceTimersByTimeAsync(0)
emit(PROJECT_GIT_COMMON_DIR, [
{ type: 'update', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'index') }
])
await vi.advanceTimersByTimeAsync(300)
await vi.advanceTimersByTimeAsync(0)
expect(notifyWorktreeGitStatusMetadataChanged).toHaveBeenCalledTimes(1)
expect(notifyWorktreeHeadIdentitiesChanged).not.toHaveBeenCalled()
})
it('re-baselines head identities silently on structural notifications', async () => {
const linkedWorktree = absolutePath('workspace', 'worktrees', 'project', 'external-5104')
vi.mocked(readGitCommonHeadIdentities).mockResolvedValue([
{ worktreePath: linkedWorktree, head: 'aaa111', branch: 'refs/heads/feature' }
])
await syncWorktreeBaseDirectoryWatchers(makeStore([makeRepo()]) as never, makeWindow() as never)
await vi.advanceTimersByTimeAsync(0)
// Branch switch: structural path owns the refresh via the full listing.
vi.mocked(readGitCommonHeadIdentities).mockResolvedValue([
{ worktreePath: linkedWorktree, head: 'ccc333', branch: 'refs/heads/other' }
])
emit(PROJECT_GIT_COMMON_DIR, [
{ type: 'update', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'HEAD') }
])
await vi.advanceTimersByTimeAsync(300)
await vi.advanceTimersByTimeAsync(0)
expect(notifyWorktreeHeadIdentitiesChanged).not.toHaveBeenCalled()
// A later status-only event diffs against the re-baselined heads.
emit(PROJECT_GIT_COMMON_DIR, [
{ type: 'update', path: join(PROJECT_GIT_COMMON_DIR, 'worktrees', 'external-5104', 'index') }
])
await vi.advanceTimersByTimeAsync(300)
await vi.advanceTimersByTimeAsync(0)
expect(notifyWorktreeHeadIdentitiesChanged).not.toHaveBeenCalled()
})
it('never reads head identities for SSH watches', async () => {
const remoteCallbacks = new Map<string, (events: never[]) => void>()
const remoteWatch = vi.fn(async (root: string, callback: (events: never[]) => void) => {
remoteCallbacks.set(root, callback)
return vi.fn()
})
vi.mocked(getSshFilesystemProvider).mockReturnValue({
stat: vi.fn(async () => ({ type: 'directory', size: 0, mtime: 0 })),
realpath: vi.fn(async (path: string) => path),
readFile: vi.fn(async () => ({ content: '', isBinary: false })),
watch: remoteWatch
} as never)
await syncWorktreeBaseDirectoryWatchers(
makeStore([makeRepo({ connectionId: 'ssh-1', path: '/home/alice/project' })]) as never,
makeWindow() as never
)
remoteCallbacks.get('/home/alice/project/.git')?.([
{
kind: 'update',
absolutePath: '/home/alice/project/.git/worktrees/wt/logs/HEAD'
}
] as never[])
await vi.advanceTimersByTimeAsync(300)
expect(notifyWorktreeGitStatusMetadataChanged).toHaveBeenCalledTimes(1)
expect(readGitCommonHeadIdentities).not.toHaveBeenCalled()
expect(notifyWorktreeHeadIdentitiesChanged).not.toHaveBeenCalled()
})
it('does not install local desktop watchers for runtime or folder repos', async () => {
await syncWorktreeBaseDirectoryWatchers(
makeStore([
@@ -197,6 +343,42 @@ describe('worktree base directory watcher', () => {
expect(remoteUnwatch).toHaveBeenCalled()
})
it('treats remote index renames as status-only and overflow as structural', async () => {
const remoteCallbacks = new Map<string, (events: never[]) => void>()
const remoteWatch = vi.fn(async (root: string, callback: (events: never[]) => void) => {
remoteCallbacks.set(root, callback)
return vi.fn()
})
vi.mocked(getSshFilesystemProvider).mockReturnValue({
stat: vi.fn(async () => ({ type: 'directory', size: 0, mtime: 0 })),
realpath: vi.fn(async (path: string) => path),
readFile: vi.fn(async () => ({ content: '', isBinary: false })),
watch: remoteWatch
} as never)
await syncWorktreeBaseDirectoryWatchers(
makeStore([makeRepo({ connectionId: 'ssh-1', path: '/home/alice/project' })]) as never,
makeWindow() as never
)
remoteCallbacks.get('/home/alice/project/.git')?.([
{
kind: 'rename',
oldAbsolutePath: '/home/alice/project/.git/worktrees/wt/index.lock',
absolutePath: '/home/alice/project/.git/worktrees/wt/index'
}
] as never[])
await vi.advanceTimersByTimeAsync(300)
expect(notifyWorktreesChanged).not.toHaveBeenCalled()
expect(notifyWorktreeGitStatusMetadataChanged).toHaveBeenCalledTimes(1)
vi.mocked(notifyWorktreeGitStatusMetadataChanged).mockClear()
remoteCallbacks.get('/home/alice/project/.git')?.([{ kind: 'overflow' }] as never[])
await vi.advanceTimersByTimeAsync(300)
expect(notifyWorktreesChanged).toHaveBeenCalledWith(expect.anything(), 'repo-1')
expect(notifyWorktreeGitStatusMetadataChanged).not.toHaveBeenCalled()
})
it('unsubscribes roots that disappear after repo settings change', async () => {
const repo = makeRepo()
const store = makeStore([repo])
+83 -49
View File
@@ -1,12 +1,18 @@
import type { BrowserWindow } from 'electron'
import type { FsChangeEvent } from '../../shared/types'
import type { Store } from '../persistence'
import { notifyWorktreesChanged } from './worktree-remote'
import { notifyWorktreeGitStatusMetadataChanged, notifyWorktreesChanged } from './worktree-remote'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import {
matchingWorktreeBaseRepoIds,
type WorktreeBaseWatchTarget
} from './worktree-base-directory-event-filter'
createWorktreeHeadIdentityRefreshState,
refreshWorktreeHeadIdentities,
type WorktreeHeadIdentityRefreshState
} from './worktree-head-identity-refresh'
import {
collectLocalWorktreeBaseChanges,
collectRemoteWorktreeBaseChanges,
type WorktreeBaseCollectedChanges
} from './worktree-base-directory-change-collector'
import type { WorktreeBaseWatchTarget } from './worktree-base-directory-event-filter'
import {
buildWorktreeBaseDirectoryWatchTargets,
clearWorktreeBaseDirectoryWatchTargetWarnings
@@ -17,7 +23,9 @@ type ActiveWatch = WorktreeBaseWatchTarget & {
mainWindow: BrowserWindow
subscription: { unsubscribe: () => Promise<void> }
notifyTimer: ReturnType<typeof setTimeout> | null
pendingRepoIds: Set<string>
pendingStructureRepoIds: Set<string>
pendingGitStatusRepoIds: Set<string>
headIdentityRefresh: WorktreeHeadIdentityRefreshState
disposed: boolean
}
@@ -27,13 +35,20 @@ let syncGeneration = 0
let scheduledSync: ReturnType<typeof setTimeout> | null = null
let latestSyncContext: { mainWindow: BrowserWindow; store: Store } | null = null
function scheduleNotification(watch: ActiveWatch, repoIds: readonly string[]): void {
function scheduleNotification(
watch: ActiveWatch,
changes: { structureRepoIds?: readonly string[]; gitStatusRepoIds?: readonly string[] }
): void {
if (watch.disposed || watch.mainWindow.isDestroyed()) {
watch.pendingRepoIds.clear()
watch.pendingStructureRepoIds.clear()
watch.pendingGitStatusRepoIds.clear()
return
}
for (const repoId of repoIds) {
watch.pendingRepoIds.add(repoId)
for (const repoId of changes.structureRepoIds ?? []) {
watch.pendingStructureRepoIds.add(repoId)
}
for (const repoId of changes.gitStatusRepoIds ?? []) {
watch.pendingGitStatusRepoIds.add(repoId)
}
if (watch.notifyTimer) {
clearTimeout(watch.notifyTimer)
@@ -41,26 +56,43 @@ function scheduleNotification(watch: ActiveWatch, repoIds: readonly string[]): v
watch.notifyTimer = setTimeout(() => {
watch.notifyTimer = null
if (watch.disposed || watch.mainWindow.isDestroyed()) {
watch.pendingRepoIds.clear()
watch.pendingStructureRepoIds.clear()
watch.pendingGitStatusRepoIds.clear()
return
}
const pending = [...watch.pendingRepoIds]
watch.pendingRepoIds.clear()
for (const repoId of pending) {
const pendingStructure = [...watch.pendingStructureRepoIds]
const pendingGitStatus = [...watch.pendingGitStatusRepoIds].filter(
(repoId) => !watch.pendingStructureRepoIds.has(repoId)
)
watch.pendingStructureRepoIds.clear()
watch.pendingGitStatusRepoIds.clear()
for (const repoId of pendingStructure) {
notifyWorktreesChanged(watch.mainWindow, repoId)
}
for (const repoId of pendingGitStatus) {
notifyWorktreeGitStatusMetadataChanged(watch.mainWindow, repoId)
}
if (supportsHeadIdentityRefresh(watch)) {
// Emit only when no structural notification fired this tick: structural
// paths already run the authoritative worktree listing; the silent pass
// just re-baselines so later status-only diffs stay accurate.
void refreshWorktreeHeadIdentities(
watch,
watch.headIdentityRefresh,
pendingStructure.length === 0
)
}
}, WATCH_DEBOUNCE_MS)
}
function collectMatchingRepoIds(
watch: ActiveWatch,
eventType: 'create' | 'update' | 'delete',
eventPath: string,
repoIds: Set<string>
): void {
for (const repoId of matchingWorktreeBaseRepoIds(watch, { type: eventType, path: eventPath })) {
repoIds.add(repoId)
}
// Why: SSH common dirs would need per-signal network reads to diff heads;
// remote background freshness stays on the structural path for now.
function supportsHeadIdentityRefresh(watch: ActiveWatch): boolean {
return watch.kind === 'git-common' && !watch.connectionId
}
function hasCollectedChanges(changes: WorktreeBaseCollectedChanges): boolean {
return changes.structureRepoIds.length > 0 || changes.gitStatusRepoIds.length > 0
}
function handleLocalWatchEvents(
@@ -73,39 +105,29 @@ function handleLocalWatchEvents(
}
if (error) {
console.warn(`[worktree-base-watcher] watcher failed for ${watch.path}:`, error)
scheduleNotification(watch, [...watch.repos.keys()])
scheduleNotification(watch, { structureRepoIds: [...watch.repos.keys()] })
return
}
const repoIds = new Set<string>()
for (const event of events) {
collectMatchingRepoIds(watch, event.type, event.path, repoIds)
}
if (repoIds.size > 0) {
scheduleNotification(watch, [...repoIds])
const changes = collectLocalWorktreeBaseChanges(watch, events)
if (hasCollectedChanges(changes)) {
scheduleNotification(watch, changes)
}
}
function handleRemoteWatchEvents(watch: ActiveWatch, events: FsChangeEvent[]): void {
function handleRemoteWatchEvents(
watch: ActiveWatch,
events: Parameters<typeof collectRemoteWorktreeBaseChanges>[1]
): void {
if (watch.disposed || watch.mainWindow.isDestroyed()) {
return
}
const repoIds = new Set<string>()
for (const event of events) {
if (event.kind === 'overflow') {
scheduleNotification(watch, [...watch.repos.keys()])
return
}
if (event.kind === 'rename') {
if (event.oldAbsolutePath) {
collectMatchingRepoIds(watch, 'delete', event.oldAbsolutePath, repoIds)
}
collectMatchingRepoIds(watch, 'create', event.absolutePath, repoIds)
continue
}
collectMatchingRepoIds(watch, event.kind, event.absolutePath, repoIds)
const changes = collectRemoteWorktreeBaseChanges(watch, events)
if (changes.overflow) {
scheduleNotification(watch, { structureRepoIds: [...watch.repos.keys()] })
return
}
if (repoIds.size > 0) {
scheduleNotification(watch, [...repoIds])
if (hasCollectedChanges(changes)) {
scheduleNotification(watch, changes)
}
}
@@ -131,7 +153,9 @@ async function subscribeTarget(
mainWindow,
subscription: { unsubscribe: async () => unwatch() },
notifyTimer: null,
pendingRepoIds: new Set(),
pendingStructureRepoIds: new Set(),
pendingGitStatusRepoIds: new Set(),
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
disposed: false
}
return activeWatch
@@ -157,9 +181,17 @@ async function subscribeTarget(
mainWindow,
subscription,
notifyTimer: null,
pendingRepoIds: new Set(),
pendingStructureRepoIds: new Set(),
pendingGitStatusRepoIds: new Set(),
headIdentityRefresh: createWorktreeHeadIdentityRefreshState(),
disposed: false
}
if (supportsHeadIdentityRefresh(activeWatch)) {
// Baseline eagerly so the first status-only signal — possibly hours after
// subscribe — diffs against subscribe-time heads instead of silently
// re-baselining past an external commit.
void refreshWorktreeHeadIdentities(activeWatch, activeWatch.headIdentityRefresh, false)
}
return activeWatch
}
@@ -199,6 +231,8 @@ async function removeWatch(key: string): Promise<void> {
if (watch.notifyTimer) {
clearTimeout(watch.notifyTimer)
}
watch.pendingStructureRepoIds.clear()
watch.pendingGitStatusRepoIds.clear()
await watch.subscription.unsubscribe().catch((error) => {
console.warn(`[worktree-base-watcher] failed to unwatch ${watch.path}:`, error)
})
+273
View File
@@ -0,0 +1,273 @@
import { readdir, stat } from 'node:fs/promises'
import { join } from 'node:path'
import type {
WorktreeBasePollEvent,
WorktreeBaseSubscription
} from './worktree-base-directory-poller'
// Shared with the darwin primary-metadata poll so the platforms cannot drift
// on which shallow leaves count as watchable metadata. `logs/HEAD` catches
// head moves that rewrite no other watched leaf (commit --amend, reset
// --soft); `config.worktree` carries the sparse flag.
export const PRIMARY_CHECKOUT_METADATA_FILES = [
'HEAD',
'packed-refs',
'index',
'config.worktree',
'logs/HEAD'
]
const LINKED_WORKTREE_STRUCTURAL_METADATA_FILES = ['HEAD', 'gitdir', 'locked', 'config.worktree']
const LINKED_WORKTREE_INDEX_FILE = 'index'
const LINKED_WORKTREE_HEAD_LOG_FILE = join('logs', 'HEAD')
// Why: the entry-dir signature gate can miss same-granule index rewrites on
// coarse-mtime filesystems; a periodic ungated re-stat bounds that miss the
// same way the base poller's backstop rescan does.
const INDEX_BACKSTOP_TICKS = 15
function statSignature(s: { mtimeMs: number; ctimeMs: number; ino: number; size: number }): string {
return `${s.mtimeMs}:${s.ctimeMs}:${s.ino}:${s.size}`
}
async function fileSignature(path: string): Promise<string | null> {
try {
const s = await stat(path)
return s.isFile() ? statSignature(s) : null
} catch {
return null
}
}
async function pathSignature(path: string): Promise<string | null> {
try {
const s = await stat(path)
// Why: omitting ctime keeps unrelated metadata churn from re-opening the
// index gate, which would make the HEAD regression test vacuous. The gate
// is load-bearing for index-event emission between backstop ticks; the
// renderer's status poll is the ultimate freshness net.
return `${s.mtimeMs}:${s.ino}:${s.size}`
} catch {
return null
}
}
type GitCommonEntrySnapshot = {
dirSignature: string | null
structuralSignatures: Map<string, string>
indexSignature: string | null
headLogSignature: string | null
}
type GitCommonSnapshot = {
worktreesDirSignature: string | null
entries: Map<string, GitCommonEntrySnapshot>
primarySignatures: Map<string, string>
}
async function snapshotGitCommonEntry(
entryPath: string,
previous: GitCommonEntrySnapshot | undefined,
forceIndexRead: boolean
): Promise<GitCommonEntrySnapshot> {
const dirSignature = await pathSignature(entryPath)
const structuralSignatures = new Map<string, string>()
await Promise.all(
LINKED_WORKTREE_STRUCTURAL_METADATA_FILES.map(async (name) => {
const signature = await fileSignature(join(entryPath, name))
if (signature !== null) {
structuralSignatures.set(name, signature)
}
})
)
// `logs/HEAD` lives in a subdirectory, so appends never bump the entry-dir
// mtime — it must be stat'd every tick rather than gated like `index`.
const headLogSignature = await fileSignature(join(entryPath, LINKED_WORKTREE_HEAD_LOG_FILE))
const shouldReadIndex = forceIndexRead || !previous || previous.dirSignature !== dirSignature
const indexSignature = shouldReadIndex
? await fileSignature(join(entryPath, LINKED_WORKTREE_INDEX_FILE))
: previous.indexSignature
return { dirSignature, structuralSignatures, indexSignature, headLogSignature }
}
async function snapshotPrimaryCheckoutSignatures(
commonDirPath: string
): Promise<Map<string, string>> {
const signatures = new Map<string, string>()
await Promise.all(
PRIMARY_CHECKOUT_METADATA_FILES.map(async (name) => {
const signature = await fileSignature(join(commonDirPath, name))
if (signature !== null) {
signatures.set(name, signature)
}
})
)
return signatures
}
async function snapshotGitCommon(
commonDirPath: string,
previous?: GitCommonSnapshot,
includePrimary = true,
forceIndexRead = false
): Promise<GitCommonSnapshot> {
const entriesByPath = new Map<string, GitCommonEntrySnapshot>()
const worktreesDir = join(commonDirPath, 'worktrees')
const worktreesDirSignature = await pathSignature(worktreesDir)
const primarySignatures = includePrimary
? await snapshotPrimaryCheckoutSignatures(commonDirPath)
: new Map<string, string>()
let entries
try {
entries = await readdir(worktreesDir, { withFileTypes: true })
} catch {
// Missing worktrees dir is normal for repos without linked worktrees.
return {
worktreesDirSignature,
entries: entriesByPath,
primarySignatures
}
}
await Promise.all(
entries.map(async (entry) => {
if (!entry.isDirectory()) {
return
}
const entryPath = join(worktreesDir, entry.name)
entriesByPath.set(
entryPath,
await snapshotGitCommonEntry(entryPath, previous?.entries.get(entryPath), forceIndexRead)
)
})
)
return {
worktreesDirSignature,
entries: entriesByPath,
primarySignatures
}
}
function classifySignatureDiff(
prevSignature: string | null | undefined,
nextSignature: string | null | undefined
): 'create' | 'update' | 'delete' | null {
if (prevSignature == null && nextSignature == null) {
return null
}
if (prevSignature == null) {
return 'create'
}
if (nextSignature == null) {
return 'delete'
}
return prevSignature === nextSignature ? null : 'update'
}
function diffSignatureMaps(
prev: Map<string, string>,
next: Map<string, string>,
resolvePath: (name: string) => string
): WorktreeBasePollEvent[] {
const events: WorktreeBasePollEvent[] = []
const names = new Set([...prev.keys(), ...next.keys()])
for (const name of names) {
const type = classifySignatureDiff(prev.get(name), next.get(name))
if (type) {
events.push({ type, path: resolvePath(name) })
}
}
return events
}
function diffGitCommon(
commonDirPath: string,
prev: GitCommonSnapshot,
next: GitCommonSnapshot
): WorktreeBasePollEvent[] {
const events: WorktreeBasePollEvent[] = []
const worktreesDir = join(commonDirPath, 'worktrees')
const worktreesDirDiff = classifySignatureDiff(
prev.worktreesDirSignature,
next.worktreesDirSignature
)
if (worktreesDirDiff) {
events.push({ type: worktreesDirDiff, path: worktreesDir })
}
for (const [entryPath, entry] of next.entries) {
const prevEntry = prev.entries.get(entryPath)
if (!prevEntry) {
events.push({ type: 'create', path: entryPath })
continue
}
events.push(
...diffSignatureMaps(prevEntry.structuralSignatures, entry.structuralSignatures, (name) =>
join(entryPath, name)
)
)
const indexDiff = classifySignatureDiff(prevEntry.indexSignature, entry.indexSignature)
if (indexDiff) {
events.push({ type: indexDiff, path: join(entryPath, LINKED_WORKTREE_INDEX_FILE) })
}
const headLogDiff = classifySignatureDiff(prevEntry.headLogSignature, entry.headLogSignature)
if (headLogDiff) {
events.push({ type: headLogDiff, path: join(entryPath, LINKED_WORKTREE_HEAD_LOG_FILE) })
}
}
for (const entryPath of prev.entries.keys()) {
if (!next.entries.has(entryPath)) {
events.push({ type: 'delete', path: entryPath })
}
}
events.push(
...diffSignatureMaps(prev.primarySignatures, next.primarySignatures, (name) =>
join(commonDirPath, name)
)
)
return events
}
export async function startGitCommonPolling(
commonDirPath: string,
onEvents: (events: WorktreeBasePollEvent[]) => void,
pollIntervalMs: number,
onFullScan?: () => void,
includePrimary = true
): Promise<WorktreeBaseSubscription> {
let disposed = false
let ticking = false
let tickCount = 0
let snapshot = await snapshotGitCommon(commonDirPath, undefined, includePrimary)
const timer = setInterval(() => {
if (disposed || ticking) {
return
}
ticking = true
tickCount++
const forceIndexRead = tickCount % INDEX_BACKSTOP_TICKS === 0
onFullScan?.()
void snapshotGitCommon(commonDirPath, snapshot, includePrimary, forceIndexRead)
.then((next) => {
if (disposed) {
return
}
const events = diffGitCommon(commonDirPath, snapshot, next)
snapshot = next
if (events.length > 0) {
onEvents(events)
}
})
.catch(() => {
// Transient fs error: keep the previous snapshot and retry next tick.
})
.finally(() => {
ticking = false
})
}, pollIntervalMs)
timer.unref?.()
return {
unsubscribe: async () => {
disposed = true
clearInterval(timer)
}
}
}
+17 -55
View File
@@ -1,10 +1,14 @@
import { readdir, stat } from 'node:fs/promises'
import { stat } from 'node:fs/promises'
import { join } from 'node:path'
import type { WorktreeBaseWatchTarget } from './worktree-base-directory-event-filter'
import type {
WorktreeBasePollEvent,
WorktreeBaseSubscription
} from './worktree-base-directory-poller'
import {
PRIMARY_CHECKOUT_METADATA_FILES,
startGitCommonPolling
} from './worktree-git-common-polling'
// Watches a repo's `<common>/.git/worktrees` metadata plus the primary
// checkout's shallow branch/index files — the only paths the git-common event
@@ -20,8 +24,6 @@ import type {
// Why: branch switches and commits made in the primary checkout rewrite these
// top-level files (linked-worktree equivalents live under `worktrees/`).
// Deliberately excludes FETCH_HEAD-style churn that carries no status change.
const PRIMARY_CHECKOUT_METADATA_FILES = ['HEAD', 'packed-refs', 'index']
async function snapshotPrimaryCheckoutMetadata(
commonDirPath: string
): Promise<Map<string, number>> {
@@ -37,46 +39,22 @@ async function snapshotPrimaryCheckoutMetadata(
return mtimes
}
async function snapshotGitCommon(commonDirPath: string): Promise<Map<string, number>> {
const mtimes = new Map<string, number>()
const worktreesDir = join(commonDirPath, 'worktrees')
let entries
try {
entries = await readdir(worktreesDir, { withFileTypes: true })
} catch {
// Missing worktrees dir is normal for repos without linked worktrees.
return mtimes
}
for (const entry of entries) {
const entryPath = join(worktreesDir, entry.name)
try {
// Entry-dir mtime covers the metadata writes the old recursive watcher
// reacted to (HEAD/gitdir/locked are written via rename into the entry
// dir, which bumps its mtime).
mtimes.set(entryPath, (await stat(entryPath)).mtimeMs)
} catch {
// Entry removed between readdir and stat.
}
}
return mtimes
}
function diffGitCommon(
function diffMtimeMap(
prev: Map<string, number>,
next: Map<string, number>
): WorktreeBasePollEvent[] {
const events: WorktreeBasePollEvent[] = []
for (const [entryPath, mtime] of next) {
const prevMtime = prev.get(entryPath)
for (const [path, mtime] of next) {
const prevMtime = prev.get(path)
if (prevMtime === undefined) {
events.push({ type: 'create', path: entryPath })
events.push({ type: 'create', path })
} else if (prevMtime !== mtime) {
events.push({ type: 'update', path: entryPath })
events.push({ type: 'update', path })
}
}
for (const entryPath of prev.keys()) {
if (!next.has(entryPath)) {
events.push({ type: 'delete', path: entryPath })
for (const path of prev.keys()) {
if (!next.has(path)) {
events.push({ type: 'delete', path })
}
}
return events
@@ -103,7 +81,7 @@ async function startSnapshotDiffPoller(
if (disposed) {
return
}
const events = diffGitCommon(snapshot, next)
const events = diffMtimeMap(snapshot, next)
snapshot = next
if (events.length > 0) {
onEvents(events)
@@ -126,19 +104,6 @@ async function startSnapshotDiffPoller(
}
}
async function snapshotGitCommonAndPrimaryMetadata(
commonDirPath: string
): Promise<Map<string, number>> {
const [worktrees, primary] = await Promise.all([
snapshotGitCommon(commonDirPath),
snapshotPrimaryCheckoutMetadata(commonDirPath)
])
for (const [path, mtime] of primary) {
worktrees.set(path, mtime)
}
return worktrees
}
async function startGitCommonNarrowWatch(
target: WorktreeBaseWatchTarget,
onEvents: (events: WorktreeBasePollEvent[]) => void,
@@ -239,6 +204,8 @@ async function startGitCommonNarrowWatch(
}
if (!(await trySubscribe())) {
// Why: repos commonly start without linked worktrees; retrying the narrow
// subscription lets macOS upgrade to native events when the directory appears.
armExistencePoll()
}
@@ -278,10 +245,5 @@ export async function startGitCommonWatch(
}
}
}
return startSnapshotDiffPoller(
() => snapshotGitCommonAndPrimaryMetadata(target.path),
onEvents,
pollIntervalMs,
onFullScan
)
return startGitCommonPolling(target.path, onEvents, pollIntervalMs, onFullScan)
}
@@ -0,0 +1,152 @@
import { afterEach, describe, expect, it } from 'vitest'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { readGitCommonHeadIdentities } from './worktree-head-identity-reader'
const OID_A = 'a'.repeat(40)
const OID_B = 'b'.repeat(40)
const OID_C = 'c'.repeat(40)
describe('readGitCommonHeadIdentities', () => {
const roots: string[] = []
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
async function makeCommonDir(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-head-reader-'))
roots.push(root)
const commonDir = join(root, 'checkout', '.git')
await mkdir(commonDir, { recursive: true })
return commonDir
}
async function writeLooseRef(commonDir: string, ref: string, oid: string): Promise<void> {
const refPath = join(commonDir, ...ref.split('/'))
await mkdir(dirname(refPath), { recursive: true })
await writeFile(refPath, `${oid}\n`)
}
async function addLinkedWorktree(
commonDir: string,
name: string,
worktreePath: string,
headContent: string
): Promise<void> {
const entry = join(commonDir, 'worktrees', name)
await mkdir(entry, { recursive: true })
await writeFile(join(entry, 'HEAD'), `${headContent}\n`)
await writeFile(join(entry, 'gitdir'), `${join(worktreePath, '.git')}\n`)
}
it('resolves the primary checkout and linked worktrees from loose refs', async () => {
const commonDir = await makeCommonDir()
await writeFile(join(commonDir, 'HEAD'), 'ref: refs/heads/main\n')
await writeLooseRef(commonDir, 'refs/heads/main', OID_A)
await writeLooseRef(commonDir, 'refs/heads/feature', OID_B)
const linkedPath = join(dirname(commonDir), '..', 'linked-wt')
await addLinkedWorktree(commonDir, 'linked-wt', linkedPath, 'ref: refs/heads/feature')
const identities = await readGitCommonHeadIdentities(commonDir)
expect(identities).toContainEqual({
worktreePath: dirname(commonDir),
head: OID_A,
branch: 'refs/heads/main'
})
expect(identities).toContainEqual({
worktreePath: linkedPath,
head: OID_B,
branch: 'refs/heads/feature'
})
})
it('falls back to packed-refs when the loose ref is absent', async () => {
const commonDir = await makeCommonDir()
await writeFile(join(commonDir, 'HEAD'), 'ref: refs/heads/main\n')
await writeFile(
join(commonDir, 'packed-refs'),
`# pack-refs with: peeled fully-peeled sorted\n${OID_C} refs/heads/main\n^${OID_A}\n`
)
const identities = await readGitCommonHeadIdentities(commonDir)
expect(identities).toEqual([
{ worktreePath: dirname(commonDir), head: OID_C, branch: 'refs/heads/main' }
])
})
it('reports detached HEAD as a raw oid with a null branch', async () => {
const commonDir = await makeCommonDir()
await writeFile(join(commonDir, 'HEAD'), `${OID_B}\n`)
const identities = await readGitCommonHeadIdentities(commonDir)
expect(identities).toEqual([{ worktreePath: dirname(commonDir), head: OID_B, branch: null }])
})
it('skips unborn branches instead of emitting partial identities', async () => {
const commonDir = await makeCommonDir()
await writeFile(join(commonDir, 'HEAD'), 'ref: refs/heads/unborn\n')
expect(await readGitCommonHeadIdentities(commonDir)).toEqual([])
})
it('resolves relative gitdir entries against the metadata dir', async () => {
const commonDir = await makeCommonDir()
await writeLooseRef(commonDir, 'refs/heads/feature', OID_B)
const entry = join(commonDir, 'worktrees', 'rel-wt')
await mkdir(entry, { recursive: true })
await writeFile(join(entry, 'HEAD'), 'ref: refs/heads/feature\n')
await writeFile(join(entry, 'gitdir'), `${join('..', '..', '..', '..', 'rel-wt', '.git')}\n`)
const identities = await readGitCommonHeadIdentities(commonDir)
expect(identities).toEqual([
{
worktreePath: join(dirname(commonDir), '..', 'rel-wt'),
head: OID_B,
branch: 'refs/heads/feature'
}
])
})
it('rejects traversal-shaped symrefs instead of reading outside the common dir', async () => {
const commonDir = await makeCommonDir()
// A crafted repo can put arbitrary content in HEAD; backslash segments
// would traverse on Windows where join treats them as separators too.
await writeFile(join(dirname(commonDir), '..', 'outside.txt'), 'secret\n')
for (const ref of [
'refs/heads/../../../outside.txt',
'refs\\..\\..\\..\\outside.txt',
'refs/heads/evil:name',
'refs//heads'
]) {
await writeFile(join(commonDir, 'HEAD'), `ref: ${ref}\n`)
expect(await readGitCommonHeadIdentities(commonDir)).toEqual([])
}
})
it('never emits resolved content that is not a hex object id', async () => {
const commonDir = await makeCommonDir()
await writeFile(join(commonDir, 'HEAD'), 'ref: refs/heads/main\n')
await writeLooseRef(commonDir, 'refs/heads/main', 'not-an-object-id')
expect(await readGitCommonHeadIdentities(commonDir)).toEqual([])
await writeFile(join(commonDir, 'HEAD'), 'this is not a detached oid\n')
expect(await readGitCommonHeadIdentities(commonDir)).toEqual([])
})
it('omits the primary row for non-standard common dir layouts', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-head-reader-'))
roots.push(root)
const commonDir = join(root, 'bare-repo')
await mkdir(commonDir, { recursive: true })
await writeFile(join(commonDir, 'HEAD'), 'ref: refs/heads/main\n')
await writeLooseRef(commonDir, 'refs/heads/main', OID_A)
expect(await readGitCommonHeadIdentities(commonDir)).toEqual([])
})
})
@@ -0,0 +1,161 @@
import { readdir, readFile } from 'node:fs/promises'
import { basename, dirname, isAbsolute, join } from 'node:path'
import type { WorktreeHeadIdentity } from '../../shared/types'
// Why: the whole point of this reader is replacing `git worktree list` fanout
// with bounded metadata-file reads, so head freshness never re-creates the
// spawn pressure that stalled terminal input. Keep it spawn-free.
const MAX_SYMREF_DEPTH = 5
async function readTrimmedFile(path: string): Promise<string | null> {
try {
return (await readFile(path, 'utf8')).trim()
} catch {
return null
}
}
// packed-refs lines are `<oid> <ref>`; `#` headers and `^` peel lines skipped.
async function readPackedRefs(commonDirPath: string): Promise<Map<string, string>> {
const refs = new Map<string, string>()
const content = await readTrimmedFile(join(commonDirPath, 'packed-refs'))
if (content === null) {
return refs
}
for (const line of content.split('\n')) {
if (!line || line.startsWith('#') || line.startsWith('^')) {
continue
}
const separator = line.indexOf(' ')
if (separator <= 0) {
continue
}
refs.set(line.slice(separator + 1).trim(), line.slice(0, separator))
}
return refs
}
// Why: ref content comes from repo files an attacker can craft. Git forbids
// `\` and `:` in ref names, and on Windows `join` also treats `\` as a
// separator — both must be rejected before splicing the ref into a file path.
function isSafeRefName(ref: string): boolean {
if (ref.length === 0 || ref.includes('\\') || ref.includes(':')) {
return false
}
return !ref.split('/').some((part) => part === '..' || part === '')
}
// SHA-1 (40) or SHA-256 (64) object id. Anything else read from disk is not a
// head and must never be emitted — this also caps what any path escape could leak.
const OBJECT_ID_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/
function asObjectId(value: string | null | undefined): string | null {
return value != null && OBJECT_ID_PATTERN.test(value) ? value : null
}
async function resolveRefToOid(
commonDirPath: string,
ref: string,
packedRefs: () => Promise<Map<string, string>>
): Promise<string | null> {
let current = ref
for (let depth = 0; depth < MAX_SYMREF_DEPTH; depth++) {
if (!isSafeRefName(current)) {
return null
}
// Branch refs are shared repo state, so loose files live in the common dir.
const loose = await readTrimmedFile(join(commonDirPath, ...current.split('/')))
if (loose === null) {
return asObjectId((await packedRefs()).get(current))
}
if (loose.startsWith('ref: ')) {
current = loose.slice('ref: '.length).trim()
continue
}
return asObjectId(loose)
}
return null
}
async function readHeadIdentity(
commonDirPath: string,
headFilePath: string,
worktreePath: string,
packedRefs: () => Promise<Map<string, string>>
): Promise<WorktreeHeadIdentity | null> {
const head = await readTrimmedFile(headFilePath)
if (!head) {
return null
}
if (head.startsWith('ref: ')) {
const ref = head.slice('ref: '.length).trim()
const oid = await resolveRefToOid(commonDirPath, ref, packedRefs)
// Unborn branches (no commit yet) stay covered by the structural listing.
if (!oid) {
return null
}
return { worktreePath, head: oid, branch: ref }
}
const detachedOid = asObjectId(head)
return detachedOid ? { worktreePath, head: detachedOid, branch: null } : null
}
/** Reads head/branch for the primary checkout and every linked worktree of a
* Git common dir using only metadata-file reads (HEAD, gitdir, loose refs,
* packed-refs) — no Git subprocess. Unresolvable entries are skipped so
* callers never overwrite store state with partial reads. */
export async function readGitCommonHeadIdentities(
commonDirPath: string
): Promise<WorktreeHeadIdentity[]> {
let packedRefsPromise: Promise<Map<string, string>> | null = null
const packedRefs = (): Promise<Map<string, string>> =>
(packedRefsPromise ??= readPackedRefs(commonDirPath))
const identities: WorktreeHeadIdentity[] = []
// Only the standard `<checkout>/.git` layout maps a common dir back to its
// primary checkout path; bare/custom GIT_DIR layouts have no primary row.
if (basename(commonDirPath) === '.git') {
const primary = await readHeadIdentity(
commonDirPath,
join(commonDirPath, 'HEAD'),
dirname(commonDirPath),
packedRefs
)
if (primary) {
identities.push(primary)
}
}
let entries
try {
entries = await readdir(join(commonDirPath, 'worktrees'), { withFileTypes: true })
} catch {
return identities
}
for (const entry of entries) {
if (!entry.isDirectory()) {
continue
}
const entryPath = join(commonDirPath, 'worktrees', entry.name)
const gitdirContent = await readTrimmedFile(join(entryPath, 'gitdir'))
if (!gitdirContent) {
continue
}
// `gitdir` holds `<worktree>/.git`, absolute or (with relative-path
// worktrees) relative to the entry dir.
const gitdirAbsolute = isAbsolute(gitdirContent)
? gitdirContent
: join(entryPath, gitdirContent)
const identity = await readHeadIdentity(
commonDirPath,
join(entryPath, 'HEAD'),
dirname(gitdirAbsolute),
packedRefs
)
if (identity) {
identities.push(identity)
}
}
return identities
}
@@ -0,0 +1,79 @@
import type { BrowserWindow } from 'electron'
import { notifyWorktreeHeadIdentitiesChanged } from './worktree-remote'
import { readGitCommonHeadIdentities } from './worktree-head-identity-reader'
type HeadIdentityWatchHost = {
path: string
repos: ReadonlyMap<string, unknown>
mainWindow: BrowserWindow
disposed: boolean
}
export type WorktreeHeadIdentityRefreshState = {
/** worktreePath → `${head} ${branch}` from the last metadata-file read. */
baseline: Map<string, string> | null
inFlight: boolean
queued: boolean
queuedEmit: boolean
}
export function createWorktreeHeadIdentityRefreshState(): WorktreeHeadIdentityRefreshState {
return { baseline: null, inFlight: false, queued: false, queuedEmit: false }
}
function headIdentitySignature(identity: { head: string; branch: string | null }): string {
return `${identity.head} ${identity.branch ?? ''}`
}
/** Diffs metadata-file head reads against the previous baseline and notifies
* only actual head moves, so status-only churn (index rewrites from external
* `git status`) stays silent and never re-enters structural fanout. Passing
* `emit: false` re-baselines without notifying — structural ticks already
* run the authoritative worktree listing. */
export async function refreshWorktreeHeadIdentities(
host: HeadIdentityWatchHost,
state: WorktreeHeadIdentityRefreshState,
emit: boolean
): Promise<void> {
if (host.disposed || host.mainWindow.isDestroyed()) {
return
}
if (state.inFlight) {
state.queued = true
state.queuedEmit ||= emit
return
}
state.inFlight = true
try {
const identities = await readGitCommonHeadIdentities(host.path)
if (host.disposed || host.mainWindow.isDestroyed()) {
return
}
const baseline = state.baseline
state.baseline = new Map(
identities.map((identity) => [identity.worktreePath, headIdentitySignature(identity)])
)
if (!baseline || !emit) {
return
}
const changed = identities.filter(
(identity) => baseline.get(identity.worktreePath) !== headIdentitySignature(identity)
)
if (changed.length === 0) {
return
}
for (const repoId of host.repos.keys()) {
notifyWorktreeHeadIdentitiesChanged(host.mainWindow, repoId, changed)
}
} catch (error) {
console.warn(`[worktree-base-watcher] head identity read failed for ${host.path}:`, error)
} finally {
state.inFlight = false
if (state.queued && !host.disposed) {
const queuedEmit = state.queuedEmit
state.queued = false
state.queuedEmit = false
void refreshWorktreeHeadIdentities(host, state, queuedEmit)
}
}
}
+25
View File
@@ -22,6 +22,7 @@ import type {
LocalBaseRefUpdateSuggestion,
Repo,
Worktree,
WorktreeHeadIdentity,
WorktreeMeta
} from '../../shared/types'
import { getPRForBranch } from '../github/client'
@@ -1516,6 +1517,30 @@ export function notifyWorktreesChanged(mainWindow: BrowserWindow, repoId: string
}
}
export function notifyWorktreeGitStatusMetadataChanged(
mainWindow: BrowserWindow,
repoId: string
): void {
// Why: index churn is a Source Control freshness hint, not a worktree graph
// mutation; keep structural caches and runtime/mobile events untouched.
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('worktrees:gitStatusMetadataChanged', { repoId })
}
}
export function notifyWorktreeHeadIdentitiesChanged(
mainWindow: BrowserWindow,
repoId: string,
identities: WorktreeHeadIdentity[]
): void {
// Why: background worktrees have no active-scoped status refresh, so head
// moves detected from metadata files ride this targeted desktop event
// instead of re-entering the structural fanout or runtime/mobile events.
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('worktrees:headIdentitiesChanged', { repoId, identities })
}
}
// Why: two-phase spinner. Main process fires `'fetching'` before waiting on
// pre-create fetch work and `'creating'` immediately before `git worktree add`.
// Renderer swaps its spinner label in response; fallback is the static
+6 -4
View File
@@ -202,6 +202,7 @@ import type {
UpdateStatus,
Worktree,
WorktreeBaseStatusEvent,
WorktreeHeadIdentity,
WorktreeLineage,
WorkspaceLineage,
WorktreeMeta,
@@ -1179,6 +1180,10 @@ export type PreloadApi = {
* in main memory only — null after a restart or once the failure clears. */
getBranchRenameFailureOutput: (args: { worktreeId: string }) => Promise<string | null>
onChanged: (callback: (data: { repoId: string }) => void) => () => void
onGitStatusMetadataChanged: (callback: (data: { repoId: string }) => void) => () => void
onHeadIdentitiesChanged: (
callback: (data: { repoId: string; identities: WorktreeHeadIdentity[] }) => void
) => () => void
onBaseStatus: (callback: (data: WorktreeBaseStatusEvent) => void) => () => void
onRemoteBranchConflict: (
callback: (data: WorktreeRemoteBranchConflictEvent) => void
@@ -2073,10 +2078,7 @@ export type PreloadApi = {
* IPC — call sparingly. */
getSync: () => GlobalSettings | null
set: (args: Partial<GlobalSettings>) => Promise<GlobalSettings>
updatePRBotAuthorOverride: (args: {
author: string
isBot: boolean
}) => Promise<GlobalSettings>
updatePRBotAuthorOverride: (args: { author: string; isBot: boolean }) => Promise<GlobalSettings>
listFonts: () => Promise<string[]>
previewGhosttyImport: () => Promise<GhosttyImportPreview>
previewWarpThemeImport: (source: WarpThemeImportSource) => Promise<WarpThemeImportPreview>
+19
View File
@@ -53,6 +53,7 @@ import type {
UpdateStatus,
WorktreeBaseStatusEvent,
WorktreeDefaultTabsLaunch,
WorktreeHeadIdentity,
WorktreeRemoteBranchConflictEvent
} from '../shared/types'
import type { PtyModelRestoreNeededEvent } from '../shared/pty-model-restore-marker'
@@ -725,6 +726,24 @@ const api = {
return () => ipcRenderer.removeListener('worktrees:changed', listener)
},
onGitStatusMetadataChanged: (callback: (data: { repoId: string }) => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent, data: { repoId: string }) =>
callback(data)
ipcRenderer.on('worktrees:gitStatusMetadataChanged', listener)
return () => ipcRenderer.removeListener('worktrees:gitStatusMetadataChanged', listener)
},
onHeadIdentitiesChanged: (
callback: (data: { repoId: string; identities: WorktreeHeadIdentity[] }) => void
): (() => void) => {
const listener = (
_event: Electron.IpcRendererEvent,
data: { repoId: string; identities: WorktreeHeadIdentity[] }
) => callback(data)
ipcRenderer.on('worktrees:headIdentitiesChanged', listener)
return () => ipcRenderer.removeListener('worktrees:headIdentitiesChanged', listener)
},
onBaseStatus: (callback: (data: WorktreeBaseStatusEvent) => void): (() => void) => {
const listener = (_event: Electron.IpcRendererEvent, data: WorktreeBaseStatusEvent) =>
callback(data)
@@ -3,6 +3,7 @@ import type * as React from 'react'
import { ORCA_TERMINAL_COMMAND_FINISHED_EVENT } from '@/hooks/terminal-command-finished-event'
type WorktreesChangedCallback = (data: { repoId: string }) => void
type GitStatusMetadataChangedCallback = (data: { repoId: string }) => void
type HookParams = {
activeRepoId: string | null
activeWorktreeId: string | null
@@ -12,8 +13,12 @@ type HookParams = {
async function renderHookOnce(params: HookParams): Promise<{
emitWorktreesChanged: (repoId: string) => void
emitGitStatusMetadataChanged: (repoId: string) => void
emitCommandFinished: (worktreeId: string) => void
onChangedSubscribe: ReturnType<typeof vi.fn>
onGitStatusMetadataChangedSubscribe: ReturnType<typeof vi.fn>
onChangedUnsubscribe: ReturnType<typeof vi.fn>
onGitStatusMetadataChangedUnsubscribe: ReturnType<typeof vi.fn>
windowListeners: Map<string, EventListener>
cleanups: (() => void)[]
}> {
@@ -35,17 +40,26 @@ async function renderHookOnce(params: HookParams): Promise<{
})
let worktreesChangedCallback: WorktreesChangedCallback | null = null
let gitStatusMetadataChangedCallback: GitStatusMetadataChangedCallback | null = null
const onChangedUnsubscribe = vi.fn()
const onGitStatusMetadataChangedUnsubscribe = vi.fn()
const onChangedSubscribe = vi.fn((callback: WorktreesChangedCallback) => {
worktreesChangedCallback = callback
return onChangedUnsubscribe
})
const onGitStatusMetadataChangedSubscribe = vi.fn(
(callback: GitStatusMetadataChangedCallback) => {
gitStatusMetadataChangedCallback = callback
return onGitStatusMetadataChangedUnsubscribe
}
)
const windowListeners = new Map<string, EventListener>()
vi.stubGlobal('window', {
api: {
worktrees: {
onChanged: onChangedSubscribe
onChanged: onChangedSubscribe,
onGitStatusMetadataChanged: onGitStatusMetadataChangedSubscribe
}
},
addEventListener: vi.fn((type: string, listener: EventListener) => {
@@ -70,11 +84,16 @@ async function renderHookOnce(params: HookParams): Promise<{
return {
emitWorktreesChanged: (repoId: string) => worktreesChangedCallback?.({ repoId }),
emitGitStatusMetadataChanged: (repoId: string) =>
gitStatusMetadataChangedCallback?.({ repoId }),
emitCommandFinished: (worktreeId: string) => {
const listener = windowListeners.get(ORCA_TERMINAL_COMMAND_FINISHED_EVENT)
listener?.({ detail: { worktreeId } } as unknown as Event)
},
onChangedSubscribe,
onGitStatusMetadataChangedSubscribe,
onChangedUnsubscribe,
onGitStatusMetadataChangedUnsubscribe,
windowListeners,
cleanups
}
@@ -102,6 +121,22 @@ describe('useGitStatusPushSignalRefresh', () => {
expect(fetchStatus).toHaveBeenCalledTimes(1)
})
it('nudges status when the active repo reports git status metadata changes', async () => {
const fetchStatus = vi.fn()
const harness = await renderHookOnce({
activeRepoId: 'repo-1',
activeWorktreeId: 'wt-1',
enabled: true,
fetchStatus
})
harness.emitGitStatusMetadataChanged('repo-1')
expect(fetchStatus).toHaveBeenCalledTimes(1)
harness.emitGitStatusMetadataChanged('repo-other')
expect(fetchStatus).toHaveBeenCalledTimes(1)
})
it('nudges status when a terminal command finishes in the active worktree', async () => {
const fetchStatus = vi.fn()
const harness = await renderHookOnce({
@@ -129,6 +164,7 @@ describe('useGitStatusPushSignalRefresh', () => {
;(document as unknown as { visibilityState: string }).visibilityState = 'hidden'
harness.emitWorktreesChanged('repo-1')
harness.emitGitStatusMetadataChanged('repo-1')
harness.emitCommandFinished('wt-1')
expect(fetchStatus).not.toHaveBeenCalled()
})
@@ -143,10 +179,11 @@ describe('useGitStatusPushSignalRefresh', () => {
})
expect(harness.onChangedSubscribe).not.toHaveBeenCalled()
expect(harness.onGitStatusMetadataChangedSubscribe).not.toHaveBeenCalled()
expect(harness.windowListeners.size).toBe(0)
})
it('unsubscribes both signals on cleanup', async () => {
it('unsubscribes preload and command-finished signals on cleanup', async () => {
const fetchStatus = vi.fn()
const harness = await renderHookOnce({
activeRepoId: 'repo-1',
@@ -160,5 +197,7 @@ describe('useGitStatusPushSignalRefresh', () => {
cleanup()
}
expect(harness.windowListeners.size).toBe(0)
expect(harness.onChangedUnsubscribe).toHaveBeenCalledTimes(1)
expect(harness.onGitStatusMetadataChangedUnsubscribe).toHaveBeenCalledTimes(1)
})
})
@@ -33,17 +33,27 @@ export function useGitStatusPushSignalRefresh({
// Why: remote web surfaces have no preload bridge; the fallback poll
// still covers them.
const subscribeToWorktreesChanged = window.api?.worktrees?.onChanged
if (!subscribeToWorktreesChanged) {
const subscribeToGitStatusMetadataChanged = window.api?.worktrees?.onGitStatusMetadataChanged
if (!subscribeToWorktreesChanged && !subscribeToGitStatusMetadataChanged) {
return
}
// Repo metadata (HEAD/index/worktrees) changed on disk. Hidden windows
// skip the nudge; the visibility interval refreshes immediately on reveal.
return subscribeToWorktreesChanged(({ repoId }) => {
const handleRepoSignal = ({ repoId }: { repoId: string }): void => {
if (repoId !== activeRepoId || !isWindowVisible()) {
return
}
fetchStatusRef.current()
})
}
// Repo metadata changed on disk. Hidden windows skip the nudge; the
// visibility interval refreshes immediately on reveal.
const unsubs = [
subscribeToWorktreesChanged?.(handleRepoSignal),
subscribeToGitStatusMetadataChanged?.(handleRepoSignal)
].filter((unsubscribe): unsubscribe is () => void => typeof unsubscribe === 'function')
return () => {
for (const unsubscribe of unsubs) {
unsubscribe()
}
}
}, [enabled, activeRepoId])
useEffect(() => {
@@ -946,6 +946,8 @@ describe('useIpcEvents browser tab create routing', () => {
repos: { onChanged: () => () => {} },
worktrees: {
onChanged: () => () => {},
onGitStatusMetadataChanged: () => () => {},
onHeadIdentitiesChanged: () => () => {},
onBaseStatus: () => () => {},
onRemoteBranchConflict: () => () => {}
},
+17
View File
@@ -3,6 +3,7 @@ import { useEffect } from 'react'
import { toast } from 'sonner'
import { useAppStore } from '../store'
import { shouldRetryPaneSpawnOnSshReconnect } from './ssh-reconnect-pane-retry'
import { applyWorktreeHeadIdentities } from './worktree-head-identity-apply'
import { getWorktreeMapFromState, getRepoMapFromState } from '@/store/selectors'
import { applyUIZoom } from '@/lib/ui-zoom'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
@@ -1141,6 +1142,22 @@ export function useIpcEvents(): void {
)
)
if (window.api.worktrees.onHeadIdentitiesChanged) {
unsubs.push(
window.api.worktrees.onHeadIdentitiesChanged((data) => {
if (isRuntimeEnvironmentActive()) {
// Why: local worktree events carry local repo ids (see onChanged).
return
}
const state = useAppStore.getState()
applyWorktreeHeadIdentities(data, {
getWorktreesForRepo: (repoId) => state.worktreesByRepo[repoId],
updateWorktreeGitIdentity: state.updateWorktreeGitIdentity
})
})
)
}
unsubs.push(
window.api.worktrees.onBaseStatus((event) => {
if (isRuntimeEnvironmentActive()) {
@@ -0,0 +1,88 @@
import { describe, expect, it, vi } from 'vitest'
import type { Worktree } from '../../../shared/types'
import { applyWorktreeHeadIdentities } from './worktree-head-identity-apply'
function makeWorktree(overrides: Partial<Worktree>): Worktree {
return {
id: 'repo-1::/repos/project/wt-a',
repoId: 'repo-1',
path: '/repos/project/wt-a',
branch: 'refs/heads/feature',
head: 'aaa111',
displayName: 'wt-a',
...overrides
} as Worktree
}
describe('applyWorktreeHeadIdentities', () => {
it('updates the matching background worktree row by path', () => {
const updateWorktreeGitIdentity = vi.fn()
applyWorktreeHeadIdentities(
{
repoId: 'repo-1',
identities: [
{ worktreePath: '/repos/project/wt-a', head: 'bbb222', branch: 'refs/heads/feature' }
]
},
{
getWorktreesForRepo: () => [makeWorktree({})],
updateWorktreeGitIdentity
}
)
expect(updateWorktreeGitIdentity).toHaveBeenCalledTimes(1)
expect(updateWorktreeGitIdentity).toHaveBeenCalledWith('repo-1::/repos/project/wt-a', {
head: 'bbb222',
branch: 'refs/heads/feature'
})
})
it('matches Windows-flavored paths that differ only by separators and casing', () => {
const updateWorktreeGitIdentity = vi.fn()
applyWorktreeHeadIdentities(
{
repoId: 'repo-1',
identities: [{ worktreePath: 'C:\\Repos\\Project\\wt-a', head: 'bbb222', branch: null }]
},
{
getWorktreesForRepo: () => [
makeWorktree({ id: 'repo-1::C:/repos/project/wt-a', path: 'C:/repos/project/wt-a' })
],
updateWorktreeGitIdentity
}
)
expect(updateWorktreeGitIdentity).toHaveBeenCalledWith('repo-1::C:/repos/project/wt-a', {
head: 'bbb222',
branch: null
})
})
it('skips identities whose worktree row does not exist', () => {
const updateWorktreeGitIdentity = vi.fn()
applyWorktreeHeadIdentities(
{
repoId: 'repo-1',
identities: [{ worktreePath: '/repos/project/removed', head: 'bbb222', branch: null }]
},
{
getWorktreesForRepo: () => [makeWorktree({})],
updateWorktreeGitIdentity
}
)
expect(updateWorktreeGitIdentity).not.toHaveBeenCalled()
})
it('no-ops for repos with no loaded worktrees', () => {
const updateWorktreeGitIdentity = vi.fn()
applyWorktreeHeadIdentities(
{
repoId: 'repo-unknown',
identities: [{ worktreePath: '/repos/project/wt-a', head: 'bbb222', branch: null }]
},
{
getWorktreesForRepo: () => undefined,
updateWorktreeGitIdentity
}
)
expect(updateWorktreeGitIdentity).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,46 @@
import type { Worktree, WorktreeHeadIdentity } from '../../../shared/types'
import { normalizeRuntimePathForComparison } from '../../../shared/cross-platform-path'
export type WorktreeHeadIdentityApplyDeps = {
getWorktreesForRepo: (repoId: string) => Worktree[] | undefined
updateWorktreeGitIdentity: (
worktreeId: string,
identity: { head?: string; branch?: string | null }
) => void
}
function findWorktreeByPath(worktrees: Worktree[], worktreePath: string): Worktree | undefined {
const exact = worktrees.find((worktree) => worktree.path === worktreePath)
if (exact) {
return exact
}
// Both paths are Git-derived, but separator/casing normalization can differ
// between `git worktree list` output and gitdir-file contents on Windows.
const normalized = normalizeRuntimePathForComparison(worktreePath)
return worktrees.find(
(worktree) => normalizeRuntimePathForComparison(worktree.path) === normalized
)
}
/** Applies head/branch snapshots from the status-only watcher path to store
* rows. Unknown paths are skipped: row creation/removal is structural and
* stays owned by the full worktree listing. */
export function applyWorktreeHeadIdentities(
data: { repoId: string; identities: WorktreeHeadIdentity[] },
deps: WorktreeHeadIdentityApplyDeps
): void {
const worktrees = deps.getWorktreesForRepo(data.repoId)
if (!worktrees || worktrees.length === 0) {
return
}
for (const identity of data.identities) {
const worktree = findWorktreeByPath(worktrees, identity.worktreePath)
if (!worktree) {
continue
}
deps.updateWorktreeGitIdentity(worktree.id, {
head: identity.head,
branch: identity.branch
})
}
}
@@ -56,9 +56,7 @@ describe('PR bot author override updates', () => {
store.pending.shift()?.()
await vi.waitFor(() => expect(store.apiUpdate).toHaveBeenCalledTimes(2))
store.pending.shift()?.()
await vi.waitFor(() =>
expect(store.settings.prBotAuthorOverrides).toEqual(['alice', 'bob'])
)
await vi.waitFor(() => expect(store.settings.prBotAuthorOverrides).toEqual(['alice', 'bob']))
})
it('continues processing updates after an atomic settings write fails', async () => {
+2
View File
@@ -1469,6 +1469,8 @@ function createWorktreesApi(): NonNullable<Partial<PreloadApi>['worktrees']> {
// pairing; the dialog falls back to the persisted excerpt on web clients.
getBranchRenameFailureOutput: async () => null,
onChanged: () => noopUnsubscribe,
onGitStatusMetadataChanged: () => noopUnsubscribe,
onHeadIdentitiesChanged: () => noopUnsubscribe,
onBaseStatus: () => noopUnsubscribe,
onRemoteBranchConflict: () => noopUnsubscribe
}
+11
View File
@@ -433,6 +433,17 @@ export type GitWorktreeInfo = {
isMainWorktree: boolean
}
/** Head/branch snapshot read from Git metadata files without spawning Git.
* Carries background-worktree freshness when status-only churn includes a
* real head move (external commit/amend/reset) that must not re-enter the
* structural `worktrees:changed` fanout. */
export type WorktreeHeadIdentity = {
worktreePath: string
head: string
/** Full ref (e.g. `refs/heads/main`), or null for a detached HEAD. */
branch: string | null
}
// ─── Worktree (app-level, enriched) ──────────────────────────────────
export type WorkspaceStatus = string