From b8014ee0b3b4dc454c468c5151351df10ee05417 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 14:01:11 -0700 Subject: [PATCH 01/20] fix(worktree): never reissue a generated workspace name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generated workspace names were deduped only against currently-live worktrees, so deleting a workspace returned its name to the pool. A later workspace could draw the same name, land on the same directory path, and inherit the previous occupant's agent conversation history — coding-agent CLIs key their prompt history and transcripts by cwd. Names are now retired permanently per repo. The registry is written in main with the name Git actually used (the create loop can advance past a requested name on collision), and seeded once per run from workspace directories and surviving agent transcript buckets so already-spent names are excluded from the start. Suggestions degrade to -2, -3 variants instead of recycling, and those variants retire too. User-typed names are untouched: retirement filters suggestions only. --- src/main/ipc/worktree-remote.ts | 7 ++ src/main/ipc/worktrees.ts | 37 +++++- ...rsistence-worktree-name-retirement.test.ts | 106 ++++++++++++++++++ src/main/persistence.ts | 83 ++++++++++++++ src/main/runtime/orca-runtime.ts | 8 ++ src/main/worktree-name-retirement.test.ts | 68 +++++++++++ src/main/worktree-name-retirement.ts | 102 +++++++++++++++++ src/preload/api-types.ts | 3 + src/preload/index.ts | 1 + .../sidebar/worktree-name-suggestions.test.ts | 30 +++++ .../sidebar/worktree-name-suggestions.ts | 10 +- src/renderer/src/hooks/useComposerState.ts | 7 +- .../src/hooks/useRetiredWorktreeNames.ts | 39 +++++++ src/renderer/src/web/web-preload-api.ts | 4 + src/shared/constants.ts | 1 + src/shared/types.ts | 4 + 16 files changed, 506 insertions(+), 4 deletions(-) create mode 100644 src/main/persistence-worktree-name-retirement.test.ts create mode 100644 src/main/worktree-name-retirement.test.ts create mode 100644 src/main/worktree-name-retirement.ts create mode 100644 src/renderer/src/hooks/useRetiredWorktreeNames.ts diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index f83c5035976f..57abd80cd762 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -135,6 +135,7 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' +import { retirableLeafName } from '../worktree-name-retirement' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1761,6 +1762,9 @@ export async function createRemoteWorktree( } const worktreeId = `${repo.id}::${created.path}` + // Why: retire the leaf the host actually created. Agent state is keyed by cwd on the execution + // host, so a reissued name would give the next occupant the prior one's conversation history. + store.addRetiredWorktreeName(repo.id, retirableLeafName(created.path)) const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch @@ -2378,6 +2382,9 @@ export async function createLocalWorktree( } const worktreeId = `${repo.id}::${created.path}` + // Why: retire the leaf the host actually created. Agent state is keyed by cwd on the execution + // host, so a reissued name would give the next occupant the prior one's conversation history. + store.addRetiredWorktreeName(repo.id, retirableLeafName(created.path)) const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 37a144a9b6d7..51f37b88f272 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -108,8 +108,10 @@ import { areWorktreePathsEqual, formatWorktreeRemovalError, isOrphanCompatiblePreflightError, - isOrphanedWorktreeError + isOrphanedWorktreeError, + computeWorktreePath } from './worktree-logic' +import { discoverRetiredWorktreeNames, retirableLeafName } from '../worktree-name-retirement' import { dedupeWorktreesByPath } from './worktree-path-comparison' import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' import { @@ -602,6 +604,9 @@ function getPreservedBranchCleanupTarget( } const loggedUnavailableSshGitProviders = new Set() +/** Repos whose retirement registry has been seeded this run; the scan is idempotent, so a + * per-run guard is enough to keep repeated suggestion reads from re-scanning the filesystem. */ +const backfilledRetirementRepoIds = new Set() const loggedWorktreeListFailures = new Set() const loggedMalformedWorktreeMetaKeys = new Set() export const DETECTED_WORKTREE_PROVIDER_TIMEOUT_MS = 30_000 @@ -1820,6 +1825,7 @@ export function registerWorktreeHandlers( // Remove previously registered handlers so re-register works when macOS re-activates and creates a new window. ipcMain.removeHandler('worktrees:listAll') ipcMain.removeHandler('worktrees:list') + ipcMain.removeHandler('worktrees:listRetiredNames') ipcMain.removeHandler('worktrees:listDetected') ipcMain.removeHandler('worktrees:listKnownForExecutionHost') ipcMain.removeHandler('worktrees:forgetRemovedForExecutionHost') @@ -1906,6 +1912,35 @@ export function registerWorktreeHandlers( return results.flat() }) + ipcMain.handle('worktrees:listRetiredNames', async (_event, args: { repoId: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo) { + return [] + } + // Why: seed once per app run rather than at startup — the scan is two directory reads, and + // repeating it per run also picks up workspaces deleted outside Orca since the last launch. + if (!backfilledRetirementRepoIds.has(args.repoId)) { + backfilledRetirementRepoIds.add(args.repoId) + try { + const probePath = computeWorktreePath( + 'orca-retirement-probe', + repo.path, + store.getSettings() + ) + const worktreeParent = probePath.slice( + 0, + probePath.length - retirableLeafName(probePath).length - 1 + ) + const discovered = await discoverRetiredWorktreeNames({ workspaceRoots: [worktreeParent] }) + store.mergeRetiredWorktreeNames(args.repoId, discovered) + } catch (err) { + // Best effort: without the seed we only under-retire, which is the pre-existing behavior. + console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) + } + } + return store.getRetiredWorktreeNames(args.repoId) + }) + ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) if (!repo) { diff --git a/src/main/persistence-worktree-name-retirement.test.ts b/src/main/persistence-worktree-name-retirement.test.ts new file mode 100644 index 000000000000..d4aef646a5fb --- /dev/null +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -0,0 +1,106 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { getDefaultPersistedState } from '../shared/constants' + +const testState = { dir: '' } + +vi.mock('electron', () => ({ + app: { getPath: () => testState.dir }, + safeStorage: { isEncryptionAvailable: () => false } +})) +vi.mock('./telemetry/client', () => ({ track: vi.fn() })) +vi.mock('./telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) + +const REPO = 'repo-1' +const OTHER_REPO = 'repo-2' + +async function createStore(persisted: Record = {}) { + mkdirSync(testState.dir, { recursive: true }) + writeFileSync( + join(testState.dir, 'orca-data.json'), + JSON.stringify({ ...getDefaultPersistedState(testState.dir), ...persisted }), + 'utf-8' + ) + vi.resetModules() + const { Store, initDataPath } = await import('./persistence') + initDataPath() + return new Store() +} + +beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-worktree-name-retirement-')) +}) + +afterEach(() => { + rmSync(testState.dir, { force: true, recursive: true }) +}) + +describe('worktree name retirement registry', () => { + it('retains a retired name so it is never reissued', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'Nautilus') + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + }) + + it('scopes retirement per repo so one repo does not burn another pool', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.getRetiredWorktreeNames(OTHER_REPO)).toEqual([]) + }) + + it('normalizes case and whitespace so a name cannot be retired twice', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, ' NaUtIlUs ') + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + }) + + it('ignores an empty name or missing repo id', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, ' ') + store.addRetiredWorktreeName('', 'nautilus') + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + }) + + it('returns a copy so callers cannot mutate the registry in place', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'nautilus') + store.getRetiredWorktreeNames(REPO).push('seahorse') + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + }) + + it('merges backfilled names without dropping a concurrent retirement', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.mergeRetiredWorktreeNames(REPO, ['seahorse', 'starfish'])).toBe(true) + expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse', 'starfish']) + }) + + it('reports no change when a merge adds nothing new', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.mergeRetiredWorktreeNames(REPO, ['NAUTILUS'])).toBe(false) + }) + + it('survives a reload so retirement outlives the workspace and the app session', async () => { + const store = await createStore({ + retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 'seahorse'] } + }) + expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + }) + + it('degrades to nothing retired when the persisted map is corrupt', async () => { + // Why: a load failure costs the app; over- or under-retiring costs at most a name. + const store = await createStore({ retiredWorktreeNamesByRepo: 'not-an-object' }) + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + }) + + it('drops non-string entries but keeps the valid ones', async () => { + const store = await createStore({ + retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 42, null, 'Seahorse'] } + }) + expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + }) +}) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 8b53a7d98d65..a2f8d6031598 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2334,6 +2334,34 @@ const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 // Why: bound removed-SSH-target history so remove/re-add churn can't grow the file unbounded. const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 +/** Why: a corrupt or hand-edited map must degrade to "nothing retired" rather than throw during + * load — over-retiring costs one name from a 552-entry pool, but a load failure costs the app. */ +function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return {} + } + const byRepo: Record = {} + for (const [repoId, names] of Object.entries(value as Record)) { + if (!repoId || !Array.isArray(names)) { + continue + } + const seen = new Set() + for (const entry of names) { + if (typeof entry !== 'string') { + continue + } + const normalized = entry.trim().toLowerCase() + if (normalized.length > 0 && normalized.length <= 256) { + seen.add(normalized) + } + } + if (seen.size > 0) { + byRepo[repoId] = [...seen] + } + } + return byRepo +} + function normalizeClaudeLivePtySessionIds(value: unknown): string[] { if (!Array.isArray(value)) { return [] @@ -3819,6 +3847,9 @@ export class Store { (alias): alias is string => typeof alias === 'string' ) : [], + retiredWorktreeNamesByRepo: normalizeRetiredWorktreeNamesByRepo( + parsed.retiredWorktreeNamesByRepo + ), sshRemotePtyLeases: (parsed.sshRemotePtyLeases ?? []) .map(normalizeSshRemotePtyLease) .filter((lease): lease is SshRemotePtyLease => lease !== null), @@ -7183,6 +7214,58 @@ export class Store { this.scheduleSave() } + getRetiredWorktreeNames(repoId: string): string[] { + return [...(this.state.retiredWorktreeNamesByRepo?.[repoId] ?? [])] + } + + /** Records a generated workspace name as spent for this repo. Called with the name main actually + * used, not the one the renderer proposed — the create path can advance past it on collision. */ + addRetiredWorktreeName(repoId: string, name: string): void { + const normalized = name.trim().toLowerCase() + if (!repoId || normalized.length === 0) { + return + } + this.state.retiredWorktreeNamesByRepo ??= {} + const existing = this.state.retiredWorktreeNamesByRepo[repoId] + if (existing?.includes(normalized)) { + return + } + this.state.retiredWorktreeNamesByRepo[repoId] = existing + ? [...existing, normalized] + : [normalized] + this.scheduleSave() + } + + /** Seeds retirements discovered by the one-time backfill. Merges rather than replaces so a + * concurrent create during backfill is not lost. Returns true when anything was added. */ + mergeRetiredWorktreeNames(repoId: string, names: Iterable): boolean { + if (!repoId) { + return false + } + const incoming = new Set() + for (const name of names) { + const normalized = name.trim().toLowerCase() + if (normalized.length > 0) { + incoming.add(normalized) + } + } + if (incoming.size === 0) { + return false + } + this.state.retiredWorktreeNamesByRepo ??= {} + const existing = this.state.retiredWorktreeNamesByRepo[repoId] ?? [] + const merged = new Set(existing) + for (const name of incoming) { + merged.add(name) + } + if (merged.size === existing.length) { + return false + } + this.state.retiredWorktreeNamesByRepo[repoId] = [...merged] + this.scheduleSave() + return true + } + getDeletedSshConfigAliases(): string[] { return [...(this.state.deletedSshConfigAliases ?? [])] } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index daf9af493863..568f3dc65c3f 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -932,6 +932,7 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' +import { retirableLeafName } from '../worktree-name-retirement' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' import type { StatsCollector } from '../stats/collector' @@ -1108,6 +1109,9 @@ export type CodexRateLimitResetRpcResult = { type RuntimeStore = { getRepos: Store['getRepos'] getRepo: Store['getRepo'] + /** Optional so older embedders of RuntimeStore keep type-checking; the create path skips + * retirement when absent, which only means a name stays issuable. */ + addRetiredWorktreeName?: Store['addRetiredWorktreeName'] addRepo: Store['addRepo'] updateRepo: Store['updateRepo'] getProjects?: Store['getProjects'] @@ -22535,6 +22539,10 @@ export class OrcaRuntimeService { } const worktreeId = `${repo.id}::${created.path}` + // Why: retire the leaf Git actually used, not the requested name — the create loop advances + // past collisions, and Git may canonicalize the path. Retirement is permanent because agent + // CLIs key conversation state by cwd, so a reissued name would inherit the prior occupant's. + this.store.addRetiredWorktreeName?.(repo.id, retirableLeafName(created.path)) const now = Date.now() // Why: PR/MR-created worktrees can start from a head ref/SHA while Source // Control must compare against the review target branch. diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts new file mode 100644 index 000000000000..965740a77e59 --- /dev/null +++ b/src/main/worktree-name-retirement.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { MARINE_CREATURES } from '../shared/marine-creatures' +import { collectRetiredNamesFromPaths, extractCandidateLeafNames } from './worktree-name-retirement' + +const FIRST = MARINE_CREATURES[0].toLowerCase() +const SECOND = MARINE_CREATURES[1].toLowerCase() + +describe('extractCandidateLeafNames', () => { + it('takes the trailing segment of a real path', () => { + expect(extractCandidateLeafNames(`/Users/ada/orca/workspaces/orca/${FIRST}`)).toEqual([FIRST]) + }) + + it('takes the trailing segment of a dash-encoded transcript bucket', () => { + expect(extractCandidateLeafNames(`-Users-ada-orca-workspaces-orca-${FIRST}`)).toEqual([FIRST]) + }) + + it('keeps a numeric tail attached so suffixed variants retire as themselves', () => { + // Why: returning only the base would retire "gar" and leave "gar-2" issuable. + expect(extractCandidateLeafNames(`-Users-ada-worktrees-${FIRST}-2`)).toEqual([ + `${FIRST}-2`, + FIRST + ]) + }) + + it('handles Windows separators and trailing separators', () => { + expect(extractCandidateLeafNames(`C:\\worktrees\\${FIRST}\\`)).toEqual([FIRST]) + }) + + it('returns nothing for an empty or separator-only input', () => { + expect(extractCandidateLeafNames('')).toEqual([]) + expect(extractCandidateLeafNames('---')).toEqual([]) + }) +}) + +describe('collectRetiredNamesFromPaths', () => { + it('retires pool names found in live workspace directories', () => { + expect(collectRetiredNamesFromPaths([FIRST, SECOND])).toEqual(new Set([FIRST, SECOND])) + }) + + it('retires a name whose directory is gone but whose transcript bucket survives', () => { + // The core case: this is the evidence that a deleted workspace left agent state behind. + expect(collectRetiredNamesFromPaths([`-Users-ada-orca-workspaces-orca-${FIRST}`])).toEqual( + new Set([FIRST]) + ) + }) + + it('retires a suffixed variant without also freeing it', () => { + const retired = collectRetiredNamesFromPaths([`-Users-ada-worktrees-${FIRST}-2`]) + expect(retired.has(`${FIRST}-2`)).toBe(true) + }) + + it('ignores paths that contain no pool name', () => { + expect( + collectRetiredNamesFromPaths(['-Users-ada-orca-workspaces-orca-fix-login-redirect']) + ).toEqual(new Set()) + }) + + it('is case-insensitive', () => { + expect(collectRetiredNamesFromPaths([MARINE_CREATURES[0].toUpperCase()])).toEqual( + new Set([FIRST]) + ) + }) + + it('skips non-string and empty entries without throwing', () => { + const paths = [undefined, null, '', FIRST] as unknown as string[] + expect(collectRetiredNamesFromPaths(paths)).toEqual(new Set([FIRST])) + }) +}) diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts new file mode 100644 index 000000000000..68dca2b0b889 --- /dev/null +++ b/src/main/worktree-name-retirement.ts @@ -0,0 +1,102 @@ +import { readdir } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { MARINE_CREATURES } from '../shared/marine-creatures' + +/** Agent CLIs bucket their per-conversation state under a directory derived from the workspace + * cwd. A bucket surviving its workspace is exactly the evidence we need: the name was used, the + * directory is gone, and reissuing the name would hand the next occupant that conversation. */ +const AGENT_TRANSCRIPT_ROOTS = ['.claude/projects', '.codex/sessions'] as const + +const POOL_NAMES: ReadonlySet = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) + +/** Why: worktree paths reaching retirement can be native, WSL, or SSH-host paths, so the leaf is + * taken separator-agnostically rather than through a platform-bound basename. */ +export function retirableLeafName(path: string): string { + const segments = path.split(/[/\\]/).filter((segment) => segment.trim().length > 0) + return segments.at(-1) ?? '' +} + +/** Bucket names encode a path with separators and dots flattened to dashes, so the workspace leaf + * is the trailing segment. A numeric tail is a suffixed variant ("gar-2") and must be kept whole, + * otherwise the base name alone gets retired and the variant stays issuable. */ +export function extractCandidateLeafNames(encodedPath: string): string[] { + const segments = encodedPath + .split(/[-/\\]/) + .map((segment) => segment.trim().toLowerCase()) + .filter((segment) => segment.length > 0) + const last = segments.at(-1) + if (last === undefined) { + return [] + } + const previous = segments.at(-2) + if (previous && /^\d+$/.test(last)) { + return [`${previous}-${last}`, previous] + } + return [last] +} + +/** Why: over-retiring costs one name from a 552-entry pool; under-retiring reissues a path whose + * agent history is still on disk. So this matches generously and never tries to be exact. */ +export function collectRetiredNamesFromPaths(paths: Iterable): Set { + const retired = new Set() + for (const path of paths) { + if (typeof path !== 'string' || path.length === 0) { + continue + } + for (const candidate of extractCandidateLeafNames(path)) { + const base = candidate.replace(/-\d+$/, '') + if (POOL_NAMES.has(base)) { + retired.add(candidate) + } + } + } + return retired +} + +/** Transcript bucket names are the workspace cwd with every non-alphanumeric run flattened to a + * dash. Encoding a repo's worktree parent the same way lets us keep retirement per-repo: a name + * spent under one repo's root says nothing about the same name under another's. */ +export function encodePathForBucketMatch(path: string): string { + return path.replace(/[^a-zA-Z0-9]+/g, '-').toLowerCase() +} + +function bucketBelongsToParent(bucketName: string, encodedParents: readonly string[]): boolean { + if (encodedParents.length === 0) { + return true + } + const bucket = bucketName.toLowerCase() + return encodedParents.some((parent) => parent.length > 0 && bucket.startsWith(parent)) +} + +async function readDirectoryNames(path: string): Promise { + try { + const entries = await readdir(path, { withFileTypes: true }) + return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name) + } catch { + // Missing or unreadable roots are normal: the agent may never have run on this machine. + return [] + } +} + +/** Discovers names already spent for a repo, for the one-time seed of the retirement registry. + * Local and best-effort by design — agent state for an SSH workspace lives on the execution host, + * so names used only there stay issuable until this host observes them. */ +export async function discoverRetiredWorktreeNames(args: { + workspaceRoots: readonly string[] + home?: string +}): Promise> { + const home = args.home ?? homedir() + const observed: string[] = [] + const encodedParents = args.workspaceRoots.map(encodePathForBucketMatch) + + for (const root of args.workspaceRoots) { + observed.push(...(await readDirectoryNames(root))) + } + for (const relativeRoot of AGENT_TRANSCRIPT_ROOTS) { + const buckets = await readDirectoryNames(join(home, ...relativeRoot.split('/'))) + observed.push(...buckets.filter((bucket) => bucketBelongsToParent(bucket, encodedParents))) + } + + return collectRetiredNamesFromPaths(observed) +} diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index c6c8ac84f808..549dbf9c62c3 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1354,6 +1354,9 @@ export type PreloadApi = { } worktrees: { list: (args: { repoId: string }) => Promise + /** Generated names already spent in this repo, including deleted workspaces. Name suggestions + * exclude these so a recreated workspace never lands on a prior occupant's path. */ + listRetiredNames: (args: { repoId: string }) => Promise listDetected: { ( args: ListDetectedWorktreesArgs diff --git a/src/preload/index.ts b/src/preload/index.ts index 31e0c5cbeebc..75c19bde52d2 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -782,6 +782,7 @@ const api = { worktrees: { list: (args) => ipcRenderer.invoke('worktrees:list', args), + listRetiredNames: (args) => ipcRenderer.invoke('worktrees:listRetiredNames', args), listDetected: (args) => ipcRenderer.invoke('worktrees:listDetected', args), diff --git a/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts b/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts index 75c267730a15..fe9403b8e8ca 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts @@ -56,6 +56,36 @@ describe('getSuggestedCreatureName', () => { expect(getSuggestedCreatureName({ 'repo-1': usedWorktrees }, pickFirst)).toBe(`${lower(0)}-2`) }) + it('never reissues a retired name whose workspace is already deleted', () => { + // The bug this guards: the deleted workspace's path still holds agent conversation + // history, so handing the name out again gives the next occupant someone else's chat. + expect(getSuggestedCreatureName({}, pickFirst, [MARINE_CREATURES[0]])).toBe(lower(1)) + }) + + it('treats retired names case-insensitively', () => { + expect(getSuggestedCreatureName({}, pickFirst, [MARINE_CREATURES[0].toUpperCase()])).toBe( + lower(1) + ) + }) + + it('retires names on top of live worktrees rather than replacing that check', () => { + expect( + getSuggestedCreatureName( + { 'repo-1': [{ path: `/tmp/worktrees/${MARINE_CREATURES[0]}` }] }, + pickFirst, + [MARINE_CREATURES[1]] + ) + ).toBe(lower(2)) + }) + + it('skips a retired suffixed variant when falling back past an exhausted pool', () => { + // Tier numbering must not rewind onto a spent variant after its workspace is deleted. + const allUsed = MARINE_CREATURES.map((name) => ({ path: `/tmp/worktrees/${name}` })) + expect(getSuggestedCreatureName({ 'repo-1': allUsed }, pickFirst, [`${lower(0)}-2`])).toBe( + `${lower(1)}-2` + ) + }) + it('treats used names case-insensitively', () => { expect( getSuggestedCreatureName({ 'repo-1': [{ path: '/tmp/worktrees/nAuTiLuS' }] }, pickFirst) diff --git a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts index 2356a7e5614c..568e854b6cf1 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts @@ -21,11 +21,19 @@ function pickRandom(items: readonly T[], random: () => number): T { return items[Math.floor(random() * items.length)] } +/** `retiredNames` are names already spent in the active repo, including ones whose workspace was + * deleted. Reissuing one would place the new workspace on the prior occupant's path, where agent + * CLIs would hand it that workspace's conversation history — so spent names are never offered + * again, and the pool degrades to suffixed variants instead of recycling. */ export function getSuggestedCreatureName( worktreesByRepo: Record, - random: () => number = Math.random + random: () => number = Math.random, + retiredNames: Iterable = [] ): string { const usedNames = collectUsedNames(worktreesByRepo) + for (const retiredName of retiredNames) { + usedNames.add(normalizeSuggestedName(retiredName)) + } // Why: names are lowercased (branch names are conventionally lowercase, e.g. // fix/seahorse), and a random pick keeps fresh worktrees from all starting at diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index b5cdcd01503b..3f76135d2d8a 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -162,6 +162,7 @@ import { getHostDisplayLabelOverrides } from '../../../shared/host-setting-overr import { queueWorkspaceActivationTerminalFocus } from '@/lib/workspace-activation-terminal-focus' import { getSettingsForRepoRuntimeOwner } from '@/lib/repo-runtime-owner' import { getSuggestedCreatureName } from '@/components/sidebar/worktree-name-suggestions' +import { useRetiredWorktreeNames } from '@/hooks/useRetiredWorktreeNames' import type { SmartWorkspaceNameSelection } from '@/components/new-workspace/SmartWorkspaceNameField' import { isBlockingJiraUrlIntent, @@ -1591,9 +1592,11 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const shouldWaitForSetupCheck = Boolean(selectedRepo) && selectedRepoIsGit && isSetupCheckPending // Why: blank name with no other seed → globally-unique creature name so workspaces don't collide across repos or on a literal default. + // Retired names are excluded too, so a recreated workspace never reuses a deleted one's path. + const retiredWorktreeNames = useRetiredWorktreeNames(repoId) const fallbackCreatureName = useMemo( - () => getSuggestedCreatureName(worktreesByRepo), - [worktreesByRepo] + () => getSuggestedCreatureName(worktreesByRepo, undefined, retiredWorktreeNames), + [worktreesByRepo, retiredWorktreeNames] ) const workspaceSeedName = useMemo( () => diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.ts new file mode 100644 index 000000000000..dbe725e8833a --- /dev/null +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.ts @@ -0,0 +1,39 @@ +import { useEffect, useState } from 'react' + +/** Names already spent in a repo, including workspaces that have since been deleted. + * + * Why this is fetched rather than derived from the worktree list: a deleted workspace leaves no + * row behind, but its directory may still hold agent conversation state keyed by that path. Only + * the host-side registry remembers it, so name suggestions must ask for it explicitly. + * + * Failure returns an empty set, which degrades to the pre-existing behavior (a spent name can be + * suggested) rather than blocking workspace creation. */ +export function useRetiredWorktreeNames(repoId: string | null | undefined): string[] { + const [retiredNames, setRetiredNames] = useState([]) + + useEffect(() => { + if (!repoId) { + setRetiredNames([]) + return + } + let cancelled = false + void window.api.worktrees + .listRetiredNames({ repoId }) + .then((names) => { + if (!cancelled) { + setRetiredNames(names) + } + }) + .catch((err) => { + if (!cancelled) { + setRetiredNames([]) + } + console.warn(`Failed to load retired workspace names for repo ${repoId}:`, err) + }) + return () => { + cancelled = true + } + }, [repoId]) + + return retiredNames +} diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 2baa23a7b289..a67258618b99 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1772,6 +1772,10 @@ function createWorktreesApi(): NonNullable['worktrees']> { withRuntimeWorktreeOwner(worktree, owned.hostId) ) }, + // Why: retirement is host-owned state with no wire call, and paired hosts update independently + // of clients. Returning empty degrades a web-client suggestion to the pre-existing behavior + // (a spent name can be offered) rather than inventing an RPC an older host cannot answer. + listRetiredNames: async () => [], listDetected: async ({ repoId }) => callRuntimeDetectedWorktrees(repoId), listAll: () => listAllRuntimeWorktrees(), create: async (args) => { diff --git a/src/shared/constants.ts b/src/shared/constants.ts index a01a778d2dd8..3e88e30f4e17 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -430,6 +430,7 @@ export function getDefaultPersistedState(homedir: string): PersistedState { projectGroups: [], folderWorkspaces: [], sparsePresetsByRepo: {}, + retiredWorktreeNamesByRepo: {}, worktreeMeta: {}, worktreeLineageById: {}, workspaceLineageByChildKey: {}, diff --git a/src/shared/types.ts b/src/shared/types.ts index 25b5df100229..1452d33e09dc 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -3723,6 +3723,10 @@ export type PersistedState = { folderWorkspaceDiffComments?: Record /** Sparse-checkout presets keyed by repoId. */ sparsePresetsByRepo: Record + /** Generated workspace names already issued, keyed by repoId. Suppresses reissuing a name so a + * recreated workspace never lands on a prior occupant's path and inherits agent state keyed to + * that cwd. Grows monotonically; entries are never removed on workspace deletion. */ + retiredWorktreeNamesByRepo?: Record /** Per paired device last tab selection by worktree; keeps mobile navigation across host restarts. */ mobileClientTabSelectionsByDeviceId?: PersistedMobileClientTabSelections worktreeMeta: Record From 1278cd8c12ca430e79159906f6a64cfabb3edc51 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 14:26:08 -0700 Subject: [PATCH 02/20] fix(mobile): honor retired workspace names, on one shared implementation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mobile hand-duplicated the desktop name-suggestion algorithm and deduped only against live workspaces, so a phone could still be offered a name whose deleted workspace left agent conversation state behind at that path. Both platforms now call one shared selector in src/shared, so the two can no longer drift. The host publishes retired names as an optional field on the existing worktree.list response, and mobile fetches them per selected repo while the create sheet is open — mirroring the desktop hook. Mobile never calls worktree.list for its catalog (it uses worktree.ps, which carries rows only), so this is a targeted request rather than a change to the catalog or its cache. Hosts predating the field omit it and mobile falls back to live-only dedupe, which is the pre-change behavior. --- mobile/src/components/NewWorktreeModal.tsx | 8 ++- .../worktree-name-suggestion.test.ts | 56 +++++++++++++++ .../components/worktree-name-suggestion.ts | 68 ++++++------------ .../worktree/use-retired-worktree-names.ts | 48 +++++++++++++ src/main/runtime/orca-runtime.ts | 31 ++++++++- .../sidebar/worktree-name-suggestions.ts | 42 +++-------- src/shared/runtime-types.ts | 7 ++ src/shared/worktree-name-suggestion.test.ts | 69 +++++++++++++++++++ src/shared/worktree-name-suggestion.ts | 64 +++++++++++++++++ 9 files changed, 313 insertions(+), 80 deletions(-) create mode 100644 mobile/src/components/worktree-name-suggestion.test.ts create mode 100644 mobile/src/worktree/use-retired-worktree-names.ts create mode 100644 src/shared/worktree-name-suggestion.test.ts create mode 100644 src/shared/worktree-name-suggestion.ts diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 3fca3261ecc8..8881185d58c1 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -20,6 +20,7 @@ import { useNewWorktreeDrawerNavigation } from './use-new-worktree-drawer-naviga import { PickerListDrawer } from './PickerListDrawer' import { MobileAgentIcon } from './MobileAgentIcon' import { getSuggestedCreatureName } from './worktree-name-suggestion' +import { useRetiredWorktreeNames } from '../worktree/use-retired-worktree-names' import { deriveWorkspaceSshGate, workspaceSshStatusLabel } from '../tasks/workspace-ssh-gate' import { isSetupHookTrusted, @@ -186,6 +187,9 @@ function NewWorktreeModalContent({ const [initialRepos] = useState(() => (hostId ? (getCachedRepos(hostId) as Repo[] | null) : null)) const [repos, setRepos] = useState(initialRepos ?? []) const [selectedRepo, setSelectedRepo] = useState(null) + // Why: a deleted workspace's directory can still hold agent conversation state keyed by cwd, so + // its name must never be suggested again. Fetched per selected repo while the sheet is open. + const retiredWorktreeNames = useRetiredWorktreeNames(client, selectedRepo?.id) const { drawerView, formSheetVisible, formSheetInteractive, transitionDrawer, openSourceDrawer } = useNewWorktreeDrawerNavigation(visible) const createInFlightRef = useRef(false) @@ -601,7 +605,9 @@ function NewWorktreeModalContent({ // the authoritative collision is checked server-side against git // branches/remotes/PRs, so we also retry-with-suffix on conflict. const trimmedName = composer.name.trim() - const baseName = trimmedName || getSuggestedCreatureName(existingWorktreePaths ?? []) + const baseName = + trimmedName || + getSuggestedCreatureName(existingWorktreePaths ?? [], undefined, retiredWorktreeNames) let setupDecision: SetupDecision = 'inherit' if (setupCommand) { diff --git a/mobile/src/components/worktree-name-suggestion.test.ts b/mobile/src/components/worktree-name-suggestion.test.ts new file mode 100644 index 000000000000..2569871c77a1 --- /dev/null +++ b/mobile/src/components/worktree-name-suggestion.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { MARINE_CREATURES } from '../../../src/shared/marine-creatures' +import { getSuggestedCreatureName } from './worktree-name-suggestion' + +const pickFirst = () => 0 +const lower = (index: number) => MARINE_CREATURES[index].toLowerCase() + +describe('getSuggestedCreatureName (mobile)', () => { + it('picks an unused name', () => { + expect(getSuggestedCreatureName([], pickFirst)).toBe(lower(0)) + }) + + it('dedupes against the basename of a live worktree path', () => { + expect(getSuggestedCreatureName([`/home/u/worktrees/${MARINE_CREATURES[0]}`], pickFirst)).toBe( + lower(1) + ) + }) + + it('handles Windows separators and trailing separators like the desktop does', () => { + expect(getSuggestedCreatureName(['C:\\worktrees\\Nautilus\\\\'], pickFirst)).not.toBe( + 'nautilus' + ) + }) + + it('never reissues a retired name whose workspace is already deleted', () => { + // Parity with desktop: the deleted workspace's directory may still hold agent + // conversation state keyed by cwd, so the name must not come back. + expect(getSuggestedCreatureName([], pickFirst, [MARINE_CREATURES[0]])).toBe(lower(1)) + }) + + it('treats retired names case-insensitively', () => { + expect(getSuggestedCreatureName([], pickFirst, [MARINE_CREATURES[0].toUpperCase()])).toBe( + lower(1) + ) + }) + + it('applies retirement on top of live paths rather than instead of them', () => { + expect( + getSuggestedCreatureName([`/home/u/worktrees/${MARINE_CREATURES[0]}`], pickFirst, [ + MARINE_CREATURES[1] + ]) + ).toBe(lower(2)) + }) + + it('degrades to a suffixed tier when the pool is spent, skipping retired variants', () => { + const allPaths = MARINE_CREATURES.map((name) => `/home/u/worktrees/${name}`) + expect(getSuggestedCreatureName(allPaths, pickFirst, [`${lower(0)}-2`])).toBe(`${lower(1)}-2`) + }) + + it('falls back to live-only dedupe when the host sends no retired names', () => { + // Hosts predating the wire field omit it; behavior must match the pre-change app. + expect(getSuggestedCreatureName([`/home/u/worktrees/${MARINE_CREATURES[0]}`], pickFirst)).toBe( + lower(1) + ) + }) +}) diff --git a/mobile/src/components/worktree-name-suggestion.ts b/mobile/src/components/worktree-name-suggestion.ts index 4e84eaae097d..585fb0821811 100644 --- a/mobile/src/components/worktree-name-suggestion.ts +++ b/mobile/src/components/worktree-name-suggestion.ts @@ -1,55 +1,31 @@ -import { MARINE_CREATURES } from '../../../src/shared/marine-creatures' +import { + normalizeSuggestedName, + selectSuggestedCreatureName, + suggestionPathBasename +} from '../../../src/shared/worktree-name-suggestion' -// Why: matches the desktop fallback in -// src/renderer/src/components/sidebar/worktree-name-suggestions.ts. The -// "already exists locally" collision is on the on-disk worktree directory -// name (the path basename), not the user-facing displayName — so we derive -// the used set from path basenames just like the desktop does. +// Why: this used to hand-duplicate the desktop algorithm and the two drifted apart by +// construction. Both now call the shared core so a name suggested on a phone and one suggested on +// the desktop obey the same rules. The dedupe is on the on-disk directory basename, not the +// user-facing displayName, because that is what actually collides. -function stripTrailingSeparators(p: string): string { - return p.replace(/[\\/]+$/, '') -} - -// Why: cross-platform path basename — handles both POSIX ("/") and Windows -// ("\\") separators, mirroring src/renderer/src/lib/path.ts so the mobile -// suggestion logic agrees with the desktop's collision check. -function pathBasename(p: string): string { - const normalized = stripTrailingSeparators(p) - const idx = Math.max(normalized.lastIndexOf('/'), normalized.lastIndexOf('\\')) - return idx === -1 ? normalized : normalized.slice(idx + 1) -} - -function normalize(name: string): string { - return name.trim().toLowerCase() -} - -function pickRandom(items: readonly T[], random: () => number): T { - return items[Math.floor(random() * items.length)] -} - -// Why: pick randomly from the unused pool (not the first in list order) so -// fresh worktrees don't all default to "Nautilus" and collide across repos. +/** `retiredNames` are names already spent in the selected repo, including workspaces that have + * since been deleted — their directories may still hold agent conversation state keyed by cwd, so + * reissuing the name would hand it to the next occupant. + * + * Hosts older than this field send nothing, in which case this degrades to deduping against live + * paths only, exactly as it did before. */ export function getSuggestedCreatureName( existingPaths: readonly string[], - random: () => number = Math.random + random: () => number = Math.random, + retiredNames: readonly string[] = [] ): string { const used = new Set() - for (const p of existingPaths) { - used.add(normalize(pathBasename(p))) - } - // Lowercased to match branch-name convention (fix/seahorse, not fix/Seahorse). - const available = MARINE_CREATURES.map(normalize).filter((name) => !used.has(name)) - if (available.length > 0) { - return pickRandom(available, random) + for (const path of existingPaths) { + used.add(normalizeSuggestedName(suggestionPathBasename(path))) } - let suffix = 2 - while (true) { - const numbered = MARINE_CREATURES.map((name) => `${normalize(name)}-${suffix}`).filter( - (name) => !used.has(name) - ) - if (numbered.length > 0) { - return pickRandom(numbered, random) - } - suffix += 1 + for (const retiredName of retiredNames) { + used.add(normalizeSuggestedName(retiredName)) } + return selectSuggestedCreatureName(used, random) } diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts new file mode 100644 index 000000000000..6aad4726756f --- /dev/null +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -0,0 +1,48 @@ +import { useEffect, useState } from 'react' +import type { RpcClient } from '../transport/rpc-client' + +/** Names already spent in a repo, including workspaces that have since been deleted. + * + * Why a targeted request rather than the workspace catalog: the catalog is served by `worktree.ps`, + * which carries rows only. Retired names are needed just while the create sheet is open and only + * for one repo, so this mirrors the desktop hook and asks for exactly that. + * + * Hosts predating the field omit it, and any failure yields an empty list, so this degrades to + * deduping against live workspaces alone — the behavior before retirement existed. */ +export function useRetiredWorktreeNames( + client: RpcClient | null | undefined, + repoId: string | null | undefined +): readonly string[] { + const [retiredNames, setRetiredNames] = useState([]) + + useEffect(() => { + if (!client || !repoId) { + setRetiredNames([]) + return + } + let cancelled = false + void client + // limit 1 because only the retirement map is wanted; the rows are incidental. + .sendRequest('worktree.list', { repo: `id:${repoId}`, limit: 1 }) + .then((response) => { + if (cancelled) { + return + } + const result = (response as { result?: unknown }).result as + | { retiredNamesByRepo?: Record } + | undefined + const names = result?.retiredNamesByRepo?.[repoId] + setRetiredNames(Array.isArray(names) ? names : []) + }) + .catch(() => { + if (!cancelled) { + setRetiredNames([]) + } + }) + return () => { + cancelled = true + } + }, [client, repoId]) + + return retiredNames +} diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 568f3dc65c3f..e2f6b635ba5d 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1112,6 +1112,7 @@ type RuntimeStore = { /** Optional so older embedders of RuntimeStore keep type-checking; the create path skips * retirement when absent, which only means a name stays issuable. */ addRetiredWorktreeName?: Store['addRetiredWorktreeName'] + getRetiredWorktreeNames?: Store['getRetiredWorktreeNames'] addRepo: Store['addRepo'] updateRepo: Store['updateRepo'] getProjects?: Store['getProjects'] @@ -21027,11 +21028,37 @@ export class OrcaRuntimeService { visibilitySourceMatchersByRepoId.get(worktree.repoId) ) }) + const page = worktrees.slice(0, limit) + const retirementRepoIds = new Set(page.map((worktree) => worktree.repoId)) + // Why: an explicitly selected repo must report its retirements even when the page is empty or + // truncated past it. A repo with no live workspaces is exactly the case where every generated + // name looks free, so omitting it would reissue names precisely where it matters most. + if (repoId) { + retirementRepoIds.add(repoId) + } return { - worktrees: worktrees.slice(0, limit), + worktrees: page, totalCount: worktrees.length, - truncated: worktrees.length > limit + truncated: worktrees.length > limit, + retiredNamesByRepo: this.collectRetiredNamesForRepos(retirementRepoIds) + } + } + + /** Why: scoped to the repos in the page plus any explicitly requested one, so the payload cannot + * grow with the number of repos on the host; a client only suggests names for repos it sees. */ + private collectRetiredNamesForRepos(repoIds: Set): Record { + const store = this.store + if (!store?.getRetiredWorktreeNames) { + return {} + } + const byRepo: Record = {} + for (const repoId of repoIds) { + const names = store.getRetiredWorktreeNames(repoId) + if (names.length > 0) { + byRepo[repoId] = names + } } + return byRepo } async listDetectedManagedWorktrees( diff --git a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts index 568e854b6cf1..bf1ebebe5faf 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts @@ -1,5 +1,8 @@ -import { MARINE_CREATURES } from '@/constants/marine-creatures' import { basename } from '@/lib/path' +import { + normalizeSuggestedName, + selectSuggestedCreatureName +} from '../../../../shared/worktree-name-suggestion' type WorktreePathLike = { path: string @@ -17,14 +20,14 @@ function collectUsedNames(worktreesByRepo: Record): return usedNames } -function pickRandom(items: readonly T[], random: () => number): T { - return items[Math.floor(random() * items.length)] -} - /** `retiredNames` are names already spent in the active repo, including ones whose workspace was * deleted. Reissuing one would place the new workspace on the prior occupant's path, where agent * CLIs would hand it that workspace's conversation history — so spent names are never offered - * again, and the pool degrades to suffixed variants instead of recycling. */ + * again, and the pool degrades to suffixed variants instead of recycling. + * + * Live dedup stays cross-repo while retirement is per-repo: two live workspaces sharing a name + * are confusing in a flat sidebar, but a name retired under one repo says nothing about the same + * name under another, whose path never collided. */ export function getSuggestedCreatureName( worktreesByRepo: Record, random: () => number = Math.random, @@ -34,34 +37,11 @@ export function getSuggestedCreatureName( for (const retiredName of retiredNames) { usedNames.add(normalizeSuggestedName(retiredName)) } - - // Why: names are lowercased (branch names are conventionally lowercase, e.g. - // fix/seahorse), and a random pick keeps fresh worktrees from all starting at - // the same creature and marching down the list in lockstep. - const available = MARINE_CREATURES.map(normalizeSuggestedName).filter( - (name) => !usedNames.has(name) - ) - if (available.length > 0) { - return pickRandom(available, random) - } - - // Every base name is taken — fall back to numbered variants. - let suffix = 2 - while (true) { - const numbered = MARINE_CREATURES.map( - (name) => `${normalizeSuggestedName(name)}-${suffix}` - ).filter((name) => !usedNames.has(name)) - if (numbered.length > 0) { - return pickRandom(numbered, random) - } - suffix += 1 - } + return selectSuggestedCreatureName(usedNames, random) } export function shouldApplySuggestedName(name: string, previousSuggestedName: string): boolean { return !name.trim() || name === previousSuggestedName } -export function normalizeSuggestedName(name: string): string { - return name.trim().toLowerCase() -} +export { normalizeSuggestedName } diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index 079a416749ae..fc4149945779 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -894,6 +894,13 @@ export type RuntimeWorktreeListResult = { worktrees: RuntimeWorktreeRecord[] totalCount: number truncated: boolean + /** Generated workspace names already spent, keyed by repo id, so a client can avoid suggesting a + * name whose old directory may still hold agent conversation state. + * + * Optional on purpose (remote wire compatibility, Rule 1): hosts predating this field omit it, + * and every reader must fall back to deduping against live worktrees alone rather than + * requiring it. Scoped to the repos present in `worktrees` so the payload stays bounded. */ + retiredNamesByRepo?: Record } // ── Browser automation types ── diff --git a/src/shared/worktree-name-suggestion.test.ts b/src/shared/worktree-name-suggestion.test.ts new file mode 100644 index 000000000000..a24f9581903b --- /dev/null +++ b/src/shared/worktree-name-suggestion.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' +import { MARINE_CREATURES } from './marine-creatures' +import { + normalizeSuggestedName, + selectSuggestedCreatureName, + suggestionPathBasename +} from './worktree-name-suggestion' + +const pickFirst = () => 0 +const lower = (index: number) => MARINE_CREATURES[index].toLowerCase() + +describe('suggestionPathBasename', () => { + it('handles POSIX, Windows, and trailing separators identically', () => { + expect(suggestionPathBasename('/tmp/worktrees/Nautilus')).toBe('Nautilus') + expect(suggestionPathBasename('C:\\worktrees\\Nautilus')).toBe('Nautilus') + expect(suggestionPathBasename('/tmp/worktrees/Nautilus///')).toBe('Nautilus') + expect(suggestionPathBasename('C:\\worktrees\\Nautilus\\\\')).toBe('Nautilus') + }) +}) + +describe('selectSuggestedCreatureName', () => { + it('returns a name absent from the used set', () => { + // Anchored on absence rather than pool position: asserting an index would keep passing + // against a filtered pool while testing nothing. + const used = [lower(0), lower(1), lower(2)] + const suggested = selectSuggestedCreatureName(used) + expect(used).not.toContain(suggested) + }) + + it('skips used names when picking the first available', () => { + expect(selectSuggestedCreatureName([lower(0)], pickFirst)).toBe(lower(1)) + }) + + it('normalizes the used set so case and padding cannot smuggle a name back in', () => { + const suggested = selectSuggestedCreatureName([` ${MARINE_CREATURES[0].toUpperCase()} `]) + expect(suggested).not.toBe(lower(0)) + }) + + it('degrades to a suffixed tier once every base name is spent', () => { + const allUsed = MARINE_CREATURES.map((name) => name.toLowerCase()) + expect(selectSuggestedCreatureName(allUsed, pickFirst)).toBe(`${lower(0)}-2`) + }) + + it('does not rewind onto a spent variant within a tier', () => { + const allUsed = [...MARINE_CREATURES.map((name) => name.toLowerCase()), `${lower(0)}-2`] + expect(selectSuggestedCreatureName(allUsed, pickFirst)).toBe(`${lower(1)}-2`) + }) + + it('advances to the next tier when a whole tier is spent', () => { + const allUsed = [ + ...MARINE_CREATURES.map((name) => name.toLowerCase()), + ...MARINE_CREATURES.map((name) => `${name.toLowerCase()}-2`) + ] + expect(selectSuggestedCreatureName(allUsed, pickFirst)).toBe(`${lower(0)}-3`) + }) + + it('returns a lowercase name to match branch convention', () => { + // Pool entries are capitalized; branch names are conventionally lowercase. + const suggested = selectSuggestedCreatureName([], pickFirst) + expect(suggested).toBe(suggested.toLowerCase()) + expect(MARINE_CREATURES).toContain(suggested.charAt(0).toUpperCase() + suggested.slice(1)) + }) +}) + +describe('normalizeSuggestedName', () => { + it('trims and lowercases', () => { + expect(normalizeSuggestedName(' Nautilus ')).toBe('nautilus') + }) +}) diff --git a/src/shared/worktree-name-suggestion.ts b/src/shared/worktree-name-suggestion.ts new file mode 100644 index 000000000000..c9c23838206e --- /dev/null +++ b/src/shared/worktree-name-suggestion.ts @@ -0,0 +1,64 @@ +import { MARINE_CREATURES } from './marine-creatures' + +/** Shared selection core for generated workspace names. + * + * Why this lives in shared: desktop and mobile each need to suggest a name before creating a + * workspace, and they previously hand-duplicated this algorithm. The two copies had to agree — + * both dedupe on the on-disk directory basename, both lowercase to match branch convention, and + * both degrade to suffixed tiers rather than recycling — so they are one implementation now. + * + * Callers assemble the used set themselves because they source it differently (a by-repo map on + * desktop, a flat path list on mobile) and because retired names arrive from different places. */ + +export function normalizeSuggestedName(name: string): string { + return name.trim().toLowerCase() +} + +function stripTrailingSeparators(path: string): string { + return path.replace(/[\\/]+$/, '') +} + +/** Cross-platform basename: worktree paths can be POSIX, Windows, or SSH-host paths, and the + * collision that matters is on the directory name rather than the user-facing display name. */ +export function suggestionPathBasename(path: string): string { + const normalized = stripTrailingSeparators(path) + const index = Math.max(normalized.lastIndexOf('/'), normalized.lastIndexOf('\\')) + return index === -1 ? normalized : normalized.slice(index + 1) +} + +function pickRandom(items: readonly T[], random: () => number): T { + return items[Math.floor(random() * items.length)] +} + +/** Picks a name no one has taken, at random rather than in list order so fresh workspaces don't + * all start at the same creature and march down the list together. + * + * `usedNames` must include retired names as well as live ones. A name whose workspace was deleted + * still owns its old directory path in any agent CLI that keys conversation state by cwd, so + * reissuing it hands the next occupant someone else's history. Once every base name is spent the + * pool degrades to `name-2`, `name-3`, and those variants are equally subject to retirement. */ +export function selectSuggestedCreatureName( + usedNames: Iterable, + random: () => number = Math.random +): string { + const used = new Set() + for (const name of usedNames) { + used.add(normalizeSuggestedName(name)) + } + + const available = MARINE_CREATURES.map(normalizeSuggestedName).filter((name) => !used.has(name)) + if (available.length > 0) { + return pickRandom(available, random) + } + + let suffix = 2 + while (true) { + const numbered = MARINE_CREATURES.map( + (name) => `${normalizeSuggestedName(name)}-${suffix}` + ).filter((name) => !used.has(name)) + if (numbered.length > 0) { + return pickRandom(numbered, random) + } + suffix += 1 + } +} From 21a117aa348c40e21e930b2887b2691c529b9458 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 15:05:05 -0700 Subject: [PATCH 03/20] fix(worktree): close retirement consistency gaps --- mobile/src/components/NewWorktreeModal.tsx | 6 +- .../worktree/use-retired-worktree-names.ts | 18 ++- src/main/ipc/worktrees.ts | 38 ++--- ...rsistence-worktree-name-retirement.test.ts | 14 ++ src/main/persistence.ts | 13 +- src/main/runtime/orca-runtime.ts | 36 +++-- src/main/worktree-name-retirement.test.ts | 75 ++++++++- src/main/worktree-name-retirement.ts | 150 +++++++++++++++++- src/renderer/src/hooks/useComposerState.ts | 20 ++- .../src/hooks/useRetiredWorktreeNames.ts | 28 +++- 10 files changed, 331 insertions(+), 67 deletions(-) diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 8881185d58c1..644a6f27184e 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -189,7 +189,8 @@ function NewWorktreeModalContent({ const [selectedRepo, setSelectedRepo] = useState(null) // Why: a deleted workspace's directory can still hold agent conversation state keyed by cwd, so // its name must never be suggested again. Fetched per selected repo while the sheet is open. - const retiredWorktreeNames = useRetiredWorktreeNames(client, selectedRepo?.id) + const { names: retiredWorktreeNames, loading: retiredWorktreeNamesLoading } = + useRetiredWorktreeNames(client, selectedRepo?.id) const { drawerView, formSheetVisible, formSheetInteractive, transitionDrawer, openSourceDrawer } = useNewWorktreeDrawerNavigation(visible) const createInFlightRef = useRef(false) @@ -564,7 +565,7 @@ function NewWorktreeModalContent({ } async function handleCreate(options: CreateOptions = {}) { - if (!client || !selectedRepo || createInFlightRef.current) { + if (!client || !selectedRepo || retiredWorktreeNamesLoading || createInFlightRef.current) { return } createInFlightRef.current = true @@ -684,6 +685,7 @@ function NewWorktreeModalContent({ const canCreate = selectedRepo != null && !creating && + !retiredWorktreeNamesLoading && !sshGate.requiresConnection && (!needsSetupChoice || setupDecisionChoice != null) const visibleAgentOptions = diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts index 6aad4726756f..b3cc666f8a59 100644 --- a/mobile/src/worktree/use-retired-worktree-names.ts +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -12,12 +12,15 @@ import type { RpcClient } from '../transport/rpc-client' export function useRetiredWorktreeNames( client: RpcClient | null | undefined, repoId: string | null | undefined -): readonly string[] { - const [retiredNames, setRetiredNames] = useState([]) +): { names: readonly string[]; loading: boolean } { + const [loaded, setLoaded] = useState<{ + repoId: string + names: readonly string[] + } | null>(null) useEffect(() => { if (!client || !repoId) { - setRetiredNames([]) + setLoaded(null) return } let cancelled = false @@ -32,11 +35,11 @@ export function useRetiredWorktreeNames( | { retiredNamesByRepo?: Record } | undefined const names = result?.retiredNamesByRepo?.[repoId] - setRetiredNames(Array.isArray(names) ? names : []) + setLoaded({ repoId, names: Array.isArray(names) ? names : [] }) }) .catch(() => { if (!cancelled) { - setRetiredNames([]) + setLoaded({ repoId, names: [] }) } }) return () => { @@ -44,5 +47,8 @@ export function useRetiredWorktreeNames( } }, [client, repoId]) - return retiredNames + return { + names: loaded && loaded.repoId === repoId ? loaded.names : [], + loading: Boolean(client && repoId) && loaded?.repoId !== repoId + } } diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 51f37b88f272..4c4b8aecba5d 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -108,10 +108,12 @@ import { areWorktreePathsEqual, formatWorktreeRemovalError, isOrphanCompatiblePreflightError, - isOrphanedWorktreeError, - computeWorktreePath + isOrphanedWorktreeError } from './worktree-logic' -import { discoverRetiredWorktreeNames, retirableLeafName } from '../worktree-name-retirement' +import { + ensureRetiredWorktreeNamesBackfilled, + getRetiredWorktreeNamesForRepo +} from '../worktree-name-retirement' import { dedupeWorktreesByPath } from './worktree-path-comparison' import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' import { @@ -604,9 +606,6 @@ function getPreservedBranchCleanupTarget( } const loggedUnavailableSshGitProviders = new Set() -/** Repos whose retirement registry has been seeded this run; the scan is idempotent, so a - * per-run guard is enough to keep repeated suggestion reads from re-scanning the filesystem. */ -const backfilledRetirementRepoIds = new Set() const loggedWorktreeListFailures = new Set() const loggedMalformedWorktreeMetaKeys = new Set() export const DETECTED_WORKTREE_PROVIDER_TIMEOUT_MS = 30_000 @@ -1917,28 +1916,13 @@ export function registerWorktreeHandlers( if (!repo) { return [] } - // Why: seed once per app run rather than at startup — the scan is two directory reads, and - // repeating it per run also picks up workspaces deleted outside Orca since the last launch. - if (!backfilledRetirementRepoIds.has(args.repoId)) { - backfilledRetirementRepoIds.add(args.repoId) - try { - const probePath = computeWorktreePath( - 'orca-retirement-probe', - repo.path, - store.getSettings() - ) - const worktreeParent = probePath.slice( - 0, - probePath.length - retirableLeafName(probePath).length - 1 - ) - const discovered = await discoverRetiredWorktreeNames({ workspaceRoots: [worktreeParent] }) - store.mergeRetiredWorktreeNames(args.repoId, discovered) - } catch (err) { - // Best effort: without the seed we only under-retire, which is the pre-existing behavior. - console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) - } + try { + await ensureRetiredWorktreeNamesBackfilled(store, repo, store.getSettings()) + } catch (err) { + // Best effort: without the seed we only under-retire, which is the pre-existing behavior. + console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) } - return store.getRetiredWorktreeNames(args.repoId) + return getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), store.getSettings()) }) ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { diff --git a/src/main/persistence-worktree-name-retirement.test.ts b/src/main/persistence-worktree-name-retirement.test.ts index d4aef646a5fb..79da3b51a74d 100644 --- a/src/main/persistence-worktree-name-retirement.test.ts +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -64,6 +64,13 @@ describe('worktree name retirement registry', () => { expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) }) + it('does not persist arbitrary user and issue-title names', async () => { + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'fix-login-redirect') + store.addRetiredWorktreeName(REPO, 'STA-4189-duplicate-name') + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + }) + it('returns a copy so callers cannot mutate the registry in place', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, 'nautilus') @@ -103,4 +110,11 @@ describe('worktree name retirement registry', () => { }) expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) }) + + it('drops legacy arbitrary names while loading the persisted map', async () => { + const store = await createStore({ + retiredWorktreeNamesByRepo: { [REPO]: ['fix-login', 'Nautilus'] } + }) + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + }) }) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index a2f8d6031598..c446afdd8013 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -170,6 +170,7 @@ import { pruneAutomationRuns } from '../shared/automation-run-retention' import { pruneWorkspaceSessionBrowserHistory } from '../shared/workspace-session-browser-history' +import { normalizeRetirableGeneratedName } from './worktree-name-retirement' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, getRepoIdFromWorktreeId, @@ -2350,8 +2351,8 @@ function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record 0 && normalized.length <= 256) { + const normalized = normalizeRetirableGeneratedName(entry) + if (normalized) { seen.add(normalized) } } @@ -7221,8 +7222,8 @@ export class Store { /** Records a generated workspace name as spent for this repo. Called with the name main actually * used, not the one the renderer proposed — the create path can advance past it on collision. */ addRetiredWorktreeName(repoId: string, name: string): void { - const normalized = name.trim().toLowerCase() - if (!repoId || normalized.length === 0) { + const normalized = normalizeRetirableGeneratedName(name) + if (!repoId || !normalized) { return } this.state.retiredWorktreeNamesByRepo ??= {} @@ -7244,8 +7245,8 @@ export class Store { } const incoming = new Set() for (const name of names) { - const normalized = name.trim().toLowerCase() - if (normalized.length > 0) { + const normalized = normalizeRetirableGeneratedName(name) + if (normalized) { incoming.add(normalized) } } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 3a8ee8ebd74f..f927be3d6500 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -933,7 +933,11 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' -import { retirableLeafName } from '../worktree-name-retirement' +import { + ensureRetiredWorktreeNamesBackfilled, + getRetiredWorktreeNamesByRepo, + retirableLeafName +} from '../worktree-name-retirement' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' import type { StatsCollector } from '../stats/collector' @@ -1114,6 +1118,7 @@ type RuntimeStore = { * retirement when absent, which only means a name stays issuable. */ addRetiredWorktreeName?: Store['addRetiredWorktreeName'] getRetiredWorktreeNames?: Store['getRetiredWorktreeNames'] + mergeRetiredWorktreeNames?: Store['mergeRetiredWorktreeNames'] addRepo: Store['addRepo'] updateRepo: Store['updateRepo'] getProjects?: Store['getProjects'] @@ -21041,8 +21046,24 @@ export class OrcaRuntimeService { if (!Number.isInteger(limit) || limit <= 0) { throw new Error('invalid_limit') } + const selectedRepo = repoSelector ? await this.resolveRepoSelector(repoSelector) : null + if ( + selectedRepo && + this.store?.getRetiredWorktreeNames && + this.store.mergeRetiredWorktreeNames + ) { + try { + await ensureRetiredWorktreeNamesBackfilled( + this.store, + selectedRepo, + this.store.getSettings() + ) + } catch (error) { + console.warn(`[runtime] retirement backfill failed for repo ${selectedRepo.id}:`, error) + } + } const resolved = await this.listResolvedWorktrees() - const repoId = repoSelector ? (await this.resolveRepoSelector(repoSelector)).id : null + const repoId = selectedRepo?.id ?? null const visibilitySourceMatchersByRepoId = this.buildRuntimeVisibilitySourceMatchersByRepoId(resolved) const worktrees = resolved.filter((worktree) => { @@ -21077,14 +21098,9 @@ export class OrcaRuntimeService { if (!store?.getRetiredWorktreeNames) { return {} } - const byRepo: Record = {} - for (const repoId of repoIds) { - const names = store.getRetiredWorktreeNames(repoId) - if (names.length > 0) { - byRepo[repoId] = names - } - } - return byRepo + const repos = store.getRepos() + const settings = store.getSettings() + return getRetiredWorktreeNamesByRepo(store, repoIds, repos, settings) } async listDetectedManagedWorktrees( diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index 965740a77e59..726adc6f70d9 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -1,6 +1,16 @@ import { describe, expect, it } from 'vitest' +import { mkdir, mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { MARINE_CREATURES } from '../shared/marine-creatures' -import { collectRetiredNamesFromPaths, extractCandidateLeafNames } from './worktree-name-retirement' +import type { GlobalSettings, Repo } from '../shared/types' +import { + collectRetiredNamesFromPaths, + ensureRetiredWorktreeNamesBackfilled, + extractCandidateLeafNames, + getRetiredWorktreeNamesForRepo, + normalizeRetirableGeneratedName +} from './worktree-name-retirement' const FIRST = MARINE_CREATURES[0].toLowerCase() const SECOND = MARINE_CREATURES[1].toLowerCase() @@ -66,3 +76,66 @@ describe('collectRetiredNamesFromPaths', () => { expect(collectRetiredNamesFromPaths(paths)).toEqual(new Set([FIRST])) }) }) + +describe('normalizeRetirableGeneratedName', () => { + it('accepts only generated pool names and their numbered variants', () => { + expect(normalizeRetirableGeneratedName(` ${FIRST} `)).toBe(FIRST) + expect(normalizeRetirableGeneratedName(`${FIRST}-2`)).toBe(`${FIRST}-2`) + expect(normalizeRetirableGeneratedName('fix-login')).toBeNull() + expect(normalizeRetirableGeneratedName(`${FIRST}-1`)).toBeNull() + }) +}) + +describe('getRetiredWorktreeNamesForRepo', () => { + const makeRepo = (id: string, path: string): Repo => + ({ id, path, displayName: id, badgeColor: '', addedAt: 0 }) as Repo + const store = { + getRetiredWorktreeNames: (repoId: string) => (repoId === 'repo-a' ? [FIRST] : [SECOND]) + } + + it('shares retirements when non-nested repos create into the same cwd namespace', () => { + const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] + const settings = { workspaceDir: '/workspaces', nestWorkspaces: false } as GlobalSettings + expect(getRetiredWorktreeNamesForRepo(store, repos[1], repos, settings).sort()).toEqual( + [FIRST, SECOND].sort() + ) + }) + + it('keeps independent nested repo paths in separate retirement domains', () => { + const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] + const settings = { workspaceDir: '/workspaces', nestWorkspaces: true } as GlobalSettings + expect(getRetiredWorktreeNamesForRepo(store, repos[1], repos, settings)).toEqual([SECOND]) + }) +}) + +describe('ensureRetiredWorktreeNamesBackfilled', () => { + it('awaits the historical workspace scan before returning names to a client', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-retirement-backfill-')) + const workspaceRoot = join(root, 'workspaces') + await mkdir(join(workspaceRoot, FIRST), { recursive: true }) + const merged: string[] = [] + const store = { + mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { + merged.push(...names) + return true + } + } + const repo = { + id: 'repo-a', + path: join(root, 'repos', 'a'), + displayName: 'repo-a', + badgeColor: '', + addedAt: 0 + } as Repo + + try { + await ensureRetiredWorktreeNamesBackfilled(store, repo, { + workspaceDir: workspaceRoot, + nestWorkspaces: false + }) + expect(merged).toContain(FIRST) + } finally { + await rm(root, { force: true, recursive: true }) + } + }) +}) diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index 68dca2b0b889..3e022e584823 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -2,6 +2,16 @@ import { readdir } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' import { MARINE_CREATURES } from '../shared/marine-creatures' +import { getRepoExecutionHostId } from '../shared/execution-host' +import { isFolderRepo } from '../shared/repo-kind' +import type { GlobalSettings, Repo } from '../shared/types' +import { + computeRemoteWorktreePath, + computeWorktreePath, + getWorktreePathSettings, + hasRepoWorktreeBasePath +} from './ipc/worktree-logic' +import { worktreePathComparisonKey } from './ipc/worktree-path-comparison' /** Agent CLIs bucket their per-conversation state under a directory derived from the workspace * cwd. A bucket surviving its workspace is exactly the evidence we need: the name was used, the @@ -9,6 +19,23 @@ import { MARINE_CREATURES } from '../shared/marine-creatures' const AGENT_TRANSCRIPT_ROOTS = ['.claude/projects', '.codex/sessions'] as const const POOL_NAMES: ReadonlySet = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) +const RETIREMENT_PROBE_NAME = 'orca-retirement-probe' +const backfillsByStore = new WeakMap>>() + +type RetirementStore = { + getRetiredWorktreeNames?(repoId: string): string[] + mergeRetiredWorktreeNames?(repoId: string, names: Iterable): boolean +} +type RetirementPathSettings = Pick + +export function normalizeRetirableGeneratedName(name: string): string | null { + const normalized = name.trim().toLowerCase() + if (normalized.length > 256) { + return null + } + const match = normalized.match(/^(.+?)(?:-([2-9]\d*))?$/) + return match && POOL_NAMES.has(match[1]) ? normalized : null +} /** Why: worktree paths reaching retirement can be native, WSL, or SSH-host paths, so the leaf is * taken separator-agnostically rather than through a platform-bound basename. */ @@ -45,18 +72,131 @@ export function collectRetiredNamesFromPaths(paths: Iterable): Set() + for (const candidate of repos) { + if ( + isFolderRepo(candidate) || + getRetirementCollisionKey(candidate, settings) !== collisionKey + ) { + continue + } + for (const name of getRetiredNames(candidate.id)) { + names.add(name) + } + } + return [...names] +} + +export function getRetiredWorktreeNamesByRepo( + store: RetirementStore, + repoIds: Iterable, + repos: readonly Repo[], + settings: RetirementPathSettings +): Record { + const getRetiredNames = store.getRetiredWorktreeNames?.bind(store) + if (!getRetiredNames) { + return {} + } + const namesByCollisionKey = new Map>() + for (const candidate of repos) { + if (isFolderRepo(candidate)) { + continue + } + const collisionKey = getRetirementCollisionKey(candidate, settings) + let names = namesByCollisionKey.get(collisionKey) + if (!names) { + names = new Set() + namesByCollisionKey.set(collisionKey, names) + } + for (const name of getRetiredNames(candidate.id)) { + names.add(name) + } + } + const requestedRepoIds = new Set(repoIds) + const byRepo: Record = {} + for (const repo of repos) { + if (!requestedRepoIds.has(repo.id) || isFolderRepo(repo)) { + continue + } + const names = namesByCollisionKey.get(getRetirementCollisionKey(repo, settings)) + if (names?.size) { + byRepo[repo.id] = [...names] + } + } + return byRepo +} + +function parentPath(path: string): string { + const trimmed = path.replace(/[/\\]+$/, '') + const separatorIndex = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\')) + return separatorIndex < 0 ? '' : trimmed.slice(0, separatorIndex) +} + +export function ensureRetiredWorktreeNamesBackfilled( + store: RetirementStore, + repo: Repo, + settings: RetirementPathSettings +): Promise { + const mergeRetiredNames = store.mergeRetiredWorktreeNames?.bind(store) + if (isFolderRepo(repo) || repo.connectionId || !mergeRetiredNames) { + return Promise.resolve() + } + let storeBackfills = backfillsByStore.get(store) + if (!storeBackfills) { + storeBackfills = new Map() + backfillsByStore.set(store, storeBackfills) + } + const collisionKey = getRetirementCollisionKey(repo, settings) + const existing = storeBackfills.get(collisionKey) + if (existing) { + return existing + } + const backfill = discoverRetiredWorktreeNames({ + workspaceRoots: [parentPath(getRetirementProbePath(repo, settings))] + }).then((names) => { + mergeRetiredNames(repo.id, names) + }) + storeBackfills.set(collisionKey, backfill) + return backfill +} + /** Transcript bucket names are the workspace cwd with every non-alphanumeric run flattened to a - * dash. Encoding a repo's worktree parent the same way lets us keep retirement per-repo: a name - * spent under one repo's root says nothing about the same name under another's. */ + * dash. Encoding the worktree parent keeps retirement scoped to the cwd collision domain. */ export function encodePathForBucketMatch(path: string): string { return path.replace(/[^a-zA-Z0-9]+/g, '-').toLowerCase() } diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index 3f76135d2d8a..b4941cc26c61 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -1593,7 +1593,16 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS // Why: blank name with no other seed → globally-unique creature name so workspaces don't collide across repos or on a literal default. // Retired names are excluded too, so a recreated workspace never reuses a deleted one's path. - const retiredWorktreeNames = useRetiredWorktreeNames(repoId) + const retiredNamesRefreshKey = useMemo( + () => + (worktreesByRepo[repoId] ?? []) + .map((worktree) => worktree.path) + .sort() + .join('\0'), + [repoId, worktreesByRepo] + ) + const { names: retiredWorktreeNames, loading: retiredWorktreeNamesLoading } = + useRetiredWorktreeNames(repoId, retiredNamesRefreshKey) const fallbackCreatureName = useMemo( () => getSuggestedCreatureName(worktreesByRepo, undefined, retiredWorktreeNames), [worktreesByRepo, retiredWorktreeNames] @@ -3571,6 +3580,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS } if ( !workspaceSeedName || + retiredWorktreeNamesLoading || selectedRepoRequiresConnection || shouldWaitForSetupCheck || shouldWaitForIssueAutomationCheck || @@ -4034,6 +4044,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS shouldWaitForIssueAutomationCheck, shouldWaitForSetupCheck, sourceIntentBlocksCreate, + retiredWorktreeNamesLoading, taskSourceContext, workspaceSeedName, isProjectGroupTarget, @@ -4084,6 +4095,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS } if ( !workspaceNameSeed || + retiredWorktreeNamesLoading || sourceIntentBlocksCreate || selectedRepoRequiresConnection || (requiresExplicitSetupChoice && !setupDecision) || @@ -4620,6 +4632,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS settings?.openAgentTabsInChatByDefault, smartNameMode, sourceIntentBlocksCreate, + retiredWorktreeNamesLoading, disabledTuiAgents, setupDecision, sparseEnabled, @@ -4653,9 +4666,10 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS sparseError } const repoCreateDisabled = - createGateMode === 'quick' + retiredWorktreeNamesLoading || + (createGateMode === 'quick' ? getQuickComposerCreateDisabled(createGateInput) - : getFullComposerCreateDisabled(createGateInput) + : getFullComposerCreateDisabled(createGateInput)) const createDisabled = isProjectGroupTarget ? folderCreateDisabled : repoCreateDisabled const cardProps: ComposerCardProps = { eligibleRepos: isProjectGroupTarget ? folderSourceRepos : eligibleRepos, diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.ts index dbe725e8833a..8dfdc0bb5924 100644 --- a/src/renderer/src/hooks/useRetiredWorktreeNames.ts +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.ts @@ -8,12 +8,22 @@ import { useEffect, useState } from 'react' * * Failure returns an empty set, which degrades to the pre-existing behavior (a spent name can be * suggested) rather than blocking workspace creation. */ -export function useRetiredWorktreeNames(repoId: string | null | undefined): string[] { - const [retiredNames, setRetiredNames] = useState([]) +export function useRetiredWorktreeNames( + repoId: string | null | undefined, + refreshKey: unknown +): { + names: string[] + loading: boolean +} { + const [loaded, setLoaded] = useState<{ + repoId: string + refreshKey: unknown + names: string[] + } | null>(null) useEffect(() => { if (!repoId) { - setRetiredNames([]) + setLoaded(null) return } let cancelled = false @@ -21,19 +31,23 @@ export function useRetiredWorktreeNames(repoId: string | null | undefined): stri .listRetiredNames({ repoId }) .then((names) => { if (!cancelled) { - setRetiredNames(names) + setLoaded({ repoId, refreshKey, names }) } }) .catch((err) => { if (!cancelled) { - setRetiredNames([]) + setLoaded({ repoId, refreshKey, names: [] }) } console.warn(`Failed to load retired workspace names for repo ${repoId}:`, err) }) return () => { cancelled = true } - }, [repoId]) + }, [refreshKey, repoId]) - return retiredNames + return { + names: + loaded && loaded.repoId === repoId && loaded.refreshKey === refreshKey ? loaded.names : [], + loading: Boolean(repoId) && (loaded?.repoId !== repoId || loaded?.refreshKey !== refreshKey) + } } From ba024d52bffe151a0fcb2203a166e69952cf3aec Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 15:32:13 -0700 Subject: [PATCH 04/20] test(worktree): cover retirement runtime contracts --- .../worktree/use-retired-worktree-names.ts | 3 +-- src/main/ipc/worktrees-windows.test.ts | 10 ++++++- src/main/ipc/worktrees.test.ts | 9 ++++++- src/main/runtime/orca-runtime.test.ts | 13 +++++++--- src/main/runtime/orca-runtime.ts | 16 ++++++++++++ src/main/runtime/rpc/methods/worktree.test.ts | 17 ++++++++++++ src/main/runtime/rpc/methods/worktree.ts | 26 +++++++++---------- src/main/runtime/runtime-rpc.ts | 1 + src/main/worktree-name-retirement.ts | 9 ++++++- 9 files changed, 82 insertions(+), 22 deletions(-) diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts index b3cc666f8a59..c875f2ca0c15 100644 --- a/mobile/src/worktree/use-retired-worktree-names.ts +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -25,8 +25,7 @@ export function useRetiredWorktreeNames( } let cancelled = false void client - // limit 1 because only the retirement map is wanted; the rows are incidental. - .sendRequest('worktree.list', { repo: `id:${repoId}`, limit: 1 }) + .sendRequest('worktree.listRetiredNames', { repo: `id:${repoId}` }) .then((response) => { if (cancelled) { return diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index ee9540048cd4..a594e182cd5c 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -158,7 +158,10 @@ describe('registerWorktreeHandlers – Windows path handling', () => { getSettings: vi.fn(), getWorktreeMeta: vi.fn(), setWorktreeMeta: vi.fn(), - removeWorktreeMeta: vi.fn() + removeWorktreeMeta: vi.fn(), + addRetiredWorktreeName: vi.fn(), + getRetiredWorktreeNames: vi.fn(), + mergeRetiredWorktreeNames: vi.fn() } beforeEach(() => { @@ -200,6 +203,9 @@ describe('registerWorktreeHandlers – Windows path handling', () => { store.getWorktreeMeta.mockReset() store.setWorktreeMeta.mockReset() store.removeWorktreeMeta.mockReset() + store.addRetiredWorktreeName.mockReset() + store.getRetiredWorktreeNames.mockReset() + store.mergeRetiredWorktreeNames.mockReset() for (const key of Object.keys(handlers)) { delete handlers[key] @@ -236,6 +242,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) resolveSetupRunnerShellMock.mockReturnValue(undefined) store.getWorktreeMeta.mockReturnValue(undefined) + store.getRetiredWorktreeNames.mockReturnValue([]) store.setWorktreeMeta.mockReturnValue({}) resolveLocalGitUsernameMock.mockResolvedValue('') getDefaultBaseRefMock.mockReturnValue('origin/main') @@ -302,6 +309,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { false ) expect(resolveLocalGitUsernameMock).not.toHaveBeenCalled() + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'improve-dashboard') expect(store.setWorktreeMeta).toHaveBeenCalledWith( 'repo-1::C:/workspaces/improve-dashboard', expect.objectContaining({ diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 02f23bc094a5..ea52426cb4d2 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -316,7 +316,10 @@ describe('registerWorktreeHandlers', () => { removeWorktreeLineage: vi.fn(), getAllWorkspaceLineage: vi.fn(), getFolderWorkspaces: vi.fn(), - getProjectGroups: vi.fn() + getProjectGroups: vi.fn(), + addRetiredWorktreeName: vi.fn(), + getRetiredWorktreeNames: vi.fn(), + mergeRetiredWorktreeNames: vi.fn() } let runtimeStub: { resolveRemoteTrackingBase: ReturnType @@ -400,6 +403,9 @@ describe('registerWorktreeHandlers', () => { store.getAllWorkspaceLineage, store.getFolderWorkspaces, store.getProjectGroups, + store.addRetiredWorktreeName, + store.getRetiredWorktreeNames, + store.mergeRetiredWorktreeNames, killAllProcessesForWorktreeMock, clearProviderPtyStateMock, getLocalPtyProviderMock, @@ -448,6 +454,7 @@ describe('registerWorktreeHandlers', () => { }) store.getWorktreeMeta.mockReturnValue(undefined) store.getAllWorktreeMeta.mockReturnValue({}) + store.getRetiredWorktreeNames.mockReturnValue([]) store.setWorktreeMeta.mockReturnValue({}) store.getProjectHostSetups.mockReturnValue([ { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index ae31995374c1..af8a19b5a8cb 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -1331,6 +1331,9 @@ const store = { addedAt: 1 } ], + addRetiredWorktreeName: () => {}, + getRetiredWorktreeNames: () => [], + mergeRetiredWorktreeNames: () => false, addRepo: () => {}, updateRepo: (id: string, updates: Record) => ({ @@ -4048,12 +4051,13 @@ describe('OrcaRuntimeService', () => { }) it('does not reuse stale in-flight worktree scans after creating a worktree', async () => { - const runtime = new OrcaRuntimeService(store) + const addRetiredWorktreeName = vi.fn() + const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName }) const staleScan = deferred() const createdWorktree = { - path: '/tmp/workspaces/cache-race', + path: '/tmp/workspaces/nautilus', head: 'def', - branch: 'cache-race', + branch: 'nautilus', isBare: false, isMainWorktree: false } @@ -4067,7 +4071,7 @@ describe('OrcaRuntimeService', () => { const staleLookup = runtime.showManagedWorktree(TEST_WORKTREE_ID) const result = await runtime.createManagedWorktree({ repoSelector: 'id:repo-1', - name: 'cache-race' + name: 'nautilus' }) const freshLookup = runtime.showManagedWorktree(result.worktree.id) @@ -4083,6 +4087,7 @@ describe('OrcaRuntimeService', () => { worktrees: expect.arrayContaining([expect.objectContaining({ path: createdWorktree.path })]) } ) + expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus') }) it('creates additional workspace metadata for folder-mode repos through runtime create', async () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index f927be3d6500..c375a1ea60f0 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -21091,6 +21091,22 @@ export class OrcaRuntimeService { } } + async listRetiredWorktreeNames(repoSelector: string): Promise> { + const store = this.store + if (!store?.getRetiredWorktreeNames) { + return {} + } + const repo = await this.resolveRepoSelector(repoSelector) + if (store.mergeRetiredWorktreeNames) { + try { + await ensureRetiredWorktreeNamesBackfilled(store, repo, store.getSettings()) + } catch (error) { + console.warn(`[runtime] retirement backfill failed for repo ${repo.id}:`, error) + } + } + return this.collectRetiredNamesForRepos(new Set([repo.id])) + } + /** Why: scoped to the repos in the page plus any explicitly requested one, so the payload cannot * grow with the number of repos on the host; a client only suggests names for repos it sees. */ private collectRetiredNamesForRepos(repoIds: Set): Record { diff --git a/src/main/runtime/rpc/methods/worktree.test.ts b/src/main/runtime/rpc/methods/worktree.test.ts index 0b5be4da3845..d70e5941a0c5 100644 --- a/src/main/runtime/rpc/methods/worktree.test.ts +++ b/src/main/runtime/rpc/methods/worktree.test.ts @@ -25,6 +25,23 @@ const passthroughDedupe = (_repo: string, _id: string | undefined, run: () => run() describe('worktree RPC methods', () => { + it('returns retired names without exposing the full worktree listing', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + listRetiredWorktreeNames: vi.fn().mockResolvedValue({ 'repo-1': ['nautilus'] }) + } as unknown as OrcaRuntimeService + + const response = await new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }).dispatch( + makeRequest('worktree.listRetiredNames', { repo: 'id:repo-1' }) + ) + + expect(runtime.listRetiredWorktreeNames).toHaveBeenCalledWith('id:repo-1') + expect(response).toMatchObject({ + ok: true, + result: { retiredNamesByRepo: { 'repo-1': ['nautilus'] } } + }) + }) + it('routes mobile session-only activation without notifying desktop clients', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/rpc/methods/worktree.ts b/src/main/runtime/rpc/methods/worktree.ts index 3d2a05b523f3..ead8306f72c5 100644 --- a/src/main/runtime/rpc/methods/worktree.ts +++ b/src/main/runtime/rpc/methods/worktree.ts @@ -43,6 +43,13 @@ export const WORKTREE_METHODS: RpcMethod[] = [ params: WorktreeListParams, handler: async (params, { runtime }) => runtime.listManagedWorktrees(params.repo, params.limit) }), + defineMethod({ + name: 'worktree.listRetiredNames', + params: WorktreeDetectedListParams, + handler: async (params, { runtime }) => ({ + retiredNamesByRepo: await runtime.listRetiredWorktreeNames(params.repo) + }) + }), defineMethod({ name: 'worktree.detectedList', params: WorktreeDetectedListParams, @@ -289,18 +296,11 @@ export const WORKTREE_METHODS: RpcMethod[] = [ defineMethod({ name: 'worktree.forceDeleteBranch', params: WorktreeForceDeleteBranch, - handler: async (params, { runtime }) => - params.hostId - ? runtime.forceDeletePreservedBranch( - params.worktree, - params.branchName, - params.expectedHead, - params.hostId - ) - : runtime.forceDeletePreservedBranch( - params.worktree, - params.branchName, - params.expectedHead - ) + handler: async (params, { runtime }) => { + const deletionArgs = [params.worktree, params.branchName, params.expectedHead] as const + return params.hostId + ? runtime.forceDeletePreservedBranch(...deletionArgs, params.hostId) + : runtime.forceDeletePreservedBranch(...deletionArgs) + } }) ] diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 326801c6fa9b..1b8c39f317d8 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -429,6 +429,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'worktree.activate', 'worktree.create', 'worktree.forceDeleteBranch', + 'worktree.listRetiredNames', 'worktree.prefetchCreateBase', 'worktree.ps', 'worktree.show', diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index 3e022e584823..04ee3d253eae 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -137,16 +137,23 @@ export function getRetiredWorktreeNamesByRepo( if (isFolderRepo(candidate)) { continue } + const retiredNames = getRetiredNames(candidate.id) + if (retiredNames.length === 0) { + continue + } const collisionKey = getRetirementCollisionKey(candidate, settings) let names = namesByCollisionKey.get(collisionKey) if (!names) { names = new Set() namesByCollisionKey.set(collisionKey, names) } - for (const name of getRetiredNames(candidate.id)) { + for (const name of retiredNames) { names.add(name) } } + if (namesByCollisionKey.size === 0) { + return {} + } const requestedRepoIds = new Set(repoIds) const byRepo: Record = {} for (const repo of repos) { From b15c7e084bdcb42bd60f20469d06d605187981c6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 15:50:30 -0700 Subject: [PATCH 05/20] fix(worktree): retire generated collision names --- src/main/ipc/worktree-remote.ts | 11 ++++------- src/main/ipc/worktrees-windows.test.ts | 18 ++++++++++++++++++ src/main/ipc/worktrees.test.ts | 9 +++++---- src/main/runtime/orca-runtime.test.ts | 2 +- src/main/runtime/orca-runtime.ts | 9 +++------ 5 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 57abd80cd762..5f80538f81ca 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -135,7 +135,6 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' -import { retirableLeafName } from '../worktree-name-retirement' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1762,9 +1761,8 @@ export async function createRemoteWorktree( } const worktreeId = `${repo.id}::${created.path}` - // Why: retire the leaf the host actually created. Agent state is keyed by cwd on the execution - // host, so a reissued name would give the next occupant the prior one's conversation history. - store.addRetiredWorktreeName(repo.id, retirableLeafName(created.path)) + // Why: repo-qualified layouts decorate the physical leaf; retire the generated collision key. + store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch @@ -2382,9 +2380,8 @@ export async function createLocalWorktree( } const worktreeId = `${repo.id}::${created.path}` - // Why: retire the leaf the host actually created. Agent state is keyed by cwd on the execution - // host, so a reissued name would give the next occupant the prior one's conversation history. - store.addRetiredWorktreeName(repo.id, retirableLeafName(created.path)) + // Why: repo-qualified layouts decorate the physical leaf; retire the generated collision key. + store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index a594e182cd5c..4ebefe848ade 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -325,6 +325,24 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) }) + it('retires the generated name when flat layout decorates the physical leaf', async () => { + computeWorktreePathMock.mockReturnValue('C:\\workspaces\\repo-nautilus') + ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\repo-nautilus') + listWorktreesMock.mockResolvedValue([ + { + path: 'C:/workspaces/repo-nautilus', + head: 'abc123', + branch: 'refs/heads/nautilus', + isBare: false, + isMainWorktree: false + } + ]) + + await handlers['worktrees:create'](null, { repoId: 'repo-1', name: 'nautilus' }) + + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'nautilus') + }) + it('resolves the Git username when the configured prefix consumes it', async () => { store.getSettings.mockReturnValue({ branchPrefix: 'git-username', diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index ea52426cb4d2..565a6c8c5f5d 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -4672,9 +4672,9 @@ describe('registerWorktreeHandlers', () => { isMainWorktree: true }, { - path: '/remote/repo-improve-dashboard', + path: '/remote/repo-nautilus', head: 'abc123', - branch: 'refs/heads/improve-dashboard', + branch: 'refs/heads/nautilus', isBare: false, isMainWorktree: false } @@ -4693,7 +4693,7 @@ describe('registerWorktreeHandlers', () => { const result = await handlers['worktrees:create'](null, { repoId: 'repo-ssh', - name: 'improve-dashboard', + name: 'nautilus', linkedIssue: 123, linkedPR: 456, createdWithAgent: 'codex', @@ -4711,8 +4711,9 @@ describe('registerWorktreeHandlers', () => { ) expect(provider.listWorktrees).toHaveBeenCalledTimes(1) expect(provider.worktreeIsClean).not.toHaveBeenCalled() + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-ssh', 'nautilus') expect(store.setWorktreeMeta).toHaveBeenCalledWith( - 'repo-ssh::/remote/repo-improve-dashboard', + 'repo-ssh::/remote/repo-nautilus', expect.objectContaining({ linkedIssue: 123, linkedPR: 456, diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index af8a19b5a8cb..97ffb515d61e 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -4055,7 +4055,7 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName }) const staleScan = deferred() const createdWorktree = { - path: '/tmp/workspaces/nautilus', + path: '/tmp/workspaces/repo-nautilus', head: 'def', branch: 'nautilus', isBare: false, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index c375a1ea60f0..184261593494 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -935,8 +935,7 @@ import { } from '../worktree-create-candidates' import { ensureRetiredWorktreeNamesBackfilled, - getRetiredWorktreeNamesByRepo, - retirableLeafName + getRetiredWorktreeNamesByRepo } from '../worktree-name-retirement' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' @@ -22624,10 +22623,8 @@ export class OrcaRuntimeService { } const worktreeId = `${repo.id}::${created.path}` - // Why: retire the leaf Git actually used, not the requested name — the create loop advances - // past collisions, and Git may canonicalize the path. Retirement is permanent because agent - // CLIs key conversation state by cwd, so a reissued name would inherit the prior occupant's. - this.store.addRetiredWorktreeName?.(repo.id, retirableLeafName(created.path)) + // Why: repo-qualified layouts decorate the physical leaf; retire the generated collision key. + this.store.addRetiredWorktreeName?.(repo.id, effectiveSanitizedName) const now = Date.now() // Why: PR/MR-created worktrees can start from a head ref/SHA while Source // Control must compare against the review target branch. From 3b082a94709e1693bbf9ed164aa95eb80502ca75 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 15:56:03 -0700 Subject: [PATCH 06/20] fix(worktree): enforce retired names at creation --- src/main/ipc/worktree-remote.ts | 13 +++++++++++++ src/main/ipc/worktrees-windows.test.ts | 13 +++++++------ src/main/ipc/worktrees.test.ts | 11 +++++++---- src/main/runtime/orca-runtime.test.ts | 12 ++++++++---- src/main/runtime/orca-runtime.ts | 9 ++++++++- 5 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 5f80538f81ca..7c30336427cf 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -135,6 +135,7 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' +import { getRetiredWorktreeNamesForRepo } from '../worktree-name-retirement' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1550,12 +1551,18 @@ export async function createRemoteWorktree( let selectedExistingLocalBranchName: string | null = null let lastBranchConflictKind: 'local' | 'remote' | null = null let remotePathResolved = false + const retiredNames = new Set( + getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings) + ) // Why: duplicate PR/MR checkouts still need a workspace; suffix branch/path while preserving review metadata and push target. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) effectiveRequestedName = args.name.trim() ? getWorktreeCreateCandidate(args.name, suffix) : effectiveSanitizedName + if (retiredNames.has(effectiveSanitizedName)) { + continue + } branchName = await resolveCreateBranchNameSsh( provider, repo.path, @@ -2091,12 +2098,18 @@ export async function createLocalWorktree( let lastBranchConflictKind: 'local' | 'remote' | null = null let lastExistingPR: Awaited> | null = null let lastExistingReviewNumber: number | null = null + const retiredNames = new Set( + getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings) + ) // Why: a create-from-review branch override may already exist locally; suffix both branch and path instead of blocking the user. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) effectiveRequestedName = requestedName.trim() ? getWorktreeCreateCandidate(requestedName, suffix) : effectiveSanitizedName + if (retiredNames.has(effectiveSanitizedName)) { + continue + } lastExistingReviewNumber = null branchName = await resolveCreateBranchName( diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index 4ebefe848ade..32477a819984 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -325,14 +325,15 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) }) - it('retires the generated name when flat layout decorates the physical leaf', async () => { - computeWorktreePathMock.mockReturnValue('C:\\workspaces\\repo-nautilus') - ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\repo-nautilus') + it('skips a retired generated name when the physical leaf is decorated', async () => { + store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + computeWorktreePathMock.mockReturnValue('C:\\workspaces\\repo-nautilus-2') + ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\repo-nautilus-2') listWorktreesMock.mockResolvedValue([ { - path: 'C:/workspaces/repo-nautilus', + path: 'C:/workspaces/repo-nautilus-2', head: 'abc123', - branch: 'refs/heads/nautilus', + branch: 'refs/heads/nautilus-2', isBare: false, isMainWorktree: false } @@ -340,7 +341,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { await handlers['worktrees:create'](null, { repoId: 'repo-1', name: 'nautilus' }) - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'nautilus') + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'nautilus-2') }) it('resolves the Git username when the configured prefix consumes it', async () => { diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 565a6c8c5f5d..8bf3c05595b4 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -4672,9 +4672,9 @@ describe('registerWorktreeHandlers', () => { isMainWorktree: true }, { - path: '/remote/repo-nautilus', + path: '/remote/repo-nautilus-2', head: 'abc123', - branch: 'refs/heads/nautilus', + branch: 'refs/heads/nautilus-2', isBare: false, isMainWorktree: false } @@ -4689,6 +4689,9 @@ describe('registerWorktreeHandlers', () => { store.getRepo.mockReturnValue(repo) getSshGitProviderMock.mockReturnValue(provider) getActiveMultiplexerMock.mockReturnValue(mux) + store.getRetiredWorktreeNames.mockImplementation((repoId) => + repoId === 'repo-ssh' ? ['nautilus'] : [] + ) store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) const result = await handlers['worktrees:create'](null, { @@ -4711,9 +4714,9 @@ describe('registerWorktreeHandlers', () => { ) expect(provider.listWorktrees).toHaveBeenCalledTimes(1) expect(provider.worktreeIsClean).not.toHaveBeenCalled() - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-ssh', 'nautilus') + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-ssh', 'nautilus-2') expect(store.setWorktreeMeta).toHaveBeenCalledWith( - 'repo-ssh::/remote/repo-nautilus', + 'repo-ssh::/remote/repo-nautilus-2', expect.objectContaining({ linkedIssue: 123, linkedPR: 456, diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 97ffb515d61e..cc23e66d4193 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -4052,12 +4052,16 @@ describe('OrcaRuntimeService', () => { it('does not reuse stale in-flight worktree scans after creating a worktree', async () => { const addRetiredWorktreeName = vi.fn() - const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName }) + const runtime = new OrcaRuntimeService({ + ...store, + addRetiredWorktreeName, + getRetiredWorktreeNames: () => ['nautilus'] + }) const staleScan = deferred() const createdWorktree = { - path: '/tmp/workspaces/repo-nautilus', + path: '/tmp/workspaces/repo-nautilus-2', head: 'def', - branch: 'nautilus', + branch: 'nautilus-2', isBare: false, isMainWorktree: false } @@ -4087,7 +4091,7 @@ describe('OrcaRuntimeService', () => { worktrees: expect.arrayContaining([expect.objectContaining({ path: createdWorktree.path })]) } ) - expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus') + expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus-2') }) it('creates additional workspace metadata for folder-mode repos through runtime create', async () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 184261593494..822c6ea70502 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -935,7 +935,8 @@ import { } from '../worktree-create-candidates' import { ensureRetiredWorktreeNamesBackfilled, - getRetiredWorktreeNamesByRepo + getRetiredWorktreeNamesByRepo, + getRetiredWorktreeNamesForRepo } from '../worktree-name-retirement' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' @@ -22297,6 +22298,9 @@ export class OrcaRuntimeService { let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false + const retiredNames = new Set( + getRetiredWorktreeNamesForRepo(this.store, repo, this.store.getRepos(), settings) + ) // Why: runtime/mobile create-from-review callers should get a new workspace // even when the PR branch or review branch name is already in use. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -22304,6 +22308,9 @@ export class OrcaRuntimeService { effectiveRequestedName = args.name.trim() ? getWorktreeCreateCandidate(args.name, suffix) : effectiveSanitizedName + if (retiredNames.has(effectiveSanitizedName)) { + continue + } branchName = await resolveCreateBranchName( repo.path, selectedExistingLocalBranchName ?? From f3361647159c855b4303ad5f173ac57e89f68a47 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 17:42:42 -0700 Subject: [PATCH 07/20] refactor(ai-vault): extract the Claude project-dir encoder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bucket-name encoder and its scope-boundary check were private to the session scanner, so a second consumer had to reimplement them — and got the per-character encoding wrong. Move both to a shared module with direct tests. --- .../claude-project-dir-encoding.test.ts | 53 +++++++++++++++++++ .../ai-vault/claude-project-dir-encoding.ts | 35 ++++++++++++ .../session-scanner-scope-discovery.ts | 33 +----------- 3 files changed, 90 insertions(+), 31 deletions(-) create mode 100644 src/main/ai-vault/claude-project-dir-encoding.test.ts create mode 100644 src/main/ai-vault/claude-project-dir-encoding.ts diff --git a/src/main/ai-vault/claude-project-dir-encoding.test.ts b/src/main/ai-vault/claude-project-dir-encoding.test.ts new file mode 100644 index 000000000000..cf6575230c74 --- /dev/null +++ b/src/main/ai-vault/claude-project-dir-encoding.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from 'vitest' +import { + encodeClaudeProjectPath, + encodeClaudeProjectPaths, + isClaudeProjectDirInScope +} from './claude-project-dir-encoding' + +describe('encodeClaudeProjectPath', () => { + it('emits one dash per non-alphanumeric character rather than per run', () => { + // The distinction is the whole contract: collapsing runs stops matching real bucket names. + expect(encodeClaudeProjectPath('/Users/ada/orca/workspaces')).toBe('-Users-ada-orca-workspaces') + expect(encodeClaudeProjectPath('/Users/ada/.orca/worktrees')).toBe('-Users-ada--orca-worktrees') + }) + + it('encodes a Windows drive path', () => { + expect(encodeClaudeProjectPath('C:\\Users\\ada\\orca\\workspaces')).toBe( + 'C--Users-ada-orca-workspaces' + ) + expect(encodeClaudeProjectPath('C:\\')).toBe('C--') + }) + + it('encodes a WSL UNC path', () => { + expect(encodeClaudeProjectPath('\\\\wsl$\\Ubuntu\\home\\ada\\orca\\workspaces')).toBe( + '--wsl--Ubuntu-home-ada-orca-workspaces' + ) + }) + + it('drops trailing separators but keeps a bare root', () => { + expect(encodeClaudeProjectPath('/Users/ada/orca/')).toBe('-Users-ada-orca') + expect(encodeClaudeProjectPath('/')).toBe('-') + }) + + it('offers the NFC spelling alongside the raw one', () => { + const nfd = '/Users/ada/cafe\u0301' + expect(encodeClaudeProjectPaths(nfd)).toEqual([ + encodeClaudeProjectPath(nfd), + encodeClaudeProjectPath(nfd.normalize('NFC')) + ]) + expect(encodeClaudeProjectPaths('/Users/ada/cafe')).toEqual(['-Users-ada-cafe']) + }) +}) + +describe('isClaudeProjectDirInScope', () => { + it('accepts the prefix itself and its dash-delimited descendants', () => { + expect(isClaudeProjectDirInScope('-w-orca', ['-w-orca'])).toBe(true) + expect(isClaudeProjectDirInScope('-w-orca-nautilus', ['-w-orca'])).toBe(true) + }) + + it('rejects a sibling that merely starts with the prefix', () => { + // Without the boundary, "orca" would absorb every workspace under "orcadyne". + expect(isClaudeProjectDirInScope('-w-orcadyne-nautilus', ['-w-orca'])).toBe(false) + }) +}) diff --git a/src/main/ai-vault/claude-project-dir-encoding.ts b/src/main/ai-vault/claude-project-dir-encoding.ts new file mode 100644 index 000000000000..5cd720b2e0d9 --- /dev/null +++ b/src/main/ai-vault/claude-project-dir-encoding.ts @@ -0,0 +1,35 @@ +import { normalizeRuntimePathSeparators } from '../../shared/cross-platform-path' + +/** + * Why: Claude derives the directory name from the raw cwd, so encoding from the + * comparison key would lowercase Windows paths and never match on disk. Encode + * the raw path, plus its NFC spelling, since macOS hands us NFD (#10832). + */ +export function encodeClaudeProjectPaths(pathValue: string): string[] { + const raw = encodeClaudeProjectPath(pathValue) + const composed = encodeClaudeProjectPath(pathValue.normalize('NFC')) + return raw === composed ? [raw] : [raw, composed] +} + +/** One dash per non-alphanumeric character — runs are NOT collapsed, so `/.claude` encodes to + * `--claude` and `C:\` to `c--`. Anything that collapses runs stops matching real buckets. */ +export function encodeClaudeProjectPath(pathValue: string): string { + const separated = normalizeRuntimePathSeparators(pathValue) + const trimmed = + separated === '/' || /^[A-Za-z]:\/$/.test(separated) ? separated : separated.replace(/\/+$/, '') + return trimmed.replace(/[^a-zA-Z0-9]/g, '-') +} + +/** Why the explicit boundary: a bare `startsWith` lets a sibling prefix match, so the encoding of + * `…/orca` would claim `…/orca-secret` and `…/orcadyne` as its own. */ +export function isClaudeProjectDirInScope( + projectDirName: string, + scopePrefixes: ReadonlySet | readonly string[] +): boolean { + for (const prefix of scopePrefixes) { + if (projectDirName === prefix || projectDirName.startsWith(`${prefix}-`)) { + return true + } + } + return false +} diff --git a/src/main/ai-vault/session-scanner-scope-discovery.ts b/src/main/ai-vault/session-scanner-scope-discovery.ts index e787aef628e5..9a436dbe814f 100644 --- a/src/main/ai-vault/session-scanner-scope-discovery.ts +++ b/src/main/ai-vault/session-scanner-scope-discovery.ts @@ -6,10 +6,8 @@ import { wslGatedStat } from '../native-chat/wsl-transcript-fs-access' import { WslTranscriptFsError } from '../native-chat/wsl-transcript-fs-gate' -import { - isPathInsideOrEqual, - normalizeRuntimePathSeparators -} from '../../shared/cross-platform-path' +import { isPathInsideOrEqual } from '../../shared/cross-platform-path' +import { encodeClaudeProjectPaths, isClaudeProjectDirInScope } from './claude-project-dir-encoding' import type { AiVaultScanIssue } from '../../shared/ai-vault-types' import { parseWslUncPath } from '../../shared/wsl-paths' import { recordSessionScanIssue } from './session-scan-issues' @@ -120,33 +118,6 @@ function scopePathCandidates(scopePath: string): string[] { return wslScopePath ? [scopePath, wslScopePath.linuxPath] : [scopePath] } -/** - * Why: Claude derives the directory name from the raw cwd, so encoding from the - * comparison key would lowercase Windows paths and never match on disk. Encode - * the raw path, plus its NFC spelling, since macOS hands us NFD (#10832). - */ -function encodeClaudeProjectPaths(pathValue: string): string[] { - const raw = encodeClaudeProjectPath(pathValue) - const composed = encodeClaudeProjectPath(pathValue.normalize('NFC')) - return raw === composed ? [raw] : [raw, composed] -} - -function encodeClaudeProjectPath(pathValue: string): string { - const separated = normalizeRuntimePathSeparators(pathValue) - const trimmed = - separated === '/' || /^[A-Za-z]:\/$/.test(separated) ? separated : separated.replace(/\/+$/, '') - return trimmed.replace(/[^a-zA-Z0-9]/g, '-') -} - -function isClaudeProjectDirInScope(projectDirName: string, scopePrefixes: ReadonlySet) { - for (const prefix of scopePrefixes) { - if (projectDirName === prefix || projectDirName.startsWith(`${prefix}-`)) { - return true - } - } - return false -} - function isCwdInsideScopePath(scopePath: string, cwd: string): boolean { if (isPathInsideOrEqual(scopePath, cwd)) { return true From 54afdb36acaf2f6e47b0bc6a944f9c61d2627de4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 17:42:54 -0700 Subject: [PATCH 08/20] fix(worktree): make the retirement seed scan actually match buckets The bucket encoder collapsed runs of non-alphanumerics while the real one emits a dash per character, so every dot-path bucket missed and the Windows default workspace root (C:\...) matched nothing at all. Reuse the shared encoder and its boundary check, which also stops a repo absorbing a sibling whose path merely shares its prefix. Also: - Derive the workspace leaf by stripping the known encoded parent instead of guessing from trailing dash segments, which retired the parent directory's name whenever a workspace was named numerically. - Reuse isAutoGeneratedCreatureBranchName so the -10 and -100 tiers retire. - Drop the .codex/sessions root: Codex keeps the cwd inside the transcript rather than in a directory name, so the scan could only ever see a year folder. Reading transcript contents is not a trade this feature justifies, so the gap is documented instead. - Honor CLAUDE_CONFIG_DIR, which relocates the bucket root. - Delete the unused retirableLeafName export. Tests write buckets with the real per-character encoding against a fake home, covering POSIX, dot-directory, Windows drive and WSL UNC roots; all three platform cases fail against the previous encoder. --- src/main/worktree-name-retirement.test.ts | 317 +++++++++++++++++----- src/main/worktree-name-retirement.ts | 262 +++++++++--------- 2 files changed, 365 insertions(+), 214 deletions(-) diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index 726adc6f70d9..52b23b35a4e7 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -1,110 +1,262 @@ -import { describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it } from 'vitest' import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { MARINE_CREATURES } from '../shared/marine-creatures' import type { GlobalSettings, Repo } from '../shared/types' import { - collectRetiredNamesFromPaths, + collectRetiredNamesFromLeafNames, + discoverRetiredWorktreeNames, ensureRetiredWorktreeNamesBackfilled, - extractCandidateLeafNames, + extractBucketLeafCandidates, getRetiredWorktreeNamesForRepo, - normalizeRetirableGeneratedName + normalizeRetirableGeneratedName, + resetRetirementCollisionKeyCacheForTests, + retireGeneratedWorktreeName } from './worktree-name-retirement' const FIRST = MARINE_CREATURES[0].toLowerCase() const SECOND = MARINE_CREATURES[1].toLowerCase() -describe('extractCandidateLeafNames', () => { - it('takes the trailing segment of a real path', () => { - expect(extractCandidateLeafNames(`/Users/ada/orca/workspaces/orca/${FIRST}`)).toEqual([FIRST]) +const makeRepo = (id: string, path: string): Repo => + ({ id, path, displayName: id, badgeColor: '', addedAt: 0 }) as Repo + +beforeEach(() => { + resetRetirementCollisionKeyCacheForTests() +}) + +describe('normalizeRetirableGeneratedName', () => { + it('accepts pool names and every numbered tier, not just single digits', () => { + expect(normalizeRetirableGeneratedName(` ${FIRST} `)).toBe(FIRST) + expect(normalizeRetirableGeneratedName(`${FIRST}-2`)).toBe(`${FIRST}-2`) + // Why: the previous `-([2-9]\d*)` never matched these, so a path whose agent history was + // still on disk got reissued — the exact bug this module exists to prevent. + expect(normalizeRetirableGeneratedName(`${FIRST}-10`)).toBe(`${FIRST}-10`) + expect(normalizeRetirableGeneratedName(`${FIRST}-100`)).toBe(`${FIRST}-100`) + }) + + it('rejects names outside the pool and absurdly long input', () => { + expect(normalizeRetirableGeneratedName('fix-login')).toBeNull() + expect(normalizeRetirableGeneratedName('')).toBeNull() + expect(normalizeRetirableGeneratedName(`${FIRST}-${'9'.repeat(300)}`)).toBeNull() }) +}) - it('takes the trailing segment of a dash-encoded transcript bucket', () => { - expect(extractCandidateLeafNames(`-Users-ada-orca-workspaces-orca-${FIRST}`)).toEqual([FIRST]) +describe('extractBucketLeafCandidates', () => { + it('takes everything past the encoded parent as the leaf', () => { + expect(extractBucketLeafCandidates(`-w-orca-${FIRST}`, ['-w-orca'])).toEqual([FIRST]) }) - it('keeps a numeric tail attached so suffixed variants retire as themselves', () => { - // Why: returning only the base would retire "gar" and leave "gar-2" issuable. - expect(extractCandidateLeafNames(`-Users-ada-worktrees-${FIRST}-2`)).toEqual([ - `${FIRST}-2`, + it('does not treat the parent directory as a leaf when the workspace name is numeric', () => { + // Real data: `-Users-x-orca-workspaces-orca-7474` must not retire `orca`, which is in the pool. + expect(extractBucketLeafCandidates('-w-workspaces-orca-7474', ['-w-workspaces-orca'])).toEqual([ + '7474' + ]) + }) + + it('offers the first segment too, so an agent run in a subdirectory still retires the leaf', () => { + expect(extractBucketLeafCandidates(`-w-orca-${FIRST}-packages-api`, ['-w-orca'])).toEqual([ + `${FIRST}-packages-api`, FIRST ]) }) - it('handles Windows separators and trailing separators', () => { - expect(extractCandidateLeafNames(`C:\\worktrees\\${FIRST}\\`)).toEqual([FIRST]) + it('rejects a sibling directory that shares the parent prefix', () => { + expect(extractBucketLeafCandidates(`-w-orcadyne-${FIRST}`, ['-w-orca'])).toEqual([]) + expect(extractBucketLeafCandidates(`-w-orca-secret-${FIRST}`, ['-w-orca-fix'])).toEqual([]) }) - it('returns nothing for an empty or separator-only input', () => { - expect(extractCandidateLeafNames('')).toEqual([]) - expect(extractCandidateLeafNames('---')).toEqual([]) + it('yields nothing for the parent bucket itself', () => { + expect(extractBucketLeafCandidates('-w-orca', ['-w-orca'])).toEqual([]) }) }) -describe('collectRetiredNamesFromPaths', () => { - it('retires pool names found in live workspace directories', () => { - expect(collectRetiredNamesFromPaths([FIRST, SECOND])).toEqual(new Set([FIRST, SECOND])) +describe('collectRetiredNamesFromLeafNames', () => { + it('keeps pool names and drops everything else', () => { + expect(collectRetiredNamesFromLeafNames([FIRST, SECOND, 'fix-login'])).toEqual( + new Set([FIRST, SECOND]) + ) }) - it('retires a name whose directory is gone but whose transcript bucket survives', () => { - // The core case: this is the evidence that a deleted workspace left agent state behind. - expect(collectRetiredNamesFromPaths([`-Users-ada-orca-workspaces-orca-${FIRST}`])).toEqual( - new Set([FIRST]) - ) + it('is case-insensitive and skips non-string entries without throwing', () => { + const leaves = [undefined, null, '', MARINE_CREATURES[0].toUpperCase()] as unknown as string[] + expect(collectRetiredNamesFromLeafNames(leaves)).toEqual(new Set([FIRST])) + }) +}) + +describe('discoverRetiredWorktreeNames', () => { + /** Buckets are written with the REAL per-character encoding, because a helper that mirrors the + * implementation would pass against a broken encoder — which is how the Windows gap shipped. */ + async function withFakeHome( + buckets: readonly string[], + run: (home: string) => Promise + ): Promise { + const home = await mkdtemp(join(tmpdir(), 'orca-retirement-home-')) + try { + for (const bucket of buckets) { + await mkdir(join(home, '.claude', 'projects', bucket), { recursive: true }) + } + await run(home) + } finally { + await rm(home, { force: true, recursive: true }) + } + } + + it('matches a plain POSIX workspace root', async () => { + await withFakeHome([`-Users-ada-orca-workspaces-orca-${FIRST}`], async (home) => { + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['/Users/ada/orca/workspaces/orca'], + home, + env: {} + }) + expect(retired).toEqual(new Set([FIRST])) + }) }) - it('retires a suffixed variant without also freeing it', () => { - const retired = collectRetiredNamesFromPaths([`-Users-ada-worktrees-${FIRST}-2`]) - expect(retired.has(`${FIRST}-2`)).toBe(true) + it('matches a dot-directory root, where the separator run encodes to two dashes', async () => { + await withFakeHome([`-Users-ada--orca-worktrees-${FIRST}`], async (home) => { + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['/Users/ada/.orca/worktrees'], + home, + env: {} + }) + expect(retired).toEqual(new Set([FIRST])) + }) }) - it('ignores paths that contain no pool name', () => { - expect( - collectRetiredNamesFromPaths(['-Users-ada-orca-workspaces-orca-fix-login-redirect']) - ).toEqual(new Set()) + it('matches a Windows drive root', async () => { + // `getDefaultWorkspaceDir` returns `C:\Users\\orca\workspaces` on Windows, so an encoder + // that collapsed `:\` rejected every bucket on that platform by default. + await withFakeHome([`C--Users-ada-orca-workspaces-${FIRST}`], async (home) => { + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['C:\\Users\\ada\\orca\\workspaces'], + home, + env: {} + }) + expect(retired).toEqual(new Set([FIRST])) + }) }) - it('is case-insensitive', () => { - expect(collectRetiredNamesFromPaths([MARINE_CREATURES[0].toUpperCase()])).toEqual( - new Set([FIRST]) + it('matches a WSL UNC root', async () => { + await withFakeHome([`--wsl--Ubuntu-home-ada-orca-workspaces-${FIRST}`], async (home) => { + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['\\\\wsl$\\Ubuntu\\home\\ada\\orca\\workspaces'], + home, + env: {} + }) + expect(retired).toEqual(new Set([FIRST])) + }) + }) + + it('ignores buckets belonging to a sibling root with the same prefix', async () => { + await withFakeHome( + [`-Users-ada-orca-workspaces-orcadyne-${FIRST}`, `-Users-ada-orca-workspaces-orca-${SECOND}`], + async (home) => { + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['/Users/ada/orca/workspaces/orca'], + home, + env: {} + }) + expect(retired).toEqual(new Set([SECOND])) + } ) }) - it('skips non-string and empty entries without throwing', () => { - const paths = [undefined, null, '', FIRST] as unknown as string[] - expect(collectRetiredNamesFromPaths(paths)).toEqual(new Set([FIRST])) + it('reads buckets from CLAUDE_CONFIG_DIR when it is set', async () => { + const configDir = await mkdtemp(join(tmpdir(), 'orca-retirement-config-')) + await withFakeHome([`-Users-ada-w-${SECOND}`], async (home) => { + try { + await mkdir(join(configDir, 'projects', `-Users-ada-w-${FIRST}`), { recursive: true }) + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: ['/Users/ada/w'], + home, + env: { CLAUDE_CONFIG_DIR: configDir } + }) + // The override relocates the whole state root, so the default home is not also scanned. + expect(retired).toEqual(new Set([FIRST])) + } finally { + await rm(configDir, { force: true, recursive: true }) + } + }) }) -}) -describe('normalizeRetirableGeneratedName', () => { - it('accepts only generated pool names and their numbered variants', () => { - expect(normalizeRetirableGeneratedName(` ${FIRST} `)).toBe(FIRST) - expect(normalizeRetirableGeneratedName(`${FIRST}-2`)).toBe(`${FIRST}-2`) - expect(normalizeRetirableGeneratedName('fix-login')).toBeNull() - expect(normalizeRetirableGeneratedName(`${FIRST}-1`)).toBeNull() + it('retires live workspace directories alongside surviving buckets', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-retirement-roots-')) + await withFakeHome([], async (home) => { + try { + await mkdir(join(root, SECOND), { recursive: true }) + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: [root], + home, + env: {} + }) + expect(retired).toEqual(new Set([SECOND])) + } finally { + await rm(root, { force: true, recursive: true }) + } + }) }) }) describe('getRetiredWorktreeNamesForRepo', () => { - const makeRepo = (id: string, path: string): Repo => - ({ id, path, displayName: id, badgeColor: '', addedAt: 0 }) as Repo - const store = { - getRetiredWorktreeNames: (repoId: string) => (repoId === 'repo-a' ? [FIRST] : [SECOND]) - } + const settingsFor = (nestWorkspaces: boolean): GlobalSettings => + ({ workspaceDir: '/workspaces', nestWorkspaces }) as GlobalSettings - it('shares retirements when non-nested repos create into the same cwd namespace', () => { - const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - const settings = { workspaceDir: '/workspaces', nestWorkspaces: false } as GlobalSettings - expect(getRetiredWorktreeNamesForRepo(store, repos[1], repos, settings).sort()).toEqual( - [FIRST, SECOND].sort() - ) + it('shares retirements when two repos create into the same cwd namespace', () => { + const byKey = new Map() + const store = { + getRetiredWorktreeNames: (key: string) => byKey.get(key) ?? [], + addRetiredWorktreeName: (key: string, name: string) => + byKey.set(key, [...(byKey.get(key) ?? []), name]) + } + const settings = settingsFor(false) + const repoA = makeRepo('repo-a', '/repos/a') + const repoB = makeRepo('repo-b', '/repos/b') + + retireGeneratedWorktreeName(store, repoA, settings, FIRST) + + expect(getRetiredWorktreeNamesForRepo(store, repoB, settings)).toEqual([FIRST]) }) it('keeps independent nested repo paths in separate retirement domains', () => { - const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - const settings = { workspaceDir: '/workspaces', nestWorkspaces: true } as GlobalSettings - expect(getRetiredWorktreeNamesForRepo(store, repos[1], repos, settings)).toEqual([SECOND]) + const byKey = new Map() + const store = { + getRetiredWorktreeNames: (key: string) => byKey.get(key) ?? [], + addRetiredWorktreeName: (key: string, name: string) => + byKey.set(key, [...(byKey.get(key) ?? []), name]) + } + const settings = settingsFor(true) + const repoA = makeRepo('repo-a', '/repos/a') + const repoB = makeRepo('repo-b', '/repos/b') + + retireGeneratedWorktreeName(store, repoA, settings, FIRST) + + expect(getRetiredWorktreeNamesForRepo(store, repoB, settings)).toEqual([]) + expect(getRetiredWorktreeNamesForRepo(store, repoA, settings)).toEqual([FIRST]) + }) + + it('survives a repo being removed and re-added under a new id', () => { + // Why: repo ids are regenerated on re-add. Keying the registry by repo id silently dropped + // every retirement for a path that had not changed at all. + const byKey = new Map() + const store = { + getRetiredWorktreeNames: (key: string) => byKey.get(key) ?? [], + addRetiredWorktreeName: (key: string, name: string) => + byKey.set(key, [...(byKey.get(key) ?? []), name]) + } + const settings = settingsFor(true) + + retireGeneratedWorktreeName(store, makeRepo('repo-old', '/repos/a'), settings, FIRST) + + expect( + getRetiredWorktreeNamesForRepo(store, makeRepo('repo-new', '/repos/a'), settings) + ).toEqual([FIRST]) + }) + + it('reports nothing for a folder workspace, which has no generated worktree names', () => { + const store = { getRetiredWorktreeNames: () => [FIRST] } + const folderRepo = { ...makeRepo('folder', '/repos/folder'), kind: 'folder' as const } + expect(getRetiredWorktreeNamesForRepo(store, folderRepo, settingsFor(false))).toEqual([]) }) }) @@ -113,29 +265,44 @@ describe('ensureRetiredWorktreeNamesBackfilled', () => { const root = await mkdtemp(join(tmpdir(), 'orca-retirement-backfill-')) const workspaceRoot = join(root, 'workspaces') await mkdir(join(workspaceRoot, FIRST), { recursive: true }) - const merged: string[] = [] + const merged: { key: string; names: string[] }[] = [] const store = { - mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { - merged.push(...names) + mergeRetiredWorktreeNames: (key: string, names: Iterable) => { + merged.push({ key, names: [...names] }) return true } } - const repo = { - id: 'repo-a', - path: join(root, 'repos', 'a'), - displayName: 'repo-a', - badgeColor: '', - addedAt: 0 - } as Repo + const repo = makeRepo('repo-a', join(root, 'repos', 'a')) + const settings = { workspaceDir: workspaceRoot, nestWorkspaces: false } try { - await ensureRetiredWorktreeNamesBackfilled(store, repo, { - workspaceDir: workspaceRoot, - nestWorkspaces: false - }) - expect(merged).toContain(FIRST) + await ensureRetiredWorktreeNamesBackfilled(store, repo, settings) + expect(merged).toHaveLength(1) + expect(merged[0].names).toContain(FIRST) + + // A second repo in the same namespace reuses the one in-flight scan. + await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-b', '/repos/b'), settings) + expect(merged).toHaveLength(1) } finally { await rm(root, { force: true, recursive: true }) } }) + + it('skips repos whose agent state lives on another host', async () => { + const merged: string[] = [] + const store = { + mergeRetiredWorktreeNames: (_key: string, names: Iterable) => { + merged.push(...names) + return true + } + } + const sshRepo = { ...makeRepo('repo-ssh', '/remote/repo'), connectionId: 'ssh-1' } + + await ensureRetiredWorktreeNamesBackfilled(store, sshRepo, { + workspaceDir: '/workspaces', + nestWorkspaces: false + }) + + expect(merged).toEqual([]) + }) }) diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index 04ee3d253eae..7698270bc373 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -1,10 +1,14 @@ import { readdir } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' -import { MARINE_CREATURES } from '../shared/marine-creatures' +import { isAutoGeneratedCreatureBranchName } from '../shared/branch-name-from-work' import { getRepoExecutionHostId } from '../shared/execution-host' import { isFolderRepo } from '../shared/repo-kind' import type { GlobalSettings, Repo } from '../shared/types' +import { + encodeClaudeProjectPath, + isClaudeProjectDirInScope +} from './ai-vault/claude-project-dir-encoding' import { computeRemoteWorktreePath, computeWorktreePath, @@ -13,74 +17,69 @@ import { } from './ipc/worktree-logic' import { worktreePathComparisonKey } from './ipc/worktree-path-comparison' -/** Agent CLIs bucket their per-conversation state under a directory derived from the workspace - * cwd. A bucket surviving its workspace is exactly the evidence we need: the name was used, the - * directory is gone, and reissuing the name would hand the next occupant that conversation. */ -const AGENT_TRANSCRIPT_ROOTS = ['.claude/projects', '.codex/sessions'] as const - -const POOL_NAMES: ReadonlySet = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) const RETIREMENT_PROBE_NAME = 'orca-retirement-probe' const backfillsByStore = new WeakMap>>() -type RetirementStore = { - getRetiredWorktreeNames?(repoId: string): string[] - mergeRetiredWorktreeNames?(repoId: string, names: Iterable): boolean +type RetirementReadStore = { + getRetiredWorktreeNames(collisionKey: string): string[] +} +type RetirementWriteStore = { + addRetiredWorktreeName(collisionKey: string, name: string): void +} +type RetirementBackfillStore = { + mergeRetiredWorktreeNames(collisionKey: string, names: Iterable): boolean } type RetirementPathSettings = Pick +/** Why reuse the auto-rename predicate: it already defines "a name Orca picked, not the user", is + * already tested, and a second definition here drifted — its `-([2-9]\d*)` never matched `-10`. */ export function normalizeRetirableGeneratedName(name: string): string | null { const normalized = name.trim().toLowerCase() if (normalized.length > 256) { return null } - const match = normalized.match(/^(.+?)(?:-([2-9]\d*))?$/) - return match && POOL_NAMES.has(match[1]) ? normalized : null -} - -/** Why: worktree paths reaching retirement can be native, WSL, or SSH-host paths, so the leaf is - * taken separator-agnostically rather than through a platform-bound basename. */ -export function retirableLeafName(path: string): string { - const segments = path.split(/[/\\]/).filter((segment) => segment.trim().length > 0) - return segments.at(-1) ?? '' -} - -/** Bucket names encode a path with separators and dots flattened to dashes, so the workspace leaf - * is the trailing segment. A numeric tail is a suffixed variant ("gar-2") and must be kept whole, - * otherwise the base name alone gets retired and the variant stays issuable. */ -export function extractCandidateLeafNames(encodedPath: string): string[] { - const segments = encodedPath - .split(/[-/\\]/) - .map((segment) => segment.trim().toLowerCase()) - .filter((segment) => segment.length > 0) - const last = segments.at(-1) - if (last === undefined) { - return [] - } - const previous = segments.at(-2) - if (previous && /^\d+$/.test(last)) { - return [`${previous}-${last}`, previous] - } - return [last] + return isAutoGeneratedCreatureBranchName(normalized) ? normalized : null } /** Why: over-retiring costs one name from a 552-entry pool; under-retiring reissues a path whose * agent history is still on disk. So this matches generously and never tries to be exact. */ -export function collectRetiredNamesFromPaths(paths: Iterable): Set { +export function collectRetiredNamesFromLeafNames(leafNames: Iterable): Set { const retired = new Set() - for (const path of paths) { - if (typeof path !== 'string' || path.length === 0) { + for (const leafName of leafNames) { + if (typeof leafName !== 'string' || leafName.length === 0) { continue } - for (const candidate of extractCandidateLeafNames(path)) { - const normalized = normalizeRetirableGeneratedName(candidate) - if (normalized) { - retired.add(normalized) - } + const normalized = normalizeRetirableGeneratedName(leafName) + if (normalized) { + retired.add(normalized) } } return retired } +/** The workspace leaf is whatever the bucket has beyond its encoded parent. Deriving it from + * trailing dash segments instead makes a numerically named workspace retire its parent + * directory's name — and `orca` is in the pool. The first segment is also offered because an + * agent run from a subdirectory buckets the whole subpath. */ +export function extractBucketLeafCandidates( + bucketName: string, + encodedParents: readonly string[] +): string[] { + const bucket = bucketName.toLowerCase() + for (const parent of encodedParents) { + if (!parent || bucket === parent || !isClaudeProjectDirInScope(bucket, [parent])) { + continue + } + const remainder = bucket.slice(parent.length + 1) + if (!remainder) { + continue + } + const firstSegment = remainder.split('-')[0] + return remainder === firstSegment ? [remainder] : [remainder, firstSegment] + } + return [] +} + function getRetirementProbePath(repo: Repo, settings: RetirementPathSettings): string { const pathSettings = getWorktreePathSettings(repo, settings) return repo.connectionId @@ -90,82 +89,61 @@ function getRetirementProbePath(repo: Repo, settings: RetirementPathSettings): s : computeWorktreePath(RETIREMENT_PROBE_NAME, repo.path, pathSettings) } -function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSettings): string { - return `${getRepoExecutionHostId(repo)}:${worktreePathComparisonKey( - getRetirementProbePath(repo, settings) - )}` +// Why: for a WSL repo the probe path costs a blocking `wsl.exe` call, and the create path plus +// every suggestion refresh asks for the same key. Inputs are all the key derives from. +const COLLISION_KEY_CACHE_MAX = 512 +const collisionKeyCache = new Map() + +export function resetRetirementCollisionKeyCacheForTests(): void { + collisionKeyCache.clear() +} + +/** Identifies the cwd namespace a repo creates workspaces into. Two repos that would place a + * workspace of the same name at the same path share retirements; independent paths do not. */ +export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSettings): string { + const hostId = getRepoExecutionHostId(repo) + const cacheKey = [ + hostId, + repo.path, + repo.worktreeBasePath ?? '', + settings.workspaceDir, + settings.nestWorkspaces ? 'nested' : 'flat' + ].join('\u0000') + const cached = collisionKeyCache.get(cacheKey) + if (cached !== undefined) { + return cached + } + const key = `${hostId}:${worktreePathComparisonKey(getRetirementProbePath(repo, settings))}` + if (collisionKeyCache.size >= COLLISION_KEY_CACHE_MAX) { + collisionKeyCache.clear() + } + collisionKeyCache.set(cacheKey, key) + return key } export function getRetiredWorktreeNamesForRepo( - store: RetirementStore, + store: RetirementReadStore, repo: Repo, - repos: readonly Repo[], settings: RetirementPathSettings ): string[] { - const getRetiredNames = store.getRetiredWorktreeNames?.bind(store) - if (!getRetiredNames) { + if (isFolderRepo(repo)) { return [] } - const collisionKey = getRetirementCollisionKey(repo, settings) - const names = new Set() - for (const candidate of repos) { - if ( - isFolderRepo(candidate) || - getRetirementCollisionKey(candidate, settings) !== collisionKey - ) { - continue - } - for (const name of getRetiredNames(candidate.id)) { - names.add(name) - } - } - return [...names] + return store.getRetiredWorktreeNames(getRetirementCollisionKey(repo, settings)) } -export function getRetiredWorktreeNamesByRepo( - store: RetirementStore, - repoIds: Iterable, - repos: readonly Repo[], - settings: RetirementPathSettings -): Record { - const getRetiredNames = store.getRetiredWorktreeNames?.bind(store) - if (!getRetiredNames) { - return {} - } - const namesByCollisionKey = new Map>() - for (const candidate of repos) { - if (isFolderRepo(candidate)) { - continue - } - const retiredNames = getRetiredNames(candidate.id) - if (retiredNames.length === 0) { - continue - } - const collisionKey = getRetirementCollisionKey(candidate, settings) - let names = namesByCollisionKey.get(collisionKey) - if (!names) { - names = new Set() - namesByCollisionKey.set(collisionKey, names) - } - for (const name of retiredNames) { - names.add(name) - } - } - if (namesByCollisionKey.size === 0) { - return {} - } - const requestedRepoIds = new Set(repoIds) - const byRepo: Record = {} - for (const repo of repos) { - if (!requestedRepoIds.has(repo.id) || isFolderRepo(repo)) { - continue - } - const names = namesByCollisionKey.get(getRetirementCollisionKey(repo, settings)) - if (names?.size) { - byRepo[repo.id] = [...names] - } +/** Records the name main actually used, not the one the client proposed — the create path can + * advance past a taken candidate. Call only for names Orca generated. */ +export function retireGeneratedWorktreeName( + store: RetirementWriteStore, + repo: Repo, + settings: RetirementPathSettings, + name: string +): void { + if (isFolderRepo(repo)) { + return } - return byRepo + store.addRetiredWorktreeName(getRetirementCollisionKey(repo, settings), name) } function parentPath(path: string): string { @@ -175,12 +153,12 @@ function parentPath(path: string): string { } export function ensureRetiredWorktreeNamesBackfilled( - store: RetirementStore, + store: RetirementBackfillStore, repo: Repo, settings: RetirementPathSettings ): Promise { - const mergeRetiredNames = store.mergeRetiredWorktreeNames?.bind(store) - if (isFolderRepo(repo) || repo.connectionId || !mergeRetiredNames) { + // Remote workspaces keep their agent state on the execution host, which this scan cannot see. + if (isFolderRepo(repo) || repo.connectionId) { return Promise.resolve() } let storeBackfills = backfillsByStore.get(store) @@ -196,26 +174,12 @@ export function ensureRetiredWorktreeNamesBackfilled( const backfill = discoverRetiredWorktreeNames({ workspaceRoots: [parentPath(getRetirementProbePath(repo, settings))] }).then((names) => { - mergeRetiredNames(repo.id, names) + store.mergeRetiredWorktreeNames(collisionKey, names) }) storeBackfills.set(collisionKey, backfill) return backfill } -/** Transcript bucket names are the workspace cwd with every non-alphanumeric run flattened to a - * dash. Encoding the worktree parent keeps retirement scoped to the cwd collision domain. */ -export function encodePathForBucketMatch(path: string): string { - return path.replace(/[^a-zA-Z0-9]+/g, '-').toLowerCase() -} - -function bucketBelongsToParent(bucketName: string, encodedParents: readonly string[]): boolean { - if (encodedParents.length === 0) { - return true - } - const bucket = bucketName.toLowerCase() - return encodedParents.some((parent) => parent.length > 0 && bucket.startsWith(parent)) -} - async function readDirectoryNames(path: string): Promise { try { const entries = await readdir(path, { withFileTypes: true }) @@ -226,24 +190,44 @@ async function readDirectoryNames(path: string): Promise { } } +/** Claude buckets its per-conversation state under a directory derived from the workspace cwd. A + * bucket surviving its workspace is exactly the evidence we need: the name was used, the + * directory is gone, and reissuing the name would hand the next occupant that conversation. + * CLAUDE_CONFIG_DIR relocates the whole state root, buckets included. + * + * Codex is deliberately not scanned: it records the cwd inside + * `sessions/YYYY/MM/DD/rollout-*.jsonl` rather than in a directory name, so seeding from it would + * mean parsing user conversation files. Names spent only under Codex before this feature shipped + * stay issuable; every name spent after it is recorded at create time regardless of agent. */ +function getClaudeProjectsDir(home: string, env: NodeJS.ProcessEnv): string { + const override = env.CLAUDE_CONFIG_DIR?.trim() + return override ? join(override, 'projects') : join(home, '.claude', 'projects') +} + /** Discovers names already spent for a repo, for the one-time seed of the retirement registry. * Local and best-effort by design — agent state for an SSH workspace lives on the execution host, * so names used only there stay issuable until this host observes them. */ export async function discoverRetiredWorktreeNames(args: { workspaceRoots: readonly string[] home?: string + env?: NodeJS.ProcessEnv }): Promise> { - const home = args.home ?? homedir() - const observed: string[] = [] - const encodedParents = args.workspaceRoots.map(encodePathForBucketMatch) - + const leafNames: string[] = [] for (const root of args.workspaceRoots) { - observed.push(...(await readDirectoryNames(root))) - } - for (const relativeRoot of AGENT_TRANSCRIPT_ROOTS) { - const buckets = await readDirectoryNames(join(home, ...relativeRoot.split('/'))) - observed.push(...buckets.filter((bucket) => bucketBelongsToParent(bucket, encodedParents))) + leafNames.push(...(await readDirectoryNames(root))) + } + + // Lowercased on both sides: the recorded cwd can differ in case from ours on case-insensitive + // filesystems, and a missed bucket reissues a live path while a spurious one costs one name. + const encodedParents = args.workspaceRoots + .filter((root) => root.length > 0) + .map((root) => encodeClaudeProjectPath(root).toLowerCase()) + if (encodedParents.length > 0) { + const projectsDir = getClaudeProjectsDir(args.home ?? homedir(), args.env ?? process.env) + for (const bucket of await readDirectoryNames(projectsDir)) { + leafNames.push(...extractBucketLeafCandidates(bucket, encodedParents)) + } } - return collectRetiredNamesFromPaths(observed) + return collectRetiredNamesFromLeafNames(leafNames) } From 5aef758fb0aa2c21a68d5412d3aa94af4a6382c5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 17:43:31 -0700 Subject: [PATCH 09/20] fix(worktree): retire only generated names, keyed by cwd namespace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two problems in the host-side registry. Retirement fired for every create, including names the user typed. The creature pool contains ordinary words — orca, runner, sole, molly, oscar — so typing a retired 'nautilus' silently produced directory and branch 'nautilus-2' and burned the name for good. Creates now carry an explicit nameWasGenerated flag; both the skip and the retire are gated on it, and it defaults to false so CLI and automation callers are unaffected. The registry was keyed by repo id, but both readers already discarded the id and unioned by the cwd collision key, because the collision this prevents is on the path. Keying by that namespace directly fixes several things at once: entries no longer orphan when a repo is removed, remove/re-add no longer loses every retirement for an unchanged path, the missing removeProject prune is moot, and the backfill promise no longer merges into only the first repo id it saw. The feature is unreleased, so no migration is needed. Also: - Memoize the collision key. It runs computeWorktreePath, which for a WSL repo is a blocking execFileSync('wsl.exe') whose failure path is uncached, and the previous code recomputed it once per repo on every create and every listRetiredNames call. - Drop retiredNamesByRepo from the worktree list result. It had no readers and leaked onto 'orca worktree list --json', and its awaited backfill sat on CLI selector resolution. The dedicated listRetiredNames RPC keeps its consumers. - Make the three RuntimeStore methods required. RuntimeStore is file-private with two constructors, so the 'older embedders' the optionality protected do not exist, and the optional chain silently returned no retirements. - Revert the unrelated forceDeleteBranch rewrite, and make room under the file's line budget by extracting the create-args mapping instead. --- src/main/ipc/worktree-remote.ts | 33 ++++--- src/main/ipc/worktrees-windows.test.ts | 39 +++++++- src/main/ipc/worktrees.test.ts | 68 +++++++++++++- src/main/ipc/worktrees.ts | 2 +- ...rsistence-worktree-name-retirement.test.ts | 65 +++++++------- src/main/persistence.ts | 44 ++++----- .../runtime/fit-override-integration.test.ts | 3 + .../graph-sync-mobile-snapshot-gating.test.ts | 3 + .../graph-sync-payload-partition.test.ts | 3 + src/main/runtime/mobile-presence-lock.test.ts | 3 + .../mobile-subscribe-integration.test.ts | 3 + src/main/runtime/orca-runtime.test.ts | 38 +++++++- src/main/runtime/orca-runtime.ts | 89 ++++++------------ .../runtime/remote-desktop-driver.test.ts | 3 + .../rpc/methods/worktree-create-args.test.ts | 29 ++++++ .../rpc/methods/worktree-create-args.ts | 73 +++++++++++++++ .../runtime/rpc/methods/worktree-schemas.ts | 3 + src/main/runtime/rpc/methods/worktree.ts | 90 +++++-------------- .../runtime/terminal-query-responder.test.ts | 3 + src/shared/constants.ts | 2 +- src/shared/runtime-types.ts | 7 -- src/shared/types.ts | 15 +++- 22 files changed, 403 insertions(+), 215 deletions(-) create mode 100644 src/main/runtime/rpc/methods/worktree-create-args.test.ts create mode 100644 src/main/runtime/rpc/methods/worktree-create-args.ts diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 7c30336427cf..c4ea34e81d35 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -135,7 +135,10 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' -import { getRetiredWorktreeNamesForRepo } from '../worktree-name-retirement' +import { + getRetiredWorktreeNamesForRepo, + retireGeneratedWorktreeName +} from '../worktree-name-retirement' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1551,16 +1554,16 @@ export async function createRemoteWorktree( let selectedExistingLocalBranchName: string | null = null let lastBranchConflictKind: 'local' | 'remote' | null = null let remotePathResolved = false - const retiredNames = new Set( - getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings) - ) + const retiredNames = args.nameWasGenerated + ? new Set(getRetiredWorktreeNamesForRepo(store, repo, settings)) + : null // Why: duplicate PR/MR checkouts still need a workspace; suffix branch/path while preserving review metadata and push target. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) effectiveRequestedName = args.name.trim() ? getWorktreeCreateCandidate(args.name, suffix) : effectiveSanitizedName - if (retiredNames.has(effectiveSanitizedName)) { + if (retiredNames?.has(effectiveSanitizedName)) { continue } branchName = await resolveCreateBranchNameSsh( @@ -1768,8 +1771,10 @@ export async function createRemoteWorktree( } const worktreeId = `${repo.id}::${created.path}` - // Why: repo-qualified layouts decorate the physical leaf; retire the generated collision key. - store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) + // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. + if (args.nameWasGenerated) { + retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + } const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch @@ -2098,16 +2103,16 @@ export async function createLocalWorktree( let lastBranchConflictKind: 'local' | 'remote' | null = null let lastExistingPR: Awaited> | null = null let lastExistingReviewNumber: number | null = null - const retiredNames = new Set( - getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings) - ) + const retiredNames = args.nameWasGenerated + ? new Set(getRetiredWorktreeNamesForRepo(store, repo, settings)) + : null // Why: a create-from-review branch override may already exist locally; suffix both branch and path instead of blocking the user. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) effectiveRequestedName = requestedName.trim() ? getWorktreeCreateCandidate(requestedName, suffix) : effectiveSanitizedName - if (retiredNames.has(effectiveSanitizedName)) { + if (retiredNames?.has(effectiveSanitizedName)) { continue } lastExistingReviewNumber = null @@ -2393,8 +2398,10 @@ export async function createLocalWorktree( } const worktreeId = `${repo.id}::${created.path}` - // Why: repo-qualified layouts decorate the physical leaf; retire the generated collision key. - store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) + // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. + if (args.nameWasGenerated) { + retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + } const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index 32477a819984..189f2e551415 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -139,6 +139,7 @@ vi.mock('./worktree-logic', async (importOriginal) => { }) import { registerWorktreeHandlers } from './worktrees' +import { resetRetirementCollisionKeyCacheForTests } from '../worktree-name-retirement' type HandlerMap = Record unknown> @@ -206,6 +207,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { store.addRetiredWorktreeName.mockReset() store.getRetiredWorktreeNames.mockReset() store.mergeRetiredWorktreeNames.mockReset() + resetRetirementCollisionKeyCacheForTests() for (const key of Object.keys(handlers)) { delete handlers[key] @@ -309,7 +311,8 @@ describe('registerWorktreeHandlers – Windows path handling', () => { false ) expect(resolveLocalGitUsernameMock).not.toHaveBeenCalled() - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'improve-dashboard') + // A name the user typed is never retired — the pool holds ordinary words people choose. + expect(store.addRetiredWorktreeName).not.toHaveBeenCalled() expect(store.setWorktreeMeta).toHaveBeenCalledWith( 'repo-1::C:/workspaces/improve-dashboard', expect.objectContaining({ @@ -339,9 +342,41 @@ describe('registerWorktreeHandlers – Windows path handling', () => { } ]) + await handlers['worktrees:create'](null, { + repoId: 'repo-1', + name: 'nautilus', + nameWasGenerated: true + }) + + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith(expect.any(String), 'nautilus-2') + }) + + it('leaves a user-typed name reusable even when the same name is retired', async () => { + // Why: the creature pool contains ordinary words ("orca", "runner", "molly"). Silently + // renaming a deliberate `nautilus` to `nautilus-2` — and burning it — is the wrong trade. + store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + computeWorktreePathMock.mockReturnValue('C:\\workspaces\\nautilus') + ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\nautilus') + listWorktreesMock.mockResolvedValue([ + { + path: 'C:/workspaces/nautilus', + head: 'abc123', + branch: 'refs/heads/nautilus', + isBare: false, + isMainWorktree: false + } + ]) + await handlers['worktrees:create'](null, { repoId: 'repo-1', name: 'nautilus' }) - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'nautilus-2') + expect(addWorktreeMock).toHaveBeenCalledWith( + 'C:\\repo', + 'C:\\workspaces\\nautilus', + 'nautilus', + 'origin/main', + false + ) + expect(store.addRetiredWorktreeName).not.toHaveBeenCalled() }) it('resolves the Git username when the configured prefix consumes it', async () => { diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 8bf3c05595b4..460f6e62b85f 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -283,6 +283,7 @@ import { registerWorktreeHandlers } from './worktrees' import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../git/worktree-shared-directories' +import { resetRetirementCollisionKeyCacheForTests } from '../worktree-name-retirement' import { getSshProviderAuthority, resetSshProviderAuthorities, @@ -455,6 +456,7 @@ describe('registerWorktreeHandlers', () => { store.getWorktreeMeta.mockReturnValue(undefined) store.getAllWorktreeMeta.mockReturnValue({}) store.getRetiredWorktreeNames.mockReturnValue([]) + resetRetirementCollisionKeyCacheForTests() store.setWorktreeMeta.mockReturnValue({}) store.getProjectHostSetups.mockReturnValue([ { @@ -4689,14 +4691,13 @@ describe('registerWorktreeHandlers', () => { store.getRepo.mockReturnValue(repo) getSshGitProviderMock.mockReturnValue(provider) getActiveMultiplexerMock.mockReturnValue(mux) - store.getRetiredWorktreeNames.mockImplementation((repoId) => - repoId === 'repo-ssh' ? ['nautilus'] : [] - ) + store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) const result = await handlers['worktrees:create'](null, { repoId: 'repo-ssh', name: 'nautilus', + nameWasGenerated: true, linkedIssue: 123, linkedPR: 456, createdWithAgent: 'codex', @@ -4714,7 +4715,7 @@ describe('registerWorktreeHandlers', () => { ) expect(provider.listWorktrees).toHaveBeenCalledTimes(1) expect(provider.worktreeIsClean).not.toHaveBeenCalled() - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-ssh', 'nautilus-2') + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith(expect.any(String), 'nautilus-2') expect(store.setWorktreeMeta).toHaveBeenCalledWith( 'repo-ssh::/remote/repo-nautilus-2', expect.objectContaining({ @@ -4736,6 +4737,65 @@ describe('registerWorktreeHandlers', () => { }) }) + it('leaves a user-typed name reusable on the SSH create path', async () => { + // Why: `nautilus` is retired here, yet the user typed it — it must neither be skipped nor burned. + const repo = { + id: 'repo-ssh', + path: '/remote/repo', + displayName: 'ssh', + badgeColor: '#000', + addedAt: 0, + connectionId: 'conn-1', + worktreeBaseRef: 'origin/main' + } + const provider = { + exec: vi.fn().mockImplementation(async (args: string[]) => { + if (args[0] === 'remote') { + return { stdout: 'origin\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }), + fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined), + addWorktree: vi.fn().mockResolvedValue(undefined), + listWorktrees: vi.fn().mockResolvedValue([ + { + path: '/remote/repo', + head: 'base123', + branch: 'refs/heads/main', + isBare: false, + isMainWorktree: true + }, + { + path: '/remote/repo-nautilus', + head: 'abc123', + branch: 'refs/heads/nautilus', + isBare: false, + isMainWorktree: false + } + ]), + worktreeIsClean: vi.fn().mockResolvedValue({ clean: true }) + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue(repo) + getSshGitProviderMock.mockReturnValue(provider) + getActiveMultiplexerMock.mockReturnValue({ + request: vi.fn().mockResolvedValue(undefined), + notify: vi.fn() + }) + store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) + + const result = await handlers['worktrees:create'](null, { + repoId: 'repo-ssh', + name: 'nautilus' + }) + + expect(store.addRetiredWorktreeName).not.toHaveBeenCalled() + expect(result).toMatchObject({ + worktree: expect.objectContaining({ path: '/remote/repo-nautilus' }) + }) + }) + it('returns SSH local base refresh skip status when the owning worktree is dirty', async () => { const repo = { id: 'repo-ssh', diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 4c4b8aecba5d..13c164d248f2 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -1922,7 +1922,7 @@ export function registerWorktreeHandlers( // Best effort: without the seed we only under-retire, which is the pre-existing behavior. console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) } - return getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), store.getSettings()) + return getRetiredWorktreeNamesForRepo(store, repo, store.getSettings()) }) ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { diff --git a/src/main/persistence-worktree-name-retirement.test.ts b/src/main/persistence-worktree-name-retirement.test.ts index 79da3b51a74d..8e296c880d4b 100644 --- a/src/main/persistence-worktree-name-retirement.test.ts +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -13,8 +13,9 @@ vi.mock('electron', () => ({ vi.mock('./telemetry/client', () => ({ track: vi.fn() })) vi.mock('./telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) -const REPO = 'repo-1' -const OTHER_REPO = 'repo-2' +// The registry is keyed by the cwd namespace a repo creates into, not by repo id. +const KEY = 'local:posix:/workspaces/repo-1' +const OTHER_KEY = 'local:posix:/workspaces/repo-2' async function createStore(persisted: Record = {}) { mkdirSync(testState.dir, { recursive: true }) @@ -40,81 +41,81 @@ afterEach(() => { describe('worktree name retirement registry', () => { it('retains a retired name so it is never reissued', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, 'Nautilus') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + store.addRetiredWorktreeName(KEY, 'Nautilus') + expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) }) - it('scopes retirement per repo so one repo does not burn another pool', async () => { + it('scopes retirement per cwd namespace so one workspace root does not burn another', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, 'nautilus') - expect(store.getRetiredWorktreeNames(OTHER_REPO)).toEqual([]) + store.addRetiredWorktreeName(KEY, 'nautilus') + expect(store.getRetiredWorktreeNames(OTHER_KEY)).toEqual([]) }) it('normalizes case and whitespace so a name cannot be retired twice', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, ' NaUtIlUs ') - store.addRetiredWorktreeName(REPO, 'nautilus') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + store.addRetiredWorktreeName(KEY, ' NaUtIlUs ') + store.addRetiredWorktreeName(KEY, 'nautilus') + expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) }) - it('ignores an empty name or missing repo id', async () => { + it('ignores an empty name or missing workspace key', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, ' ') + store.addRetiredWorktreeName(KEY, ' ') store.addRetiredWorktreeName('', 'nautilus') - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + expect(store.getRetiredWorktreeNames(KEY)).toEqual([]) }) it('does not persist arbitrary user and issue-title names', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, 'fix-login-redirect') - store.addRetiredWorktreeName(REPO, 'STA-4189-duplicate-name') - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + store.addRetiredWorktreeName(KEY, 'fix-login-redirect') + store.addRetiredWorktreeName(KEY, 'STA-4189-duplicate-name') + expect(store.getRetiredWorktreeNames(KEY)).toEqual([]) }) it('returns a copy so callers cannot mutate the registry in place', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, 'nautilus') - store.getRetiredWorktreeNames(REPO).push('seahorse') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + store.addRetiredWorktreeName(KEY, 'nautilus') + store.getRetiredWorktreeNames(KEY).push('seahorse') + expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) }) it('merges backfilled names without dropping a concurrent retirement', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, 'nautilus') - expect(store.mergeRetiredWorktreeNames(REPO, ['seahorse', 'starfish'])).toBe(true) - expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse', 'starfish']) + store.addRetiredWorktreeName(KEY, 'nautilus') + expect(store.mergeRetiredWorktreeNames(KEY, ['seahorse', 'starfish'])).toBe(true) + expect(store.getRetiredWorktreeNames(KEY).sort()).toEqual(['nautilus', 'seahorse', 'starfish']) }) it('reports no change when a merge adds nothing new', async () => { const store = await createStore() - store.addRetiredWorktreeName(REPO, 'nautilus') - expect(store.mergeRetiredWorktreeNames(REPO, ['NAUTILUS'])).toBe(false) + store.addRetiredWorktreeName(KEY, 'nautilus') + expect(store.mergeRetiredWorktreeNames(KEY, ['NAUTILUS'])).toBe(false) }) it('survives a reload so retirement outlives the workspace and the app session', async () => { const store = await createStore({ - retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 'seahorse'] } + retiredWorktreeNamesByWorkspaceKey: { [KEY]: ['nautilus', 'seahorse'] } }) - expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + expect(store.getRetiredWorktreeNames(KEY).sort()).toEqual(['nautilus', 'seahorse']) }) it('degrades to nothing retired when the persisted map is corrupt', async () => { // Why: a load failure costs the app; over- or under-retiring costs at most a name. - const store = await createStore({ retiredWorktreeNamesByRepo: 'not-an-object' }) - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + const store = await createStore({ retiredWorktreeNamesByWorkspaceKey: 'not-an-object' }) + expect(store.getRetiredWorktreeNames(KEY)).toEqual([]) }) it('drops non-string entries but keeps the valid ones', async () => { const store = await createStore({ - retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 42, null, 'Seahorse'] } + retiredWorktreeNamesByWorkspaceKey: { [KEY]: ['nautilus', 42, null, 'Seahorse'] } }) - expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + expect(store.getRetiredWorktreeNames(KEY).sort()).toEqual(['nautilus', 'seahorse']) }) it('drops legacy arbitrary names while loading the persisted map', async () => { const store = await createStore({ - retiredWorktreeNamesByRepo: { [REPO]: ['fix-login', 'Nautilus'] } + retiredWorktreeNamesByWorkspaceKey: { [KEY]: ['fix-login', 'Nautilus'] } }) - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) }) }) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index c446afdd8013..22eea861a07d 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2337,13 +2337,13 @@ const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 /** Why: a corrupt or hand-edited map must degrade to "nothing retired" rather than throw during * load — over-retiring costs one name from a 552-entry pool, but a load failure costs the app. */ -function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record { +function normalizeRetiredWorktreeNamesByWorkspaceKey(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return {} } - const byRepo: Record = {} - for (const [repoId, names] of Object.entries(value as Record)) { - if (!repoId || !Array.isArray(names)) { + const byKey: Record = {} + for (const [workspaceKey, names] of Object.entries(value as Record)) { + if (!workspaceKey || !Array.isArray(names)) { continue } const seen = new Set() @@ -2357,10 +2357,10 @@ function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record 0) { - byRepo[repoId] = [...seen] + byKey[workspaceKey] = [...seen] } } - return byRepo + return byKey } function normalizeClaudeLivePtySessionIds(value: unknown): string[] { @@ -3848,8 +3848,8 @@ export class Store { (alias): alias is string => typeof alias === 'string' ) : [], - retiredWorktreeNamesByRepo: normalizeRetiredWorktreeNamesByRepo( - parsed.retiredWorktreeNamesByRepo + retiredWorktreeNamesByWorkspaceKey: normalizeRetiredWorktreeNamesByWorkspaceKey( + parsed.retiredWorktreeNamesByWorkspaceKey ), sshRemotePtyLeases: (parsed.sshRemotePtyLeases ?? []) .map(normalizeSshRemotePtyLease) @@ -7215,23 +7215,23 @@ export class Store { this.scheduleSave() } - getRetiredWorktreeNames(repoId: string): string[] { - return [...(this.state.retiredWorktreeNamesByRepo?.[repoId] ?? [])] + getRetiredWorktreeNames(workspaceKey: string): string[] { + return [...(this.state.retiredWorktreeNamesByWorkspaceKey?.[workspaceKey] ?? [])] } - /** Records a generated workspace name as spent for this repo. Called with the name main actually - * used, not the one the renderer proposed — the create path can advance past it on collision. */ - addRetiredWorktreeName(repoId: string, name: string): void { + /** Records a generated workspace name as spent in this cwd namespace. Called with the name main + * actually used, not the one the renderer proposed — create can advance past it on collision. */ + addRetiredWorktreeName(workspaceKey: string, name: string): void { const normalized = normalizeRetirableGeneratedName(name) - if (!repoId || !normalized) { + if (!workspaceKey || !normalized) { return } - this.state.retiredWorktreeNamesByRepo ??= {} - const existing = this.state.retiredWorktreeNamesByRepo[repoId] + this.state.retiredWorktreeNamesByWorkspaceKey ??= {} + const existing = this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] if (existing?.includes(normalized)) { return } - this.state.retiredWorktreeNamesByRepo[repoId] = existing + this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] = existing ? [...existing, normalized] : [normalized] this.scheduleSave() @@ -7239,8 +7239,8 @@ export class Store { /** Seeds retirements discovered by the one-time backfill. Merges rather than replaces so a * concurrent create during backfill is not lost. Returns true when anything was added. */ - mergeRetiredWorktreeNames(repoId: string, names: Iterable): boolean { - if (!repoId) { + mergeRetiredWorktreeNames(workspaceKey: string, names: Iterable): boolean { + if (!workspaceKey) { return false } const incoming = new Set() @@ -7253,8 +7253,8 @@ export class Store { if (incoming.size === 0) { return false } - this.state.retiredWorktreeNamesByRepo ??= {} - const existing = this.state.retiredWorktreeNamesByRepo[repoId] ?? [] + this.state.retiredWorktreeNamesByWorkspaceKey ??= {} + const existing = this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] ?? [] const merged = new Set(existing) for (const name of incoming) { merged.add(name) @@ -7262,7 +7262,7 @@ export class Store { if (merged.size === existing.length) { return false } - this.state.retiredWorktreeNamesByRepo[repoId] = [...merged] + this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] = [...merged] this.scheduleSave() return true } diff --git a/src/main/runtime/fit-override-integration.test.ts b/src/main/runtime/fit-override-integration.test.ts index 9bcfa8706143..98a3b1655052 100644 --- a/src/main/runtime/fit-override-integration.test.ts +++ b/src/main/runtime/fit-override-integration.test.ts @@ -64,6 +64,9 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts b/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts index 338535562a43..7228ac4e8f4d 100644 --- a/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts +++ b/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts @@ -54,6 +54,9 @@ const storeBase = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/graph-sync-payload-partition.test.ts b/src/main/runtime/graph-sync-payload-partition.test.ts index 6533a53f9fb1..3d73ad14dc49 100644 --- a/src/main/runtime/graph-sync-payload-partition.test.ts +++ b/src/main/runtime/graph-sync-payload-partition.test.ts @@ -31,6 +31,9 @@ const storeBase = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/mobile-presence-lock.test.ts b/src/main/runtime/mobile-presence-lock.test.ts index 517c038bd703..701f87847930 100644 --- a/src/main/runtime/mobile-presence-lock.test.ts +++ b/src/main/runtime/mobile-presence-lock.test.ts @@ -49,6 +49,9 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/mobile-subscribe-integration.test.ts b/src/main/runtime/mobile-subscribe-integration.test.ts index ceb178ee3623..75318ab8b511 100644 --- a/src/main/runtime/mobile-subscribe-integration.test.ts +++ b/src/main/runtime/mobile-subscribe-integration.test.ts @@ -70,6 +70,9 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index cc23e66d4193..5e8d0ca51883 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -4075,7 +4075,8 @@ describe('OrcaRuntimeService', () => { const staleLookup = runtime.showManagedWorktree(TEST_WORKTREE_ID) const result = await runtime.createManagedWorktree({ repoSelector: 'id:repo-1', - name: 'nautilus' + name: 'nautilus', + nameWasGenerated: true }) const freshLookup = runtime.showManagedWorktree(result.worktree.id) @@ -4091,7 +4092,37 @@ describe('OrcaRuntimeService', () => { worktrees: expect.arrayContaining([expect.objectContaining({ path: createdWorktree.path })]) } ) - expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus-2') + expect(addRetiredWorktreeName).toHaveBeenCalledWith(expect.any(String), 'nautilus-2') + }) + + it('neither skips nor retires a name the user typed', async () => { + // Why: the pool contains ordinary words. Retirement only ever applies to generated names. + const addRetiredWorktreeName = vi.fn() + const runtime = new OrcaRuntimeService({ + ...store, + addRetiredWorktreeName, + getRetiredWorktreeNames: () => ['nautilus'] + }) + const createdWorktree = { + path: '/tmp/workspaces/nautilus', + head: 'def', + branch: 'nautilus', + isBare: false, + isMainWorktree: false + } + computeWorktreePathMock.mockReturnValue(createdWorktree.path) + ensurePathWithinWorkspaceMock.mockReturnValue(createdWorktree.path) + // Not `...Once`: the shared beforeEach re-stubs the resolved value but cannot drain a queue, + // so leftover one-shots would poison later tests in this file. + vi.mocked(listWorktrees).mockResolvedValue([...MOCK_GIT_WORKTREES, createdWorktree]) + + const result = await runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'nautilus' + }) + + expect(result.worktree.path).toBe(createdWorktree.path) + expect(addRetiredWorktreeName).not.toHaveBeenCalled() }) it('creates additional workspace metadata for folder-mode repos through runtime create', async () => { @@ -48342,6 +48373,9 @@ describe('OrcaRuntimeService', () => { return nextMeta }, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getGitHubCache: () => undefined as never, getSettings: () => ({ workspaceDir: 'C:\\workspaces', diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 822c6ea70502..bc092758e666 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -935,8 +935,8 @@ import { } from '../worktree-create-candidates' import { ensureRetiredWorktreeNamesBackfilled, - getRetiredWorktreeNamesByRepo, - getRetiredWorktreeNamesForRepo + getRetiredWorktreeNamesForRepo, + retireGeneratedWorktreeName } from '../worktree-name-retirement' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' @@ -1114,11 +1114,9 @@ export type CodexRateLimitResetRpcResult = { type RuntimeStore = { getRepos: Store['getRepos'] getRepo: Store['getRepo'] - /** Optional so older embedders of RuntimeStore keep type-checking; the create path skips - * retirement when absent, which only means a name stays issuable. */ - addRetiredWorktreeName?: Store['addRetiredWorktreeName'] - getRetiredWorktreeNames?: Store['getRetiredWorktreeNames'] - mergeRetiredWorktreeNames?: Store['mergeRetiredWorktreeNames'] + addRetiredWorktreeName: Store['addRetiredWorktreeName'] + getRetiredWorktreeNames: Store['getRetiredWorktreeNames'] + mergeRetiredWorktreeNames: Store['mergeRetiredWorktreeNames'] addRepo: Store['addRepo'] updateRepo: Store['updateRepo'] getProjects?: Store['getProjects'] @@ -21046,24 +21044,8 @@ export class OrcaRuntimeService { if (!Number.isInteger(limit) || limit <= 0) { throw new Error('invalid_limit') } - const selectedRepo = repoSelector ? await this.resolveRepoSelector(repoSelector) : null - if ( - selectedRepo && - this.store?.getRetiredWorktreeNames && - this.store.mergeRetiredWorktreeNames - ) { - try { - await ensureRetiredWorktreeNamesBackfilled( - this.store, - selectedRepo, - this.store.getSettings() - ) - } catch (error) { - console.warn(`[runtime] retirement backfill failed for repo ${selectedRepo.id}:`, error) - } - } const resolved = await this.listResolvedWorktrees() - const repoId = selectedRepo?.id ?? null + const repoId = repoSelector ? (await this.resolveRepoSelector(repoSelector)).id : null const visibilitySourceMatchersByRepoId = this.buildRuntimeVisibilitySourceMatchersByRepoId(resolved) const worktrees = resolved.filter((worktree) => { @@ -21075,48 +21057,28 @@ export class OrcaRuntimeService { visibilitySourceMatchersByRepoId.get(worktree.repoId) ) }) - const page = worktrees.slice(0, limit) - const retirementRepoIds = new Set(page.map((worktree) => worktree.repoId)) - // Why: an explicitly selected repo must report its retirements even when the page is empty or - // truncated past it. A repo with no live workspaces is exactly the case where every generated - // name looks free, so omitting it would reissue names precisely where it matters most. - if (repoId) { - retirementRepoIds.add(repoId) - } return { - worktrees: page, + worktrees: worktrees.slice(0, limit), totalCount: worktrees.length, - truncated: worktrees.length > limit, - retiredNamesByRepo: this.collectRetiredNamesForRepos(retirementRepoIds) + truncated: worktrees.length > limit } } + /** Keyed by repo id on the wire even though one repo is requested: the caller asked by selector + * and needs to know which repo answered. */ async listRetiredWorktreeNames(repoSelector: string): Promise> { const store = this.store - if (!store?.getRetiredWorktreeNames) { + if (!store) { return {} } const repo = await this.resolveRepoSelector(repoSelector) - if (store.mergeRetiredWorktreeNames) { - try { - await ensureRetiredWorktreeNamesBackfilled(store, repo, store.getSettings()) - } catch (error) { - console.warn(`[runtime] retirement backfill failed for repo ${repo.id}:`, error) - } - } - return this.collectRetiredNamesForRepos(new Set([repo.id])) - } - - /** Why: scoped to the repos in the page plus any explicitly requested one, so the payload cannot - * grow with the number of repos on the host; a client only suggests names for repos it sees. */ - private collectRetiredNamesForRepos(repoIds: Set): Record { - const store = this.store - if (!store?.getRetiredWorktreeNames) { - return {} - } - const repos = store.getRepos() const settings = store.getSettings() - return getRetiredWorktreeNamesByRepo(store, repoIds, repos, settings) + try { + await ensureRetiredWorktreeNamesBackfilled(store, repo, settings) + } catch (error) { + console.warn(`[runtime] retirement backfill failed for repo ${repo.id}:`, error) + } + return { [repo.id]: getRetiredWorktreeNamesForRepo(store, repo, settings) } } async listDetectedManagedWorktrees( @@ -21961,6 +21923,9 @@ export class OrcaRuntimeService { async createManagedWorktree(args: { repoSelector: string name: string + /** True only when `name` came from Orca's creature-name generator; gates retirement so a name + * the user typed stays reusable. Absent for CLI and automation callers. */ + nameWasGenerated?: boolean baseBranch?: string compareBaseRef?: string branchNameOverride?: string @@ -22298,9 +22263,9 @@ export class OrcaRuntimeService { let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false - const retiredNames = new Set( - getRetiredWorktreeNamesForRepo(this.store, repo, this.store.getRepos(), settings) - ) + const retiredNames = args.nameWasGenerated + ? new Set(getRetiredWorktreeNamesForRepo(this.store, repo, settings)) + : null // Why: runtime/mobile create-from-review callers should get a new workspace // even when the PR branch or review branch name is already in use. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -22308,7 +22273,7 @@ export class OrcaRuntimeService { effectiveRequestedName = args.name.trim() ? getWorktreeCreateCandidate(args.name, suffix) : effectiveSanitizedName - if (retiredNames.has(effectiveSanitizedName)) { + if (retiredNames?.has(effectiveSanitizedName)) { continue } branchName = await resolveCreateBranchName( @@ -22630,8 +22595,10 @@ export class OrcaRuntimeService { } const worktreeId = `${repo.id}::${created.path}` - // Why: repo-qualified layouts decorate the physical leaf; retire the generated collision key. - this.store.addRetiredWorktreeName?.(repo.id, effectiveSanitizedName) + // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. + if (args.nameWasGenerated) { + retireGeneratedWorktreeName(this.store, repo, settings, effectiveSanitizedName) + } const now = Date.now() // Why: PR/MR-created worktrees can start from a head ref/SHA while Source // Control must compare against the review target branch. diff --git a/src/main/runtime/remote-desktop-driver.test.ts b/src/main/runtime/remote-desktop-driver.test.ts index 2a75853b1bee..5d976ac517e2 100644 --- a/src/main/runtime/remote-desktop-driver.test.ts +++ b/src/main/runtime/remote-desktop-driver.test.ts @@ -58,6 +58,9 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/rpc/methods/worktree-create-args.test.ts b/src/main/runtime/rpc/methods/worktree-create-args.test.ts new file mode 100644 index 000000000000..c630f6170aff --- /dev/null +++ b/src/main/runtime/rpc/methods/worktree-create-args.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from 'vitest' +import { buildManagedWorktreeCreateArgs } from './worktree-create-args' +import { WorktreeCreate } from './worktree-schemas' + +const PROVENANCE = { + automationProvenance: undefined, + cliProvenance: undefined, + creatorProvenance: { kind: 'host' as const } +} + +const build = (params: Record) => + buildManagedWorktreeCreateArgs(WorktreeCreate.parse(params), PROVENANCE) + +describe('buildManagedWorktreeCreateArgs', () => { + it('omits name provenance when the client did not claim a generated name', () => { + // Why: absent must mean user-typed. A truthy default would let the host permanently retire + // names people chose on purpose — the pool contains ordinary words like "orca" and "molly". + expect(build({ repo: 'id:repo-1', name: 'nautilus' })).not.toHaveProperty('nameWasGenerated') + expect( + build({ repo: 'id:repo-1', name: 'nautilus', nameWasGenerated: false }) + ).not.toHaveProperty('nameWasGenerated') + }) + + it('forwards the flag when the client fell back to a generated name', () => { + expect(build({ repo: 'id:repo-1', name: 'nautilus', nameWasGenerated: true })).toMatchObject({ + nameWasGenerated: true + }) + }) +}) diff --git a/src/main/runtime/rpc/methods/worktree-create-args.ts b/src/main/runtime/rpc/methods/worktree-create-args.ts new file mode 100644 index 000000000000..8b0d3ac49eb1 --- /dev/null +++ b/src/main/runtime/rpc/methods/worktree-create-args.ts @@ -0,0 +1,73 @@ +import type { z } from 'zod' +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { WorktreeCreate } from './worktree-schemas' + +type WorktreeCreateParams = z.infer +type ManagedWorktreeCreateArgs = Parameters[0] +type CreateProvenance = Pick< + ManagedWorktreeCreateArgs, + 'automationProvenance' | 'cliProvenance' | 'creatorProvenance' +> + +/** Wire params → runtime create args. Kept out of the method table so the mapping can grow with + * the schema without the table becoming unreadable. */ +export function buildManagedWorktreeCreateArgs( + params: WorktreeCreateParams, + provenance: CreateProvenance +): ManagedWorktreeCreateArgs { + return { + repoSelector: params.repo, + name: params.name ?? '', + // Absent means the user typed the name, which must never be retired. + ...(params.nameWasGenerated === true ? { nameWasGenerated: true } : {}), + baseBranch: params.baseBranch, + compareBaseRef: params.compareBaseRef, + branchNameOverride: params.branchNameOverride, + linkedIssue: params.linkedIssue, + linkedPR: params.linkedPR, + linkedLinearIssue: params.linkedLinearIssue, + linkedLinearIssueWorkspaceId: params.linkedLinearIssueWorkspaceId, + linkedLinearIssueOrganizationUrlKey: params.linkedLinearIssueOrganizationUrlKey, + linkedGitLabMR: params.linkedGitLabMR, + linkedGitLabIssue: params.linkedGitLabIssue, + linkedBitbucketPR: params.linkedBitbucketPR, + linkedAzureDevOpsPR: params.linkedAzureDevOpsPR, + linkedGiteaPR: params.linkedGiteaPR, + linkedWorkItem: params.linkedWorkItem, + linkedTaskSourceContext: params.linkedTaskSourceContext, + comment: params.comment, + displayName: params.displayName, + telemetrySource: params.telemetrySource, + workspaceStatus: params.workspaceStatus, + manualOrder: params.manualOrder, + sparseCheckout: params.sparseCheckout, + pushTarget: params.pushTarget, + runHooks: params.runHooks === true, + activate: params.activate === true, + setupDecision: params.setupDecision, + createdWithAgent: params.createdWithAgent ?? params.startupAgent, + ...provenance, + startup: params.startupCommand + ? { + command: params.startupCommand, + ...(params.startupEnv ? { env: params.startupEnv } : {}), + ...(params.startupLaunchConfig ? { launchConfig: params.startupLaunchConfig } : {}), + ...(params.startupCommandDelivery + ? { startupCommandDelivery: params.startupCommandDelivery } + : {}) + } + : undefined, + ...(params.startupAgent ? { startupAgent: params.startupAgent } : {}), + ...(params.startupPrompt !== undefined ? { startupPrompt: params.startupPrompt } : {}), + startupDraft: params.startupDraft, + lineage: { + parentWorkspace: params.parentWorkspace, + envParentWorkspace: params.envParentWorkspace, + parentWorktree: params.parentWorktree, + ...(params.cwdParentWorktree ? { cwdParentWorktree: params.cwdParentWorktree } : {}), + noParent: params.noParent === true, + callerTerminalHandle: params.callerTerminalHandle, + orchestrationContext: params.orchestrationContext + } + } +} diff --git a/src/main/runtime/rpc/methods/worktree-schemas.ts b/src/main/runtime/rpc/methods/worktree-schemas.ts index a3e562e85161..cbd8b128d61c 100644 --- a/src/main/runtime/rpc/methods/worktree-schemas.ts +++ b/src/main/runtime/rpc/methods/worktree-schemas.ts @@ -104,6 +104,9 @@ export const WorktreeCreate = z .transform((v) => (typeof v === 'string' ? v : '')) .pipe(z.string().min(1, 'Missing repo selector')), name: OptionalString, + /** Set by clients that fell back to a generated creature name. Absent means user-typed, so the + * host neither skips a retired candidate nor retires the name it lands on. */ + nameWasGenerated: z.boolean().optional(), baseBranch: OptionalString, compareBaseRef: OptionalString, branchNameOverride: OptionalString, diff --git a/src/main/runtime/rpc/methods/worktree.ts b/src/main/runtime/rpc/methods/worktree.ts index ead8306f72c5..386bd676c2c6 100644 --- a/src/main/runtime/rpc/methods/worktree.ts +++ b/src/main/runtime/rpc/methods/worktree.ts @@ -5,6 +5,7 @@ import { } from '../../../automations/workspace-provenance' import { buildCliWorkspaceProvenance } from '../../../../shared/cli-workspace-provenance' import { defineMethod, type RpcMethod } from '../core' +import { buildManagedWorktreeCreateArgs } from './worktree-create-args' import { resolveWorktreeCatalogSnapshot } from '../worktree-catalog-snapshot' import { resolveRuntimeNavigationTarget } from '../../../../shared/runtime-navigation' import { resolveRpcWorkspaceCreatorProvenance } from '../workspace-creator-context' @@ -120,66 +121,16 @@ export const WORKTREE_METHODS: RpcMethod[] = [ // Why: provenance tokens are reserved before creation so retries can recover, // but failed create attempts must release the reservation for a safe retry. try { - const result = await runtime.createManagedWorktree({ - repoSelector: params.repo, - name: params.name ?? '', - baseBranch: params.baseBranch, - compareBaseRef: params.compareBaseRef, - branchNameOverride: params.branchNameOverride, - linkedIssue: params.linkedIssue, - linkedPR: params.linkedPR, - linkedLinearIssue: params.linkedLinearIssue, - linkedLinearIssueWorkspaceId: params.linkedLinearIssueWorkspaceId, - linkedLinearIssueOrganizationUrlKey: params.linkedLinearIssueOrganizationUrlKey, - linkedGitLabMR: params.linkedGitLabMR, - linkedGitLabIssue: params.linkedGitLabIssue, - linkedBitbucketPR: params.linkedBitbucketPR, - linkedAzureDevOpsPR: params.linkedAzureDevOpsPR, - linkedGiteaPR: params.linkedGiteaPR, - linkedWorkItem: params.linkedWorkItem, - linkedTaskSourceContext: params.linkedTaskSourceContext, - comment: params.comment, - displayName: params.displayName, - telemetrySource: params.telemetrySource, - workspaceStatus: params.workspaceStatus, - manualOrder: params.manualOrder, - sparseCheckout: params.sparseCheckout, - pushTarget: params.pushTarget, - runHooks: params.runHooks === true, - activate: params.activate === true, - setupDecision: params.setupDecision, - createdWithAgent: params.createdWithAgent ?? params.startupAgent, - automationProvenance, - cliProvenance: buildCliWorkspaceProvenance(params.cliProvenanceRequest, { - startupAgent: params.startupAgent ?? params.createdWithAgent, - createdAt: Date.now() - }), - creatorProvenance: resolveRpcWorkspaceCreatorProvenance(context), - startup: params.startupCommand - ? { - command: params.startupCommand, - ...(params.startupEnv ? { env: params.startupEnv } : {}), - ...(params.startupLaunchConfig - ? { launchConfig: params.startupLaunchConfig } - : {}), - ...(params.startupCommandDelivery - ? { startupCommandDelivery: params.startupCommandDelivery } - : {}) - } - : undefined, - ...(params.startupAgent ? { startupAgent: params.startupAgent } : {}), - ...(params.startupPrompt !== undefined ? { startupPrompt: params.startupPrompt } : {}), - startupDraft: params.startupDraft, - lineage: { - parentWorkspace: params.parentWorkspace, - envParentWorkspace: params.envParentWorkspace, - parentWorktree: params.parentWorktree, - ...(params.cwdParentWorktree ? { cwdParentWorktree: params.cwdParentWorktree } : {}), - noParent: params.noParent === true, - callerTerminalHandle: params.callerTerminalHandle, - orchestrationContext: params.orchestrationContext - } - }) + const result = await runtime.createManagedWorktree( + buildManagedWorktreeCreateArgs(params, { + automationProvenance, + cliProvenance: buildCliWorkspaceProvenance(params.cliProvenanceRequest, { + startupAgent: params.startupAgent ?? params.createdWithAgent, + createdAt: Date.now() + }), + creatorProvenance: resolveRpcWorkspaceCreatorProvenance(context) + }) + ) finishAutomationWorkspaceProvenanceRequest(params.automationProvenanceRequest) // Why: agent callers need a stable dispatch target without traversing // terminal-list layout duplicates after creating the worktree. @@ -296,11 +247,18 @@ export const WORKTREE_METHODS: RpcMethod[] = [ defineMethod({ name: 'worktree.forceDeleteBranch', params: WorktreeForceDeleteBranch, - handler: async (params, { runtime }) => { - const deletionArgs = [params.worktree, params.branchName, params.expectedHead] as const - return params.hostId - ? runtime.forceDeletePreservedBranch(...deletionArgs, params.hostId) - : runtime.forceDeletePreservedBranch(...deletionArgs) - } + handler: async (params, { runtime }) => + params.hostId + ? runtime.forceDeletePreservedBranch( + params.worktree, + params.branchName, + params.expectedHead, + params.hostId + ) + : runtime.forceDeletePreservedBranch( + params.worktree, + params.branchName, + params.expectedHead + ) }) ] diff --git a/src/main/runtime/terminal-query-responder.test.ts b/src/main/runtime/terminal-query-responder.test.ts index cdcd10dfbc34..9d55139f6770 100644 --- a/src/main/runtime/terminal-query-responder.test.ts +++ b/src/main/runtime/terminal-query-responder.test.ts @@ -37,6 +37,9 @@ const store = { getWorktreeMeta: () => undefined, setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNames: () => [], + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getGitHubCache: () => ({ pr: {}, issue: {} }) as never, getSettings: () => ({ workspaceDir: '/tmp/workspaces', diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 3e88e30f4e17..6263ace512ef 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -430,7 +430,7 @@ export function getDefaultPersistedState(homedir: string): PersistedState { projectGroups: [], folderWorkspaces: [], sparsePresetsByRepo: {}, - retiredWorktreeNamesByRepo: {}, + retiredWorktreeNamesByWorkspaceKey: {}, worktreeMeta: {}, worktreeLineageById: {}, workspaceLineageByChildKey: {}, diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index fc4149945779..079a416749ae 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -894,13 +894,6 @@ export type RuntimeWorktreeListResult = { worktrees: RuntimeWorktreeRecord[] totalCount: number truncated: boolean - /** Generated workspace names already spent, keyed by repo id, so a client can avoid suggesting a - * name whose old directory may still hold agent conversation state. - * - * Optional on purpose (remote wire compatibility, Rule 1): hosts predating this field omit it, - * and every reader must fall back to deduping against live worktrees alone rather than - * requiring it. Scoped to the repos present in `worktrees` so the payload stays bounded. */ - retiredNamesByRepo?: Record } // ── Browser automation types ── diff --git a/src/shared/types.ts b/src/shared/types.ts index 1452d33e09dc..d80ac4c67c6b 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -2306,6 +2306,11 @@ export type SparsePreset = { export type CreateWorktreeArgs = { repoId: string name: string + /** True only when `name` came from Orca's creature-name generator rather than the user. Gates + * name retirement: a generated name is never reissued, but `Orca`, `Runner` and `Molly` are all + * in that pool, so a name the user typed must stay reusable. Defaults to false, which keeps + * CLI and automation callers on the pre-retirement behavior. */ + nameWasGenerated?: boolean /** Optional user-facing label to persist separately from the git-safe * branch/path seed. Used when a workspace is created from a GitHub or * Linear artifact whose title should remain readable in the sidebar. */ @@ -3723,10 +3728,12 @@ export type PersistedState = { folderWorkspaceDiffComments?: Record /** Sparse-checkout presets keyed by repoId. */ sparsePresetsByRepo: Record - /** Generated workspace names already issued, keyed by repoId. Suppresses reissuing a name so a - * recreated workspace never lands on a prior occupant's path and inherits agent state keyed to - * that cwd. Grows monotonically; entries are never removed on workspace deletion. */ - retiredWorktreeNamesByRepo?: Record + /** Generated workspace names already issued, keyed by the cwd namespace repos create into + * (execution host + workspace-root path), not by repoId — the collision this prevents is on the + * path, and repo ids change on remove/re-add while the path does not. Suppresses reissuing a + * name so a recreated workspace never lands on a prior occupant's path and inherits agent state + * keyed to that cwd. Grows monotonically; entries are never removed on workspace deletion. */ + retiredWorktreeNamesByWorkspaceKey?: Record /** Per paired device last tab selection by worktree; keeps mobile navigation across host restarts. */ mobileClientTabSelectionsByDeviceId?: PersistedMobileClientTabSelections worktreeMeta: Record From ef06e49a64d37c7b706233b5ce62ad5402e70993 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 17:43:56 -0700 Subject: [PATCH 10/20] fix(worktree): send name provenance and stop gating Create on the fetch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desktop and mobile now mark a create as generated-name only when the user typed nothing and the composer fell back to the suggestion, so the host knows which names it may retire. Remove the retired-names loading gate from every create path. The host already skips retired candidates before doing any git work, so the client gate bought nothing while it could disable Create for the length of a full mobile reconnect ladder (the wait had no timeout) and blank the desktop button between queued creates. The suggestion still waits; the button never does. Also make the web client call worktree.listRetiredNames instead of hardcoding an empty list — the method is registered and mobile-allowlisted, so the comment claiming no wire call existed was wrong — and filter the mobile response to strings so a malformed row cannot throw during normalization. --- mobile/src/components/NewWorktreeModal.tsx | 8 ++-- .../src/tasks/blank-workspace-create.test.ts | 24 ++++++++++ mobile/src/tasks/blank-workspace-create.ts | 4 ++ .../worktree/use-retired-worktree-names.ts | 6 ++- src/renderer/src/hooks/useComposerState.ts | 22 +++++---- .../src/lib/pending-worktree-creation.ts | 2 + .../src/lib/worktree-creation-flow.ts | 1 + .../src/store/slices/worktree-helpers.ts | 2 + .../src/store/slices/worktrees.test.ts | 45 +++++++++++++++++++ src/renderer/src/store/slices/worktrees.ts | 1 + src/renderer/src/web/web-preload-api.ts | 18 ++++++-- 11 files changed, 115 insertions(+), 18 deletions(-) diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 644a6f27184e..0da42f35f215 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -189,8 +189,8 @@ function NewWorktreeModalContent({ const [selectedRepo, setSelectedRepo] = useState(null) // Why: a deleted workspace's directory can still hold agent conversation state keyed by cwd, so // its name must never be suggested again. Fetched per selected repo while the sheet is open. - const { names: retiredWorktreeNames, loading: retiredWorktreeNamesLoading } = - useRetiredWorktreeNames(client, selectedRepo?.id) + // Create is never gated on it: the host skips retired candidates before doing any git work. + const { names: retiredWorktreeNames } = useRetiredWorktreeNames(client, selectedRepo?.id) const { drawerView, formSheetVisible, formSheetInteractive, transitionDrawer, openSourceDrawer } = useNewWorktreeDrawerNavigation(visible) const createInFlightRef = useRef(false) @@ -565,7 +565,7 @@ function NewWorktreeModalContent({ } async function handleCreate(options: CreateOptions = {}) { - if (!client || !selectedRepo || retiredWorktreeNamesLoading || createInFlightRef.current) { + if (!client || !selectedRepo || createInFlightRef.current) { return } createInFlightRef.current = true @@ -662,6 +662,7 @@ function NewWorktreeModalContent({ client, repoId: selectedRepo.id, baseName, + nameWasGenerated: !trimmedName, createdWithAgentId, comment: trimmedNote, setupDecision, @@ -685,7 +686,6 @@ function NewWorktreeModalContent({ const canCreate = selectedRepo != null && !creating && - !retiredWorktreeNamesLoading && !sshGate.requiresConnection && (!needsSetupChoice || setupDecisionChoice != null) const visibleAgentOptions = diff --git a/mobile/src/tasks/blank-workspace-create.test.ts b/mobile/src/tasks/blank-workspace-create.test.ts index b1b391c55a45..32e9e162ef40 100644 --- a/mobile/src/tasks/blank-workspace-create.test.ts +++ b/mobile/src/tasks/blank-workspace-create.test.ts @@ -34,6 +34,7 @@ describe('createBlankWorkspace', () => { createdWithAgentId: undefined, comment: undefined, setupDecision: 'inherit', + nameWasGenerated: false, supportsIdempotentCutoverRetry: true }) @@ -56,6 +57,25 @@ describe('createBlankWorkspace', () => { expect('comment' in params).toBe(false) }) + it('marks the name as generated only when the user typed nothing', async () => { + // Why: the host retires generated names permanently; a name the user chose must stay reusable. + const calls: Call[] = [] + const client = fakeClient(() => ({ worktree: { id: 'wt-3' } }), calls) + + await createBlankWorkspace({ + client, + repoId: 'repo-1', + baseName: 'octopus', + createdWithAgentId: undefined, + comment: undefined, + setupDecision: 'inherit', + nameWasGenerated: true, + supportsIdempotentCutoverRetry: true + }) + + expect(calls[0]?.params).toMatchObject({ nameWasGenerated: true }) + }) + it('sends startupAgent (not a pre-built command) so the host resolves launch args', async () => { // Why: regression — the modal used to send a bare startupCommand ('claude') // that skipped the host's default `--dangerously-skip-permissions`. @@ -69,6 +89,7 @@ describe('createBlankWorkspace', () => { createdWithAgentId: 'claude', comment: 'spike', setupDecision: 'run', + nameWasGenerated: false, supportsIdempotentCutoverRetry: true }) @@ -100,6 +121,7 @@ describe('createBlankWorkspace', () => { createdWithAgentId: undefined, comment: undefined, setupDecision: 'inherit', + nameWasGenerated: false, supportsIdempotentCutoverRetry: true }) @@ -125,6 +147,7 @@ describe('createBlankWorkspace', () => { createdWithAgentId: undefined, comment: undefined, setupDecision: 'inherit', + nameWasGenerated: false, supportsIdempotentCutoverRetry: true }) @@ -143,6 +166,7 @@ describe('createBlankWorkspace', () => { createdWithAgentId: undefined, comment: undefined, setupDecision: 'skip', + nameWasGenerated: false, supportsIdempotentCutoverRetry: true }) diff --git a/mobile/src/tasks/blank-workspace-create.ts b/mobile/src/tasks/blank-workspace-create.ts index 2cbed6982766..14c095a777e2 100644 --- a/mobile/src/tasks/blank-workspace-create.ts +++ b/mobile/src/tasks/blank-workspace-create.ts @@ -16,6 +16,9 @@ export async function createBlankWorkspace(args: { createdWithAgentId: TuiAgent | undefined comment: string | undefined setupDecision: WorkspaceCreateSetupDecision + /** True when `baseName` is a generated creature name rather than one the user typed; only then + * may the host retire it. */ + nameWasGenerated: boolean supportsIdempotentCutoverRetry: boolean | Promise }): Promise { return createWorktreeWithNameRetry({ @@ -27,6 +30,7 @@ export async function createBlankWorkspace(args: { repo: `id:${args.repoId}`, setupDecision: args.setupDecision, name, + ...(args.nameWasGenerated ? { nameWasGenerated: true } : {}), ...agentLaunchCreateFields(args.createdWithAgentId) } if (args.comment) { diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts index c875f2ca0c15..a641b3f9d4b4 100644 --- a/mobile/src/worktree/use-retired-worktree-names.ts +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -34,7 +34,11 @@ export function useRetiredWorktreeNames( | { retiredNamesByRepo?: Record } | undefined const names = result?.retiredNamesByRepo?.[repoId] - setLoaded({ repoId, names: Array.isArray(names) ? names : [] }) + setLoaded({ + repoId, + // A host can answer with a malformed row; a non-string would throw when normalized. + names: Array.isArray(names) ? names.filter((name) => typeof name === 'string') : [] + }) }) .catch(() => { if (!cancelled) { diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index b4941cc26c61..dc43f47ae062 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -1601,8 +1601,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS .join('\0'), [repoId, worktreesByRepo] ) - const { names: retiredWorktreeNames, loading: retiredWorktreeNamesLoading } = - useRetiredWorktreeNames(repoId, retiredNamesRefreshKey) + // Create is never gated on this load: the host skips retired candidates before any git work, so + // a pending fetch can only cost a suggestion, never correctness. + const { names: retiredWorktreeNames } = useRetiredWorktreeNames(repoId, retiredNamesRefreshKey) const fallbackCreatureName = useMemo( () => getSuggestedCreatureName(worktreesByRepo, undefined, retiredWorktreeNames), [worktreesByRepo, retiredWorktreeNames] @@ -3580,7 +3581,6 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS } if ( !workspaceSeedName || - retiredWorktreeNamesLoading || selectedRepoRequiresConnection || shouldWaitForSetupCheck || shouldWaitForIssueAutomationCheck || @@ -3648,6 +3648,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS if (!workspaceName) { return } + // Why: only a name Orca generated may be retired — the creature pool contains ordinary words + // ("orca", "runner", "molly") a user can type deliberately and expect to reuse. + const nameWasGenerated = !name.trim() && workspaceName === fallbackCreatureName const submitBaseBranch = smartGitHubResolution.kind === 'pr-start-point' ? smartGitHubResolution.baseBranch @@ -3898,6 +3901,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS { linkedWorkItem: toFolderWorkspaceLinkedTask(submitLinkedWorkItem), linkedTaskSourceContext: taskSourceContext, + nameWasGenerated, ...(!backendStartup && startupPlan?.draftPrompt ? { startupDraft: startupPlan.draftPrompt } : {}) @@ -4044,9 +4048,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS shouldWaitForIssueAutomationCheck, shouldWaitForSetupCheck, sourceIntentBlocksCreate, - retiredWorktreeNamesLoading, taskSourceContext, workspaceSeedName, + fallbackCreatureName, isProjectGroupTarget, submitFolderTarget ]) @@ -4095,7 +4099,6 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS } if ( !workspaceNameSeed || - retiredWorktreeNamesLoading || sourceIntentBlocksCreate || selectedRepoRequiresConnection || (requiresExplicitSetupChoice && !setupDecision) || @@ -4184,6 +4187,8 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS if (!workspaceName) { return } + // Why: only a name Orca generated may be retired — see the full-composer submit path. + const nameWasGenerated = !name.trim() && workspaceName === fallbackCreatureName const smartSubmitBaseBranch = smartGitHubResolution.kind === 'pr-start-point' ? smartGitHubResolution.baseBranch @@ -4512,6 +4517,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS linkedTaskSourceContext: taskSourceContext, ...(workspaceRunContext ? { workspaceRunContext } : {}), name: workspaceName, + ...(nameWasGenerated ? { nameWasGenerated: true } : {}), ...(createDisplayName ? { displayName: createDisplayName } : {}), ...(selectedRepoIsGit && submitBaseBranch ? { baseBranch: submitBaseBranch } : {}), ...(selectedRepoIsGit && submitCompareBaseRef @@ -4632,7 +4638,6 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS settings?.openAgentTabsInChatByDefault, smartNameMode, sourceIntentBlocksCreate, - retiredWorktreeNamesLoading, disabledTuiAgents, setupDecision, sparseEnabled, @@ -4666,10 +4671,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS sparseError } const repoCreateDisabled = - retiredWorktreeNamesLoading || - (createGateMode === 'quick' + createGateMode === 'quick' ? getQuickComposerCreateDisabled(createGateInput) - : getFullComposerCreateDisabled(createGateInput)) + : getFullComposerCreateDisabled(createGateInput) const createDisabled = isProjectGroupTarget ? folderCreateDisabled : repoCreateDisabled const cardProps: ComposerCardProps = { eligibleRepos: isProjectGroupTarget ? folderSourceRepos : eligibleRepos, diff --git a/src/renderer/src/lib/pending-worktree-creation.ts b/src/renderer/src/lib/pending-worktree-creation.ts index d635e82555a1..b1c45e9adc24 100644 --- a/src/renderer/src/lib/pending-worktree-creation.ts +++ b/src/renderer/src/lib/pending-worktree-creation.ts @@ -56,6 +56,8 @@ export type WorktreeCreationRequest = { * local-vs-runtime progress behavior even if the focused runtime changes. */ worktreeCreateProgressMode?: WorktreeCreationProgressMode name: string + /** True only when `name` came from the creature-name generator; gates host-side retirement. */ + nameWasGenerated?: boolean displayName?: string baseBranch?: string compareBaseRef?: string diff --git a/src/renderer/src/lib/worktree-creation-flow.ts b/src/renderer/src/lib/worktree-creation-flow.ts index 132f4825dc86..c822bed55abe 100644 --- a/src/renderer/src/lib/worktree-creation-flow.ts +++ b/src/renderer/src/lib/worktree-creation-flow.ts @@ -135,6 +135,7 @@ async function executeWorktreeCreation( preparedRequest.linkedGiteaPR, preparedRequest.compareBaseRef, { + ...(preparedRequest.nameWasGenerated ? { nameWasGenerated: true } : {}), ...(preparedRequest.linkedWorkItem !== undefined ? { linkedWorkItem: preparedRequest.linkedWorkItem } : {}), diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index c2980357ee85..995ca3bd8aa1 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -209,6 +209,8 @@ export type WorktreeSlice = { linkedTaskSourceContext?: TaskSourceContext | null /** Lets the owning runtime launch and prefill a task agent without first creating an idle shell. */ startupDraft?: string + /** True only when `name` came from the creature-name generator; gates host-side retirement. */ + nameWasGenerated?: boolean } ) => Promise /** Register an in-flight background creation and make it the active surface. */ diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 6077204ba51a..7349b9a35e74 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -4867,6 +4867,51 @@ describe('createWorktree base status merge', () => { expect(mockApi.worktrees.prefetchCreateBase).not.toHaveBeenCalled() }) + it('marks the create payload as a generated name only when the caller says so', async () => { + // Why: the host retires generated names permanently, and the creature pool contains ordinary + // words ("orca", "runner", "molly"). A name the user typed must stay reusable. + const store = createTestStore() + mockApi.worktrees.create.mockResolvedValue({ + worktree: makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) + }) + + await store.getState().createWorktree('repo1', 'nautilus', 'origin/main') + expect(mockApi.worktrees.create.mock.calls[0][0]).not.toHaveProperty('nameWasGenerated') + + mockApi.worktrees.create.mockClear() + await store + .getState() + .createWorktree( + 'repo1', + 'nautilus', + 'origin/main', + 'inherit', + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + { nameWasGenerated: true } + ) + expect(mockApi.worktrees.create.mock.calls[0][0]).toMatchObject({ nameWasGenerated: true }) + }) + it('passes linked work item and creation agent metadata through the create IPC payload', async () => { const store = createTestStore() const wt = makeWorktree({ diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 00e421cb7dfd..4fd22ab07f7f 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -3945,6 +3945,7 @@ export const createWorktreeSlice: StateCreator const createArgs = { repoId, name: candidateName, + ...(options?.nameWasGenerated ? { nameWasGenerated: true } : {}), baseBranch, ...(compareBaseRef ? { compareBaseRef } : {}), ...(candidateBranchNameOverride diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index a67258618b99..8c10342a1f31 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1772,10 +1772,20 @@ function createWorktreesApi(): NonNullable['worktrees']> { withRuntimeWorktreeOwner(worktree, owned.hostId) ) }, - // Why: retirement is host-owned state with no wire call, and paired hosts update independently - // of clients. Returning empty degrades a web-client suggestion to the pre-existing behavior - // (a spent name can be offered) rather than inventing an RPC an older host cannot answer. - listRetiredNames: async () => [], + // Why the catch: a host predating this method answers `method_not_found`, and an empty list + // degrades the suggestion to the pre-existing behavior rather than blocking workspace create. + listRetiredNames: async ({ repoId }) => { + try { + const result = await callRuntimeResult<{ retiredNamesByRepo?: Record }>( + 'worktree.listRetiredNames', + { repo: repoId } + ) + const names = result.retiredNamesByRepo?.[repoId] + return Array.isArray(names) ? names.filter((name) => typeof name === 'string') : [] + } catch { + return [] + } + }, listDetected: async ({ repoId }) => callRuntimeDetectedWorktrees(repoId), listAll: () => listAllRuntimeWorktrees(), create: async (args) => { From 9234cb4055863754ce992435b63c448555db12ea Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 17:59:00 -0700 Subject: [PATCH 11/20] fix(worktree): key retirement by repo id and prune it with the repo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reverts the collision-key storage key. It was a function of workspaceDir, nestWorkspaces, worktreeBasePath and repo.path, so toggling any one of those orphaned every retirement for every affected repo at once — trading a rare churn (remove/re-add) for a common one. The read path already unions by cwd namespace at query time, so cross-repo sharing never depended on the storage key. Instead, address the growth and orphaning directly: - Drop the registry in removeProject, and in removeProjectForHost once the last host's copy of the repo id is gone, alongside the sparse-preset deletes that already follow this convention. - Bound each repo's registry. The cap sits far above the 552-name pool because evicting inside it would reissue a name whose agent state is still on disk; only -2/-3 tier accumulation can ever reach it. - Carry retirements through profile transfer, re-keyed to the destination repo id and dropped from the source, mirroring sparsePresetsByRepo. Separately, fix the backfill merge: the scan promise is cached per cwd namespace, but it closed over the first repo id that triggered it, so a second repo in the same namespace received nothing. The scan stays shared; the merge moves out of the cached promise and runs for whichever repo asked. Local repos re-seed on re-add through that backfill. SSH repos do not — the scan cannot see the execution host — which is now stated in the module. --- src/main/ipc/worktree-remote.ts | 13 +- src/main/ipc/worktrees-windows.test.ts | 2 +- src/main/ipc/worktrees.test.ts | 2 +- src/main/ipc/worktrees.ts | 2 +- .../profile-project-source-removal.ts | 2 + .../profile-project-state-file.ts | 1 + .../profile-project-transfer-payload.ts | 11 ++ .../profile-project-transfer.test.ts | 4 + ...rsistence-worktree-name-retirement.test.ts | 119 +++++++++++++----- src/main/persistence.ts | 67 ++++++---- src/main/runtime/orca-runtime.test.ts | 2 +- src/main/runtime/orca-runtime.ts | 9 +- src/main/worktree-name-retirement.test.ts | 112 +++++++++-------- src/main/worktree-name-retirement.ts | 78 +++++++----- src/shared/constants.ts | 2 +- src/shared/types.ts | 13 +- 16 files changed, 270 insertions(+), 169 deletions(-) diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index c4ea34e81d35..d03199081228 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -135,10 +135,7 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' -import { - getRetiredWorktreeNamesForRepo, - retireGeneratedWorktreeName -} from '../worktree-name-retirement' +import { getRetiredWorktreeNamesForRepo } from '../worktree-name-retirement' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1555,7 +1552,7 @@ export async function createRemoteWorktree( let lastBranchConflictKind: 'local' | 'remote' | null = null let remotePathResolved = false const retiredNames = args.nameWasGenerated - ? new Set(getRetiredWorktreeNamesForRepo(store, repo, settings)) + ? new Set(getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings)) : null // Why: duplicate PR/MR checkouts still need a workspace; suffix branch/path while preserving review metadata and push target. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -1773,7 +1770,7 @@ export async function createRemoteWorktree( const worktreeId = `${repo.id}::${created.path}` // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. if (args.nameWasGenerated) { - retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) } const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. @@ -2104,7 +2101,7 @@ export async function createLocalWorktree( let lastExistingPR: Awaited> | null = null let lastExistingReviewNumber: number | null = null const retiredNames = args.nameWasGenerated - ? new Set(getRetiredWorktreeNamesForRepo(store, repo, settings)) + ? new Set(getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings)) : null // Why: a create-from-review branch override may already exist locally; suffix both branch and path instead of blocking the user. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -2400,7 +2397,7 @@ export async function createLocalWorktree( const worktreeId = `${repo.id}::${created.path}` // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. if (args.nameWasGenerated) { - retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) } const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index 189f2e551415..8efa7c905fc6 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -348,7 +348,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { nameWasGenerated: true }) - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith(expect.any(String), 'nautilus-2') + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'nautilus-2') }) it('leaves a user-typed name reusable even when the same name is retired', async () => { diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 460f6e62b85f..3ea8e2cfc350 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -4715,7 +4715,7 @@ describe('registerWorktreeHandlers', () => { ) expect(provider.listWorktrees).toHaveBeenCalledTimes(1) expect(provider.worktreeIsClean).not.toHaveBeenCalled() - expect(store.addRetiredWorktreeName).toHaveBeenCalledWith(expect.any(String), 'nautilus-2') + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-ssh', 'nautilus-2') expect(store.setWorktreeMeta).toHaveBeenCalledWith( 'repo-ssh::/remote/repo-nautilus-2', expect.objectContaining({ diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 62620720d213..a5335ca20dee 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -1925,7 +1925,7 @@ export function registerWorktreeHandlers( // Best effort: without the seed we only under-retire, which is the pre-existing behavior. console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) } - return getRetiredWorktreeNamesForRepo(store, repo, store.getSettings()) + return getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), store.getSettings()) }) ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { diff --git a/src/main/orca-profiles/profile-project-source-removal.ts b/src/main/orca-profiles/profile-project-source-removal.ts index edb923e62938..b120ba0c3724 100644 --- a/src/main/orca-profiles/profile-project-source-removal.ts +++ b/src/main/orca-profiles/profile-project-source-removal.ts @@ -18,6 +18,7 @@ export function removeSourceRepo( ...state, repos: state.repos.filter((repo) => repo.id !== repoId), sparsePresetsByRepo: { ...state.sparsePresetsByRepo }, + retiredWorktreeNamesByRepo: { ...state.retiredWorktreeNamesByRepo }, worktreeMeta: { ...state.worktreeMeta }, worktreeLineageById: { ...state.worktreeLineageById }, workspaceLineageByChildKey: { ...state.workspaceLineageByChildKey }, @@ -38,6 +39,7 @@ export function removeSourceRepo( } } delete next.sparsePresetsByRepo[repoId] + delete next.retiredWorktreeNamesByRepo?.[repoId] removeRepoWorktreeMetadata(next, repoId) return rebuildRepoBackedProjectState(next) } diff --git a/src/main/orca-profiles/profile-project-state-file.ts b/src/main/orca-profiles/profile-project-state-file.ts index 4169fea6ffc4..bd7fbc8f6be1 100644 --- a/src/main/orca-profiles/profile-project-state-file.ts +++ b/src/main/orca-profiles/profile-project-state-file.ts @@ -45,6 +45,7 @@ export function readProfileState(profileId: string, userDataPath: string): Trans projectGroups: arrayOrEmpty(parsed.projectGroups), folderWorkspaces: arrayOrEmpty(parsed.folderWorkspaces), sparsePresetsByRepo: recordOrEmpty(parsed.sparsePresetsByRepo), + retiredWorktreeNamesByRepo: recordOrEmpty(parsed.retiredWorktreeNamesByRepo), worktreeMeta: recordOrEmpty(parsed.worktreeMeta), worktreeLineageById: recordOrEmpty(parsed.worktreeLineageById), workspaceLineageByChildKey: recordOrEmpty(parsed.workspaceLineageByChildKey), diff --git a/src/main/orca-profiles/profile-project-transfer-payload.ts b/src/main/orca-profiles/profile-project-transfer-payload.ts index f8e458df4df8..524aa02ad92b 100644 --- a/src/main/orca-profiles/profile-project-transfer-payload.ts +++ b/src/main/orca-profiles/profile-project-transfer-payload.ts @@ -20,6 +20,9 @@ import { export type TransferPayload = { repo: Repo sparsePresets: SparsePreset[] + /** Generated names already spent for this repo. Carried so the destination profile does not + * reissue a name whose old directory still holds agent state. */ + retiredWorktreeNames: string[] worktreeMeta: PersistedState['worktreeMeta'] worktreeLineageById: PersistedState['worktreeLineageById'] workspaceLineageByChildKey: PersistedState['workspaceLineageByChildKey'] @@ -214,6 +217,7 @@ export function createTransferPayload(args: { ...structuredClone(preset), repoId: newRepoId })), + retiredWorktreeNames: [...(sourceState.retiredWorktreeNamesByRepo?.[oldRepoId] ?? [])], worktreeMeta: rekeyWorktreeIdRecord( sourceState.worktreeMeta, worktreeIds, @@ -269,6 +273,13 @@ export function applyPayloadToTarget( ...targetState.sparsePresetsByRepo, ...(payload.sparsePresets.length > 0 ? { [payload.repo.id]: payload.sparsePresets } : {}) }, + retiredWorktreeNamesByRepo: { + ...targetState.retiredWorktreeNamesByRepo, + ...(payload.retiredWorktreeNames.length > 0 + ? { [payload.repo.id]: payload.retiredWorktreeNames } + : {}) + }, + worktreeMeta: { ...targetState.worktreeMeta, ...payload.worktreeMeta }, worktreeLineageById: { ...targetState.worktreeLineageById, ...payload.worktreeLineageById }, workspaceLineageByChildKey: { diff --git a/src/main/orca-profiles/profile-project-transfer.test.ts b/src/main/orca-profiles/profile-project-transfer.test.ts index 3c3a4643387d..a8983dc49798 100644 --- a/src/main/orca-profiles/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/profile-project-transfer.test.ts @@ -126,6 +126,7 @@ describe('profile project transfer', () => { } ] }, + retiredWorktreeNamesByRepo: { 'repo-1': ['nautilus'] }, worktreeMeta: { [sourceWorktreeId]: makeWorktreeMeta({ projectHostSetupId: 'repo-1' }) }, @@ -177,6 +178,9 @@ describe('profile project transfer', () => { expect(target.sparsePresetsByRepo[targetRepoId]).toEqual([ expect.objectContaining({ id: 'preset-1', repoId: targetRepoId }) ]) + // Why: without the re-key the destination profile reissues a name whose old directory may + // still hold the previous occupant's agent conversation. + expect(target.retiredWorktreeNamesByRepo?.[targetRepoId]).toEqual(['nautilus']) expect(target.workspaceSession.tabsByWorktree).toEqual({}) expect(readProfileState('personal').repos.map((repo) => repo.id)).toEqual(['repo-1']) }) diff --git a/src/main/persistence-worktree-name-retirement.test.ts b/src/main/persistence-worktree-name-retirement.test.ts index 8e296c880d4b..6522e3bae0a4 100644 --- a/src/main/persistence-worktree-name-retirement.test.ts +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -3,6 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { getDefaultPersistedState } from '../shared/constants' +import { MARINE_CREATURES } from '../shared/marine-creatures' const testState = { dir: '' } @@ -13,9 +14,8 @@ vi.mock('electron', () => ({ vi.mock('./telemetry/client', () => ({ track: vi.fn() })) vi.mock('./telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) -// The registry is keyed by the cwd namespace a repo creates into, not by repo id. -const KEY = 'local:posix:/workspaces/repo-1' -const OTHER_KEY = 'local:posix:/workspaces/repo-2' +const REPO = 'repo-1' +const OTHER_REPO = 'repo-2' async function createStore(persisted: Record = {}) { mkdirSync(testState.dir, { recursive: true }) @@ -41,81 +41,134 @@ afterEach(() => { describe('worktree name retirement registry', () => { it('retains a retired name so it is never reissued', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, 'Nautilus') - expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) + store.addRetiredWorktreeName(REPO, 'Nautilus') + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) }) - it('scopes retirement per cwd namespace so one workspace root does not burn another', async () => { + it('scopes retirement per repo so one repo does not burn another pool', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, 'nautilus') - expect(store.getRetiredWorktreeNames(OTHER_KEY)).toEqual([]) + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.getRetiredWorktreeNames(OTHER_REPO)).toEqual([]) }) it('normalizes case and whitespace so a name cannot be retired twice', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, ' NaUtIlUs ') - store.addRetiredWorktreeName(KEY, 'nautilus') - expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) + store.addRetiredWorktreeName(REPO, ' NaUtIlUs ') + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) }) - it('ignores an empty name or missing workspace key', async () => { + it('ignores an empty name or missing repo id', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, ' ') + store.addRetiredWorktreeName(REPO, ' ') store.addRetiredWorktreeName('', 'nautilus') - expect(store.getRetiredWorktreeNames(KEY)).toEqual([]) + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) }) it('does not persist arbitrary user and issue-title names', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, 'fix-login-redirect') - store.addRetiredWorktreeName(KEY, 'STA-4189-duplicate-name') - expect(store.getRetiredWorktreeNames(KEY)).toEqual([]) + store.addRetiredWorktreeName(REPO, 'fix-login-redirect') + store.addRetiredWorktreeName(REPO, 'STA-4189-duplicate-name') + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) }) it('returns a copy so callers cannot mutate the registry in place', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, 'nautilus') - store.getRetiredWorktreeNames(KEY).push('seahorse') - expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) + store.addRetiredWorktreeName(REPO, 'nautilus') + store.getRetiredWorktreeNames(REPO).push('seahorse') + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) }) it('merges backfilled names without dropping a concurrent retirement', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, 'nautilus') - expect(store.mergeRetiredWorktreeNames(KEY, ['seahorse', 'starfish'])).toBe(true) - expect(store.getRetiredWorktreeNames(KEY).sort()).toEqual(['nautilus', 'seahorse', 'starfish']) + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.mergeRetiredWorktreeNames(REPO, ['seahorse', 'starfish'])).toBe(true) + expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse', 'starfish']) }) it('reports no change when a merge adds nothing new', async () => { const store = await createStore() - store.addRetiredWorktreeName(KEY, 'nautilus') - expect(store.mergeRetiredWorktreeNames(KEY, ['NAUTILUS'])).toBe(false) + store.addRetiredWorktreeName(REPO, 'nautilus') + expect(store.mergeRetiredWorktreeNames(REPO, ['NAUTILUS'])).toBe(false) }) it('survives a reload so retirement outlives the workspace and the app session', async () => { const store = await createStore({ - retiredWorktreeNamesByWorkspaceKey: { [KEY]: ['nautilus', 'seahorse'] } + retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 'seahorse'] } }) - expect(store.getRetiredWorktreeNames(KEY).sort()).toEqual(['nautilus', 'seahorse']) + expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) }) it('degrades to nothing retired when the persisted map is corrupt', async () => { // Why: a load failure costs the app; over- or under-retiring costs at most a name. - const store = await createStore({ retiredWorktreeNamesByWorkspaceKey: 'not-an-object' }) - expect(store.getRetiredWorktreeNames(KEY)).toEqual([]) + const store = await createStore({ retiredWorktreeNamesByRepo: 'not-an-object' }) + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) }) it('drops non-string entries but keeps the valid ones', async () => { const store = await createStore({ - retiredWorktreeNamesByWorkspaceKey: { [KEY]: ['nautilus', 42, null, 'Seahorse'] } + retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 42, null, 'Seahorse'] } }) - expect(store.getRetiredWorktreeNames(KEY).sort()).toEqual(['nautilus', 'seahorse']) + expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + }) + + it('drops the registry when the repo is removed, matching the sparse-preset convention', async () => { + // Why: entries are repo-id keyed, so without this they orphan forever — a repo id is never + // reused, and remove/re-add mints a new one. + const store = await createStore() + store.addRepo({ id: REPO, path: '/repos/a', displayName: 'a', badgeColor: '', addedAt: 0 }) + store.addRetiredWorktreeName(REPO, 'nautilus') + + store.removeProject(REPO) + + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + }) + + it('keeps the registry when one host row is removed but the repo id survives elsewhere', async () => { + const store = await createStore() + store.addRepo({ id: REPO, path: '/repos/a', displayName: 'a', badgeColor: '', addedAt: 0 }) + store.addRepo({ + id: REPO, + path: '/repos/a', + displayName: 'a', + badgeColor: '', + addedAt: 0, + executionHostId: 'runtime:env-1' + } as never) + store.addRetiredWorktreeName(REPO, 'nautilus') + + store.removeProjectForHost(REPO, 'runtime:env-1') + + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + + store.removeProjectForHost(REPO, 'local') + + expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + }) + + it('bounds the per-repo registry above the pool so the cap never reissues a base name', async () => { + // The cap must sit well past the 552-name pool: evicting inside it would hand back a name whose + // agent state is still on disk, which is the bug this registry exists to prevent. + const store = await createStore() + const names = MARINE_CREATURES.map((name) => name.toLowerCase()) + for (let tier = 2; tier <= 5; tier += 1) { + store.mergeRetiredWorktreeNames( + REPO, + names.map((name) => `${name}-${tier}`) + ) + } + store.mergeRetiredWorktreeNames(REPO, names) + + const retained = store.getRetiredWorktreeNames(REPO) + expect(retained.length).toBe(2000) + // Oldest-first eviction, so the most recent merge survives intact. + expect(retained).toEqual(expect.arrayContaining(names)) }) it('drops legacy arbitrary names while loading the persisted map', async () => { const store = await createStore({ - retiredWorktreeNamesByWorkspaceKey: { [KEY]: ['fix-login', 'Nautilus'] } + retiredWorktreeNamesByRepo: { [REPO]: ['fix-login', 'Nautilus'] } }) - expect(store.getRetiredWorktreeNames(KEY)).toEqual(['nautilus']) + expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) }) }) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 22eea861a07d..0aee1c2bd16a 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2335,15 +2335,28 @@ const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 // Why: bound removed-SSH-target history so remove/re-add churn can't grow the file unbounded. const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 +// Why: bound per-repo retirement so long-lived repos can't grow the file unbounded. Deliberately +// far above the 552-name pool — a cap below it would start reissuing names and reintroduce the bug +// this registry exists to prevent, so only `-2`/`-3` tier accumulation can ever reach it. +const MAX_RETIRED_WORKTREE_NAMES_PER_REPO = 2000 + +/** Oldest-first eviction: entries are appended in retirement order, and the oldest paths are the + * ones whose agent state is likeliest to be gone already. */ +function boundRetiredWorktreeNames(names: readonly string[]): string[] { + return names.length > MAX_RETIRED_WORKTREE_NAMES_PER_REPO + ? names.slice(names.length - MAX_RETIRED_WORKTREE_NAMES_PER_REPO) + : [...names] +} + /** Why: a corrupt or hand-edited map must degrade to "nothing retired" rather than throw during * load — over-retiring costs one name from a 552-entry pool, but a load failure costs the app. */ -function normalizeRetiredWorktreeNamesByWorkspaceKey(value: unknown): Record { +function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return {} } - const byKey: Record = {} - for (const [workspaceKey, names] of Object.entries(value as Record)) { - if (!workspaceKey || !Array.isArray(names)) { + const byRepo: Record = {} + for (const [repoId, names] of Object.entries(value as Record)) { + if (!repoId || !Array.isArray(names)) { continue } const seen = new Set() @@ -2357,10 +2370,10 @@ function normalizeRetiredWorktreeNamesByWorkspaceKey(value: unknown): Record 0) { - byKey[workspaceKey] = [...seen] + byRepo[repoId] = boundRetiredWorktreeNames([...seen]) } } - return byKey + return byRepo } function normalizeClaudeLivePtySessionIds(value: unknown): string[] { @@ -3848,8 +3861,8 @@ export class Store { (alias): alias is string => typeof alias === 'string' ) : [], - retiredWorktreeNamesByWorkspaceKey: normalizeRetiredWorktreeNamesByWorkspaceKey( - parsed.retiredWorktreeNamesByWorkspaceKey + retiredWorktreeNamesByRepo: normalizeRetiredWorktreeNamesByRepo( + parsed.retiredWorktreeNamesByRepo ), sshRemotePtyLeases: (parsed.sshRemotePtyLeases ?? []) .map(normalizeSshRemotePtyLease) @@ -4881,6 +4894,8 @@ export class Store { this.syncProjectHostSetupCompatibilityState() // Why: presets are repo-scoped and unreachable once the repo is gone, so drop them with it. delete this.state.sparsePresetsByRepo[id] + // Same convention: retirements are repo-id-keyed, so they would otherwise orphan forever. + delete this.state.retiredWorktreeNamesByRepo?.[id] this.pruneWorktreeStateForRepo(id, null) this.state.workspaceSession = removeRepoFromWorkspaceSession(this.state.workspaceSession, id) this.state.workspaceSessionsByHostId = removeRepoFromHostWorkspaceSessions( @@ -4896,9 +4911,11 @@ export class Store { (r) => !(r.id === id && getRepoExecutionHostId(r) === hostId) ) const idStillPresent = this.state.repos.some((r) => r.id === id) - // Why: presets are repo-id-scoped (not host-scoped); drop them only when the last host's copy is gone. + // Why: presets and retirements are repo-id-scoped (not host-scoped); drop them only when the + // last host's copy is gone. if (!idStillPresent) { delete this.state.sparsePresetsByRepo[id] + delete this.state.retiredWorktreeNamesByRepo?.[id] } this.syncProjectHostSetupCompatibilityState() // Why: prune only this host's worktree metas if the id survives elsewhere; otherwise prune everything (matches removeProject). @@ -7215,32 +7232,32 @@ export class Store { this.scheduleSave() } - getRetiredWorktreeNames(workspaceKey: string): string[] { - return [...(this.state.retiredWorktreeNamesByWorkspaceKey?.[workspaceKey] ?? [])] + getRetiredWorktreeNames(repoId: string): string[] { + return [...(this.state.retiredWorktreeNamesByRepo?.[repoId] ?? [])] } - /** Records a generated workspace name as spent in this cwd namespace. Called with the name main - * actually used, not the one the renderer proposed — create can advance past it on collision. */ - addRetiredWorktreeName(workspaceKey: string, name: string): void { + /** Records a generated workspace name as spent for this repo. Called with the name main actually + * used, not the one the renderer proposed — the create path can advance past it on collision. */ + addRetiredWorktreeName(repoId: string, name: string): void { const normalized = normalizeRetirableGeneratedName(name) - if (!workspaceKey || !normalized) { + if (!repoId || !normalized) { return } - this.state.retiredWorktreeNamesByWorkspaceKey ??= {} - const existing = this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] + this.state.retiredWorktreeNamesByRepo ??= {} + const existing = this.state.retiredWorktreeNamesByRepo[repoId] if (existing?.includes(normalized)) { return } - this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] = existing - ? [...existing, normalized] - : [normalized] + this.state.retiredWorktreeNamesByRepo[repoId] = boundRetiredWorktreeNames( + existing ? [...existing, normalized] : [normalized] + ) this.scheduleSave() } /** Seeds retirements discovered by the one-time backfill. Merges rather than replaces so a * concurrent create during backfill is not lost. Returns true when anything was added. */ - mergeRetiredWorktreeNames(workspaceKey: string, names: Iterable): boolean { - if (!workspaceKey) { + mergeRetiredWorktreeNames(repoId: string, names: Iterable): boolean { + if (!repoId) { return false } const incoming = new Set() @@ -7253,8 +7270,8 @@ export class Store { if (incoming.size === 0) { return false } - this.state.retiredWorktreeNamesByWorkspaceKey ??= {} - const existing = this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] ?? [] + this.state.retiredWorktreeNamesByRepo ??= {} + const existing = this.state.retiredWorktreeNamesByRepo[repoId] ?? [] const merged = new Set(existing) for (const name of incoming) { merged.add(name) @@ -7262,7 +7279,7 @@ export class Store { if (merged.size === existing.length) { return false } - this.state.retiredWorktreeNamesByWorkspaceKey[workspaceKey] = [...merged] + this.state.retiredWorktreeNamesByRepo[repoId] = boundRetiredWorktreeNames([...merged]) this.scheduleSave() return true } diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 7013b17b05ff..9081df980d12 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -4092,7 +4092,7 @@ describe('OrcaRuntimeService', () => { worktrees: expect.arrayContaining([expect.objectContaining({ path: createdWorktree.path })]) } ) - expect(addRetiredWorktreeName).toHaveBeenCalledWith(expect.any(String), 'nautilus-2') + expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus-2') }) it('neither skips nor retires a name the user typed', async () => { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 5c4995b776dd..2efcbf73f034 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -936,8 +936,7 @@ import { } from '../worktree-create-candidates' import { ensureRetiredWorktreeNamesBackfilled, - getRetiredWorktreeNamesForRepo, - retireGeneratedWorktreeName + getRetiredWorktreeNamesForRepo } from '../worktree-name-retirement' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' @@ -21180,7 +21179,7 @@ export class OrcaRuntimeService { } catch (error) { console.warn(`[runtime] retirement backfill failed for repo ${repo.id}:`, error) } - return { [repo.id]: getRetiredWorktreeNamesForRepo(store, repo, settings) } + return { [repo.id]: getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings) } } async listDetectedManagedWorktrees( @@ -22374,7 +22373,7 @@ export class OrcaRuntimeService { let worktreePath = '' let worktreePathResolved = false const retiredNames = args.nameWasGenerated - ? new Set(getRetiredWorktreeNamesForRepo(this.store, repo, settings)) + ? new Set(getRetiredWorktreeNamesForRepo(this.store, repo, this.store.getRepos(), settings)) : null // Why: runtime/mobile create-from-review callers should get a new workspace // even when the PR branch or review branch name is already in use. @@ -22707,7 +22706,7 @@ export class OrcaRuntimeService { const worktreeId = `${repo.id}::${created.path}` // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. if (args.nameWasGenerated) { - retireGeneratedWorktreeName(this.store, repo, settings, effectiveSanitizedName) + this.store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) } const now = Date.now() // Why: PR/MR-created worktrees can start from a head ref/SHA while Source diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index 52b23b35a4e7..d298dccb4314 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -11,8 +11,7 @@ import { extractBucketLeafCandidates, getRetiredWorktreeNamesForRepo, normalizeRetirableGeneratedName, - resetRetirementCollisionKeyCacheForTests, - retireGeneratedWorktreeName + resetRetirementCollisionKeyCacheForTests } from './worktree-name-retirement' const FIRST = MARINE_CREATURES[0].toLowerCase() @@ -201,62 +200,67 @@ describe('discoverRetiredWorktreeNames', () => { describe('getRetiredWorktreeNamesForRepo', () => { const settingsFor = (nestWorkspaces: boolean): GlobalSettings => ({ workspaceDir: '/workspaces', nestWorkspaces }) as GlobalSettings - - it('shares retirements when two repos create into the same cwd namespace', () => { - const byKey = new Map() - const store = { - getRetiredWorktreeNames: (key: string) => byKey.get(key) ?? [], - addRetiredWorktreeName: (key: string, name: string) => - byKey.set(key, [...(byKey.get(key) ?? []), name]) + const storeOf = (byRepo: Record) => { + const calls: string[] = [] + return { + calls, + getRetiredWorktreeNames: (repoId: string) => { + calls.push(repoId) + return byRepo[repoId] ?? [] + } } - const settings = settingsFor(false) - const repoA = makeRepo('repo-a', '/repos/a') - const repoB = makeRepo('repo-b', '/repos/b') + } - retireGeneratedWorktreeName(store, repoA, settings, FIRST) + it('shares retirements when two repos create into the same cwd namespace', () => { + const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) + const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - expect(getRetiredWorktreeNamesForRepo(store, repoB, settings)).toEqual([FIRST]) + expect( + getRetiredWorktreeNamesForRepo(store, repos[1], repos, settingsFor(false)).sort() + ).toEqual([FIRST, SECOND].sort()) }) it('keeps independent nested repo paths in separate retirement domains', () => { - const byKey = new Map() - const store = { - getRetiredWorktreeNames: (key: string) => byKey.get(key) ?? [], - addRetiredWorktreeName: (key: string, name: string) => - byKey.set(key, [...(byKey.get(key) ?? []), name]) - } - const settings = settingsFor(true) - const repoA = makeRepo('repo-a', '/repos/a') - const repoB = makeRepo('repo-b', '/repos/b') + const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) + const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - retireGeneratedWorktreeName(store, repoA, settings, FIRST) - - expect(getRetiredWorktreeNamesForRepo(store, repoB, settings)).toEqual([]) - expect(getRetiredWorktreeNamesForRepo(store, repoA, settings)).toEqual([FIRST]) + expect(getRetiredWorktreeNamesForRepo(store, repos[1], repos, settingsFor(true))).toEqual([ + SECOND + ]) }) - it('survives a repo being removed and re-added under a new id', () => { - // Why: repo ids are regenerated on re-add. Keying the registry by repo id silently dropped - // every retirement for a path that had not changed at all. - const byKey = new Map() - const store = { - getRetiredWorktreeNames: (key: string) => byKey.get(key) ?? [], - addRetiredWorktreeName: (key: string, name: string) => - byKey.set(key, [...(byKey.get(key) ?? []), name]) + it('never probes a path for peers that hold no retirements', () => { + // Why: deriving a peer's namespace runs computeWorktreePath, which for a WSL repo is a blocking + // wsl.exe call. Reading `path` is exactly what a probe does, so count that. + const pathReads: string[] = [] + const spyRepo = (id: string, path: string): Repo => { + const repo = makeRepo(id, path) + return Object.defineProperty(repo, 'path', { + get: () => { + pathReads.push(id) + return path + } + }) as Repo } - const settings = settingsFor(true) + const store = storeOf({ 'repo-a': [FIRST] }) + const repos = [ + spyRepo('repo-a', '/repos/a'), + ...Array.from({ length: 20 }, (_unused, index) => spyRepo(`peer-${index}`, `/repos/${index}`)) + ] - retireGeneratedWorktreeName(store, makeRepo('repo-old', '/repos/a'), settings, FIRST) - - expect( - getRetiredWorktreeNamesForRepo(store, makeRepo('repo-new', '/repos/a'), settings) - ).toEqual([FIRST]) + expect(getRetiredWorktreeNamesForRepo(store, repos[0], repos, settingsFor(false))).toEqual([ + FIRST + ]) + expect(pathReads.filter((id) => id.startsWith('peer-'))).toEqual([]) }) it('reports nothing for a folder workspace, which has no generated worktree names', () => { - const store = { getRetiredWorktreeNames: () => [FIRST] } + const store = storeOf({ folder: [FIRST] }) const folderRepo = { ...makeRepo('folder', '/repos/folder'), kind: 'folder' as const } - expect(getRetiredWorktreeNamesForRepo(store, folderRepo, settingsFor(false))).toEqual([]) + + expect( + getRetiredWorktreeNamesForRepo(store, folderRepo, [folderRepo], settingsFor(false)) + ).toEqual([]) }) }) @@ -265,24 +269,26 @@ describe('ensureRetiredWorktreeNamesBackfilled', () => { const root = await mkdtemp(join(tmpdir(), 'orca-retirement-backfill-')) const workspaceRoot = join(root, 'workspaces') await mkdir(join(workspaceRoot, FIRST), { recursive: true }) - const merged: { key: string; names: string[] }[] = [] + const merged: { repoId: string; names: string[] }[] = [] const store = { - mergeRetiredWorktreeNames: (key: string, names: Iterable) => { - merged.push({ key, names: [...names] }) + mergeRetiredWorktreeNames: (repoId: string, names: Iterable) => { + merged.push({ repoId, names: [...names] }) return true } } - const repo = makeRepo('repo-a', join(root, 'repos', 'a')) const settings = { workspaceDir: workspaceRoot, nestWorkspaces: false } try { - await ensureRetiredWorktreeNamesBackfilled(store, repo, settings) - expect(merged).toHaveLength(1) - expect(merged[0].names).toContain(FIRST) + await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-a', '/repos/a'), settings) + expect(merged).toEqual([{ repoId: 'repo-a', names: [FIRST] }]) - // A second repo in the same namespace reuses the one in-flight scan. + // Why: the scan is cached per cwd namespace but the registry is per repo, so a second repo in + // the same namespace must still receive the merge rather than silently inheriting nothing. await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-b', '/repos/b'), settings) - expect(merged).toHaveLength(1) + expect(merged).toEqual([ + { repoId: 'repo-a', names: [FIRST] }, + { repoId: 'repo-b', names: [FIRST] } + ]) } finally { await rm(root, { force: true, recursive: true }) } @@ -291,7 +297,7 @@ describe('ensureRetiredWorktreeNamesBackfilled', () => { it('skips repos whose agent state lives on another host', async () => { const merged: string[] = [] const store = { - mergeRetiredWorktreeNames: (_key: string, names: Iterable) => { + mergeRetiredWorktreeNames: (_repoId: string, names: Iterable) => { merged.push(...names) return true } diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index 7698270bc373..a46c4b0b2b20 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -18,16 +18,13 @@ import { import { worktreePathComparisonKey } from './ipc/worktree-path-comparison' const RETIREMENT_PROBE_NAME = 'orca-retirement-probe' -const backfillsByStore = new WeakMap>>() +const scansByStore = new WeakMap>>>() type RetirementReadStore = { - getRetiredWorktreeNames(collisionKey: string): string[] -} -type RetirementWriteStore = { - addRetiredWorktreeName(collisionKey: string, name: string): void + getRetiredWorktreeNames(repoId: string): string[] } type RetirementBackfillStore = { - mergeRetiredWorktreeNames(collisionKey: string, names: Iterable): boolean + mergeRetiredWorktreeNames(repoId: string, names: Iterable): boolean } type RetirementPathSettings = Pick @@ -121,29 +118,40 @@ export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSe return key } +/** Stored per repo id, which is stable, but read across every repo that creates into the same cwd + * namespace — that is where a reissued name would actually collide. + * + * The peer scan is deliberately lazy: a repo's own retirements never touch a path, and a peer's + * namespace is derived only once that peer is known to hold retirements. Deriving one costs a + * blocking `wsl.exe` call for a WSL repo, so it must not be paid per repo on every create. */ export function getRetiredWorktreeNamesForRepo( store: RetirementReadStore, repo: Repo, + repos: readonly Repo[], settings: RetirementPathSettings ): string[] { if (isFolderRepo(repo)) { return [] } - return store.getRetiredWorktreeNames(getRetirementCollisionKey(repo, settings)) -} - -/** Records the name main actually used, not the one the client proposed — the create path can - * advance past a taken candidate. Call only for names Orca generated. */ -export function retireGeneratedWorktreeName( - store: RetirementWriteStore, - repo: Repo, - settings: RetirementPathSettings, - name: string -): void { - if (isFolderRepo(repo)) { - return + const names = new Set(store.getRetiredWorktreeNames(repo.id)) + let collisionKey: string | null = null + for (const candidate of repos) { + if (candidate.id === repo.id || isFolderRepo(candidate)) { + continue + } + const candidateNames = store.getRetiredWorktreeNames(candidate.id) + if (candidateNames.length === 0) { + continue + } + collisionKey ??= getRetirementCollisionKey(repo, settings) + if (getRetirementCollisionKey(candidate, settings) !== collisionKey) { + continue + } + for (const name of candidateNames) { + names.add(name) + } } - store.addRetiredWorktreeName(getRetirementCollisionKey(repo, settings), name) + return [...names] } function parentPath(path: string): string { @@ -157,27 +165,29 @@ export function ensureRetiredWorktreeNamesBackfilled( repo: Repo, settings: RetirementPathSettings ): Promise { - // Remote workspaces keep their agent state on the execution host, which this scan cannot see. + // Remote workspaces keep their agent state on the execution host, which this scan cannot see, so + // a re-added SSH repo does not recover its retirements the way a local one does. if (isFolderRepo(repo) || repo.connectionId) { return Promise.resolve() } - let storeBackfills = backfillsByStore.get(store) - if (!storeBackfills) { - storeBackfills = new Map() - backfillsByStore.set(store, storeBackfills) + let storeScans = scansByStore.get(store) + if (!storeScans) { + storeScans = new Map() + scansByStore.set(store, storeScans) } const collisionKey = getRetirementCollisionKey(repo, settings) - const existing = storeBackfills.get(collisionKey) - if (existing) { - return existing + let scan = storeScans.get(collisionKey) + if (!scan) { + scan = discoverRetiredWorktreeNames({ + workspaceRoots: [parentPath(getRetirementProbePath(repo, settings))] + }) + storeScans.set(collisionKey, scan) } - const backfill = discoverRetiredWorktreeNames({ - workspaceRoots: [parentPath(getRetirementProbePath(repo, settings))] - }).then((names) => { - store.mergeRetiredWorktreeNames(collisionKey, names) + // Why the merge sits outside the cached promise: the scan is per cwd namespace but the registry + // is per repo, so every repo that asks must receive it — not only the one that triggered it. + return scan.then((names) => { + store.mergeRetiredWorktreeNames(repo.id, names) }) - storeBackfills.set(collisionKey, backfill) - return backfill } async function readDirectoryNames(path: string): Promise { diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 7a860143d1f3..3610ad224f71 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -431,7 +431,7 @@ export function getDefaultPersistedState(homedir: string): PersistedState { projectGroups: [], folderWorkspaces: [], sparsePresetsByRepo: {}, - retiredWorktreeNamesByWorkspaceKey: {}, + retiredWorktreeNamesByRepo: {}, worktreeMeta: {}, worktreeLineageById: {}, workspaceLineageByChildKey: {}, diff --git a/src/shared/types.ts b/src/shared/types.ts index a8dd14962a8e..9be84019b4dd 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -3742,12 +3742,13 @@ export type PersistedState = { folderWorkspaceDiffComments?: Record /** Sparse-checkout presets keyed by repoId. */ sparsePresetsByRepo: Record - /** Generated workspace names already issued, keyed by the cwd namespace repos create into - * (execution host + workspace-root path), not by repoId — the collision this prevents is on the - * path, and repo ids change on remove/re-add while the path does not. Suppresses reissuing a - * name so a recreated workspace never lands on a prior occupant's path and inherits agent state - * keyed to that cwd. Grows monotonically; entries are never removed on workspace deletion. */ - retiredWorktreeNamesByWorkspaceKey?: Record + /** Generated workspace names already issued, keyed by repoId. Suppresses reissuing a name so a + * recreated workspace never lands on a prior occupant's path and inherits agent state keyed to + * that cwd. Grows monotonically within a repo — entries are never removed on workspace deletion + * — and is dropped wholesale when the repo is removed. Readers union across every repo that + * creates into the same cwd namespace, so the storage key stays the stable repo id while the + * guarantee follows the path. */ + retiredWorktreeNamesByRepo?: Record /** Per paired device last tab selection by worktree; keeps mobile navigation across host restarts. */ mobileClientTabSelectionsByDeviceId?: PersistedMobileClientTabSelections worktreeMeta: Record From f583faebc7f55a29dd56508030516061278856ed Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 18:01:10 -0700 Subject: [PATCH 12/20] docs(worktree): spell out why the retirement bound sits above the pool Names the trap directly: the neighbouring 50/200 bounds cap histories, so lowering this one to match them would silently start reissuing names whose agent state is still on disk. Also states that oldest-first eviction is a deliberate least-bad choice rather than a neutral one. --- src/main/persistence.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 0aee1c2bd16a..019ece2c31f2 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2335,13 +2335,17 @@ const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 // Why: bound removed-SSH-target history so remove/re-add churn can't grow the file unbounded. const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 -// Why: bound per-repo retirement so long-lived repos can't grow the file unbounded. Deliberately -// far above the 552-name pool — a cap below it would start reissuing names and reintroduce the bug -// this registry exists to prevent, so only `-2`/`-3` tier accumulation can ever reach it. +// Bounds per-repo retirement so a long-lived repo can't grow the state file unbounded. +// +// DO NOT lower this to match the two bounds above. Those cap histories, where evicting the oldest +// entry is harmless. This set is a correctness guarantee, so any cap below the 552-name pool hands +// back a name whose agent conversation is still on disk — the exact bug this registry exists to +// prevent. Only `-2`/`-3` tier accumulation can reach 2000, at roughly 21KB per repo. const MAX_RETIRED_WORKTREE_NAMES_PER_REPO = 2000 -/** Oldest-first eviction: entries are appended in retirement order, and the oldest paths are the - * ones whose agent state is likeliest to be gone already. */ +/** Oldest-first once the bound bites — a deliberate least-bad degradation rather than a neutral + * policy. Something must be dropped, and the oldest directories are the likeliest to have been + * reclaimed since, so their names are the safest of a bad set to reissue. */ function boundRetiredWorktreeNames(names: readonly string[]): string[] { return names.length > MAX_RETIRED_WORKTREE_NAMES_PER_REPO ? names.slice(names.length - MAX_RETIRED_WORKTREE_NAMES_PER_REPO) From b87360f6c0766de761da971e702230cb5a068a45 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 18:24:18 -0700 Subject: [PATCH 13/20] fix(worktree): send name provenance from the web runtime client This client hand-enumerates worktree.create params, so the new optional field was silently dropped and typecheck could not see it. On web and paired-desktop the host therefore never received it: generated names were never retired, and the host-side skip that backstops a stale suggestion was disabled too. The same client does fetch retired names for suggestions, so it was filtering against a registry nothing ever wrote to. The test asserts both directions, and fails without the fix. --- src/renderer/src/web/web-preload-api.test.ts | 13 +++++++++++++ src/renderer/src/web/web-preload-api.ts | 2 ++ 2 files changed, 15 insertions(+) diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index a7447369f4b6..380c1c89c432 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -3365,6 +3365,12 @@ describe('web worktree preload API', () => { targetBranch: 'release', isCrossRepository: false }) + await globals.window.api.worktrees.create({ + repoId: 'repo-1', + name: 'nautilus', + setupDecision: 'inherit', + nameWasGenerated: true + }) expect(runtimeCalls).toEqual([ { @@ -3404,8 +3410,15 @@ describe('web worktree preload API', () => { targetBranch: 'release', isCrossRepository: false } + }, + { + method: 'worktree.create', + params: expect.objectContaining({ repo: 'repo-1', nameWasGenerated: true }) } ]) + // Why: this client hand-enumerates create params, so a new optional field silently vanishes. + // Absent must mean user-typed — the host neither skips a retired candidate nor retires it. + expect(runtimeCalls[0]?.params).not.toHaveProperty('nameWasGenerated') }) it('encodes explicit push target clears for runtime worktree updates', async () => { diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index bfdd9cd13a40..8bd5e98c7b64 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1793,6 +1793,8 @@ function createWorktreesApi(): NonNullable['worktrees']> { const owned = await callRuntimeResultWithOwner<{ worktree: Worktree }>('worktree.create', { repo: args.repoId, name: args.name, + // Absent means user-typed, which is what the host must assume — so send it only when true. + ...(args.nameWasGenerated ? { nameWasGenerated: true } : {}), baseBranch: args.baseBranch, compareBaseRef: args.compareBaseRef, branchNameOverride: args.branchNameOverride, From 5052f1ccfa3e06c74e090fae3140e513fe29d743 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 18:24:30 -0700 Subject: [PATCH 14/20] fix(worktree): retire names that took more than one collision suffix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit isAutoGeneratedCreatureBranchName strips exactly one trailing -N, which is right for auto-rename eligibility but wrong here. Once the pool is spent the suggester emits nautilus-2, and a collision on that yields nautilus-2-3 — which a single strip leaves as nautilus-2, not a pool name, so retirement no-opped at exactly the tier where every base name is already gone. Strip repeated suffixes locally rather than moving the auto-rename predicate. --- src/main/worktree-name-retirement.test.ts | 9 ++++ src/main/worktree-name-retirement.ts | 56 ++++++++++++++++------- 2 files changed, 48 insertions(+), 17 deletions(-) diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index d298dccb4314..9d603f68ae3d 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -34,6 +34,15 @@ describe('normalizeRetirableGeneratedName', () => { expect(normalizeRetirableGeneratedName(`${FIRST}-100`)).toBe(`${FIRST}-100`) }) + it('retires a suffixed name that itself took a collision suffix', () => { + // Once the pool is spent the suggester emits `-2`; a collision on that yields + // `-2-3`. Stripping only one suffix leaves `-2`, which is not a pool name, so + // retirement would no-op at exactly the tier where every base name is already gone. + expect(normalizeRetirableGeneratedName(`${FIRST}-2-3`)).toBe(`${FIRST}-2-3`) + expect(normalizeRetirableGeneratedName(`${FIRST}-2-3-4`)).toBe(`${FIRST}-2-3-4`) + expect(normalizeRetirableGeneratedName('fix-login-2-3')).toBeNull() + }) + it('rejects names outside the pool and absurdly long input', () => { expect(normalizeRetirableGeneratedName('fix-login')).toBeNull() expect(normalizeRetirableGeneratedName('')).toBeNull() diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index a46c4b0b2b20..16d3c3ce0246 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -1,7 +1,7 @@ import { readdir } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' -import { isAutoGeneratedCreatureBranchName } from '../shared/branch-name-from-work' +import { MARINE_CREATURES } from '../shared/marine-creatures' import { getRepoExecutionHostId } from '../shared/execution-host' import { isFolderRepo } from '../shared/repo-kind' import type { GlobalSettings, Repo } from '../shared/types' @@ -12,11 +12,14 @@ import { import { computeRemoteWorktreePath, computeWorktreePath, + computeWorktreePathAsync, getWorktreePathSettings, hasRepoWorktreeBasePath } from './ipc/worktree-logic' import { worktreePathComparisonKey } from './ipc/worktree-path-comparison' +import { hasCachedWslHome, parseWslPath } from './wsl' +const POOL_NAMES: ReadonlySet = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) const RETIREMENT_PROBE_NAME = 'orca-retirement-probe' const scansByStore = new WeakMap>>>() @@ -28,14 +31,23 @@ type RetirementBackfillStore = { } type RetirementPathSettings = Pick -/** Why reuse the auto-rename predicate: it already defines "a name Orca picked, not the user", is - * already tested, and a second definition here drifted — its `-([2-9]\d*)` never matched `-10`. */ +/** Strips EVERY trailing numeric suffix, not just one. Once the pool is spent the suggester emits + * `nautilus-2`, and a collision on that yields `nautilus-2-3` — which a single strip leaves as + * `nautilus-2`, not a pool name, so retirement would silently no-op on exactly the tier where the + * pool is already exhausted. Deliberately not shared with `isAutoGeneratedCreatureBranchName`: + * auto-rename eligibility is a different question and its single-strip behavior is intended. */ export function normalizeRetirableGeneratedName(name: string): string | null { const normalized = name.trim().toLowerCase() if (normalized.length > 256) { return null } - return isAutoGeneratedCreatureBranchName(normalized) ? normalized : null + let base = normalized + let stripped = base.replace(/-\d+$/, '') + while (stripped !== base) { + base = stripped + stripped = base.replace(/-\d+$/, '') + } + return base && POOL_NAMES.has(base) ? normalized : null } /** Why: over-retiring costs one name from a 552-entry pool; under-retiring reissues a path whose @@ -111,6 +123,12 @@ export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSe return cached } const key = `${hostId}:${worktreePathComparisonKey(getRetirementProbePath(repo, settings))}` + // Why not always cache: only the WSL home *success* path is cached upstream, so a stopped distro + // yields a fallback namespace. Memoizing that would strand the repo there for the whole session. + const wsl = parseWslPath(repo.path) + if (wsl && !hasCachedWslHome(wsl.distro)) { + return key + } if (collisionKeyCache.size >= COLLISION_KEY_CACHE_MAX) { collisionKeyCache.clear() } @@ -160,7 +178,10 @@ function parentPath(path: string): string { return separatorIndex < 0 ? '' : trimmed.slice(0, separatorIndex) } -export function ensureRetiredWorktreeNamesBackfilled( +/** Async throughout on purpose: this runs on composer open, not just at create time, and the sync + * probe would resolve a WSL home with a blocking `wsl.exe` call — up to 5s of frozen main process + * on a stopped distro. Resolving it here also warms the shared cache for later sync callers. */ +export async function ensureRetiredWorktreeNamesBackfilled( store: RetirementBackfillStore, repo: Repo, settings: RetirementPathSettings @@ -168,26 +189,27 @@ export function ensureRetiredWorktreeNamesBackfilled( // Remote workspaces keep their agent state on the execution host, which this scan cannot see, so // a re-added SSH repo does not recover its retirements the way a local one does. if (isFolderRepo(repo) || repo.connectionId) { - return Promise.resolve() + return } + const probePath = await computeWorktreePathAsync( + RETIREMENT_PROBE_NAME, + repo.path, + getWorktreePathSettings(repo, settings) + ) + const scanKey = `${getRepoExecutionHostId(repo)}:${worktreePathComparisonKey(probePath)}` let storeScans = scansByStore.get(store) if (!storeScans) { storeScans = new Map() scansByStore.set(store, storeScans) } - const collisionKey = getRetirementCollisionKey(repo, settings) - let scan = storeScans.get(collisionKey) + let scan = storeScans.get(scanKey) if (!scan) { - scan = discoverRetiredWorktreeNames({ - workspaceRoots: [parentPath(getRetirementProbePath(repo, settings))] - }) - storeScans.set(collisionKey, scan) + scan = discoverRetiredWorktreeNames({ workspaceRoots: [parentPath(probePath)] }) + storeScans.set(scanKey, scan) } - // Why the merge sits outside the cached promise: the scan is per cwd namespace but the registry - // is per repo, so every repo that asks must receive it — not only the one that triggered it. - return scan.then((names) => { - store.mergeRetiredWorktreeNames(repo.id, names) - }) + // Why the merge sits outside the cached scan: the scan is per cwd namespace but the registry is + // per repo, so every repo that asks must receive it — not only the one that triggered it. + store.mergeRetiredWorktreeNames(repo.id, await scan) } async function readDirectoryNames(path: string): Promise { From 348bf5d4722374f7b3c3fe5ddf8635783cd18b98 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 18:24:31 -0700 Subject: [PATCH 15/20] perf(worktree): keep the retirement backfill off the blocking WSL probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The backfill runs on composer repo-select, not just at create time, and it derived the probe path synchronously — which for a WSL repo with a mirrored workspace dir reaches getWslHome and its blocking execFileSync('wsl.exe'). A stopped distro froze the main process for up to 5s on composer open. Adds an async twin of computeWorktreePath and uses it for the probe. Resolving the home there also warms the shared cache, so later sync callers are free. Also stops memoizing the collision key when the WSL home is still unresolved: only the success path is cached upstream, so caching the fallback namespace would strand the repo there for the rest of the session. --- src/main/ipc/worktree-logic.ts | 33 ++++++++++++++++++++++++++++++++- src/main/wsl.ts | 6 ++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/main/ipc/worktree-logic.ts b/src/main/ipc/worktree-logic.ts index a056d657f028..fe61f943d143 100644 --- a/src/main/ipc/worktree-logic.ts +++ b/src/main/ipc/worktree-logic.ts @@ -4,7 +4,7 @@ import { isWindowsAbsolutePathLike, resolveRuntimePath } from '../../shared/cros import { isWslUncPath } from '../../shared/wsl-paths' import { splitWorktreeId } from '../../shared/worktree-id' import { replaceKnownEmojiWithShortcodes } from '../../shared/emoji-shortcode-catalog' -import { getWslHome, parseWslPath } from '../wsl' +import { getWslHome, getWslHomeAsync, parseWslPath } from '../wsl' type WorktreePathSettings = Pick type WorktreeBasePathRepo = Pick @@ -112,6 +112,37 @@ export function computeWorktreePath( return pathOps.join(workspaceRoot, sanitizedName) } +/** Async twin of computeWorktreePath. Same result; resolves the WSL home without blocking the main + * thread, so callers off the create path never freeze the app on a stopped distro. */ +export async function computeWorktreePathAsync( + sanitizedName: string, + repoPath: string, + settings: WorktreePathSettings +): Promise { + const workspaceRoot = await computeWorkspaceRootAsync(repoPath, settings) + const pathOps = getRuntimePathOps(repoPath, workspaceRoot) + + if (settings.nestWorkspaces) { + const repoName = pathOps.basename(repoPath).replace(/\.git$/, '') + return pathOps.join(workspaceRoot, repoName, sanitizedName) + } + return pathOps.join(workspaceRoot, sanitizedName) +} + +async function computeWorkspaceRootAsync( + repoPath: string, + settings: { workspaceDir: string } +): Promise { + const wsl = parseWslPath(repoPath) + if (wsl && shouldMirrorWorkspaceDirInsideWsl(repoPath, settings.workspaceDir)) { + const wslHome = await getWslHomeAsync(wsl.distro) + if (wslHome) { + return win32.join(wslHome, 'orca', 'workspaces') + } + } + return resolveWorkspaceDirForRepo(repoPath, settings.workspaceDir) +} + export function computeWorkspaceRoot(repoPath: string, settings: { workspaceDir: string }): string { const wsl = parseWslPath(repoPath) if (wsl && shouldMirrorWorkspaceDirInsideWsl(repoPath, settings.workspaceDir)) { diff --git a/src/main/wsl.ts b/src/main/wsl.ts index 8311170faeb4..31c1c9a8a5cd 100644 --- a/src/main/wsl.ts +++ b/src/main/wsl.ts @@ -303,6 +303,12 @@ export function getWslHome(distro: string): string | null { } } +/** Pure cache lookup — never probes. Lets callers that memoize a derived value avoid caching one + * built from the unresolved fallback, since only the success path is cached above. */ +export function hasCachedWslHome(distro: string): boolean { + return wslHomeCache.has(distro) +} + export async function getWslHomeAsync(distro: string): Promise { if (wslHomeCache.has(distro)) { return wslHomeCache.get(distro)! From 58e8c7d4810052e848c6cb3f019e7a88d2015e76 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 18:24:41 -0700 Subject: [PATCH 16/20] fix(worktree): hold retired names across a refresh instead of blanking MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshKey changes on every workspace-list mutation, so create-multiple refetches after each create and the hook returned an empty list until the refetch landed — precisely the window in which resetForNextCreate clears the name field and a fresh suggestion is drawn. Keep the previous answer while revalidating and reset only when the repo changes; a failed refresh keeps what was already loaded rather than un-retiring everything. Also makes the returned array referentially stable, so the suggestion memo downstream stops rerunning on every refetch. --- .../src/hooks/useRetiredWorktreeNames.test.ts | 85 +++++++++++++++++++ .../src/hooks/useRetiredWorktreeNames.ts | 22 +++-- 2 files changed, 102 insertions(+), 5 deletions(-) create mode 100644 src/renderer/src/hooks/useRetiredWorktreeNames.test.ts diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts new file mode 100644 index 000000000000..452771caf144 --- /dev/null +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts @@ -0,0 +1,85 @@ +// @vitest-environment happy-dom + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { renderHook, waitFor } from '@testing-library/react' +import { useRetiredWorktreeNames } from './useRetiredWorktreeNames' + +const listRetiredNames = vi.fn() + +beforeEach(() => { + listRetiredNames.mockReset() + Object.assign(window, { api: { worktrees: { listRetiredNames } } }) +}) + +describe('useRetiredWorktreeNames', () => { + it('keeps the previous names while a refresh is in flight', async () => { + // Why: refreshKey changes on every workspace-list mutation, so create-multiple refetches after + // each create. Dropping to empty in between would suggest a spent name in exactly that window. + listRetiredNames.mockResolvedValueOnce(['nautilus']) + const { result, rerender } = renderHook( + ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), + { initialProps: { key: 'a' } } + ) + await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + + let resolveSecond: (names: string[]) => void = () => {} + listRetiredNames.mockReturnValueOnce( + new Promise((resolve) => { + resolveSecond = resolve + }) + ) + rerender({ key: 'b' }) + + expect(result.current.names).toEqual(['nautilus']) + expect(result.current.loading).toBe(true) + + resolveSecond(['nautilus', 'seahorse']) + await waitFor(() => expect(result.current.names).toEqual(['nautilus', 'seahorse'])) + }) + + it('returns a referentially stable array across refreshes that change nothing', async () => { + // The suggestion memo downstream keys on this array; a new identity per refetch reruns it. + const names = ['nautilus'] + listRetiredNames.mockResolvedValue(names) + const { result, rerender } = renderHook( + ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), + { initialProps: { key: 'a' } } + ) + await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + const first = result.current.names + + rerender({ key: 'b' }) + + expect(result.current.names).toBe(first) + }) + + it('drops names when the repo changes rather than showing another repo pool', async () => { + listRetiredNames.mockResolvedValueOnce(['nautilus']) + const { result, rerender } = renderHook( + ({ repoId }: { repoId: string }) => useRetiredWorktreeNames(repoId, 'key'), + { initialProps: { repoId: 'repo-1' } } + ) + await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + + listRetiredNames.mockReturnValueOnce(new Promise(() => {})) + rerender({ repoId: 'repo-2' }) + + expect(result.current.names).toEqual([]) + }) + + it('keeps previously loaded names when a refresh fails', async () => { + listRetiredNames.mockResolvedValueOnce(['nautilus']) + const { result, rerender } = renderHook( + ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), + { initialProps: { key: 'a' } } + ) + await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + + vi.spyOn(console, 'warn').mockImplementation(() => {}) + listRetiredNames.mockRejectedValueOnce(new Error('host unreachable')) + rerender({ key: 'b' }) + + await waitFor(() => expect(result.current.loading).toBe(false)) + expect(result.current.names).toEqual(['nautilus']) + }) +}) diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.ts index 8dfdc0bb5924..f68c5c91e1b4 100644 --- a/src/renderer/src/hooks/useRetiredWorktreeNames.ts +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.ts @@ -1,24 +1,32 @@ import { useEffect, useState } from 'react' +const NO_RETIRED_NAMES: readonly string[] = [] + /** Names already spent in a repo, including workspaces that have since been deleted. * * Why this is fetched rather than derived from the worktree list: a deleted workspace leaves no * row behind, but its directory may still hold agent conversation state keyed by that path. Only * the host-side registry remembers it, so name suggestions must ask for it explicitly. * + * Stale-while-revalidate across `refreshKey`, reset only when the repo changes. A refresh fires on + * every workspace-list mutation, so create-multiple refetches after each create — dropping to + * empty in between would suggest a spent name in exactly that window, which is when + * `resetForNextCreate` clears the field. Holding the previous answer also keeps the returned array + * referentially stable, so the suggestion memo downstream does not rerun on every refetch. + * * Failure returns an empty set, which degrades to the pre-existing behavior (a spent name can be * suggested) rather than blocking workspace creation. */ export function useRetiredWorktreeNames( repoId: string | null | undefined, refreshKey: unknown ): { - names: string[] + names: readonly string[] loading: boolean } { const [loaded, setLoaded] = useState<{ repoId: string refreshKey: unknown - names: string[] + names: readonly string[] } | null>(null) useEffect(() => { @@ -36,7 +44,12 @@ export function useRetiredWorktreeNames( }) .catch((err) => { if (!cancelled) { - setLoaded({ repoId, refreshKey, names: [] }) + // Keep whatever a previous refresh loaded; a transient failure must not un-retire names. + setLoaded((previous) => ({ + repoId, + refreshKey, + names: previous?.repoId === repoId ? previous.names : NO_RETIRED_NAMES + })) } console.warn(`Failed to load retired workspace names for repo ${repoId}:`, err) }) @@ -46,8 +59,7 @@ export function useRetiredWorktreeNames( }, [refreshKey, repoId]) return { - names: - loaded && loaded.repoId === repoId && loaded.refreshKey === refreshKey ? loaded.names : [], + names: loaded && loaded.repoId === repoId ? loaded.names : NO_RETIRED_NAMES, loading: Boolean(repoId) && (loaded?.repoId !== repoId || loaded?.refreshKey !== refreshKey) } } From 07b207c5fa6807dd31c10d4d3faba4af6d255b85 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:58:33 -0700 Subject: [PATCH 17/20] refactor(worktree): put the retired-name cache rules on one implementation The desktop and mobile hooks that fetch retired names had already drifted four ways. The transports genuinely differ (IPC vs RPC), but the caching rules must not, and mobile's copy reset to [] on any error -- which un-retires every name for the rest of the sheet session, the one outcome retirement exists to prevent. Moves the rules into src/shared/worktree/retired-name-cache: response normalization, the never-leak-across-repos rule, and the hold-previous-on- failure rule. Pure, no React, because src/shared is on the main process's import graph. Each platform keeps its own transport and effect. Mobile moves up to desktop's behavior: it now holds the previous answer through a failed refresh, and refetches when the workspace list changes instead of never refetching after mount. Also drops the unused `loading` return. Neither platform consumed it; its only consumer was the Create-button gate reviewed out earlier, and removing it makes that regression unexpressible. --- mobile/src/components/NewWorktreeModal.tsx | 14 ++- .../use-retired-worktree-names.test.tsx | 116 ++++++++++++++++++ .../worktree/use-retired-worktree-names.ts | 63 +++++----- .../sidebar/worktree-name-suggestions.ts | 8 +- src/renderer/src/hooks/useComposerState.ts | 7 +- .../src/hooks/useRetiredWorktreeNames.test.ts | 37 ++++-- .../src/hooks/useRetiredWorktreeNames.ts | 55 +++------ src/renderer/src/web/web-preload-api.ts | 9 +- .../worktree/retired-name-cache.test.ts | 76 ++++++++++++ src/shared/worktree/retired-name-cache.ts | 54 ++++++++ 10 files changed, 343 insertions(+), 96 deletions(-) create mode 100644 mobile/src/worktree/use-retired-worktree-names.test.tsx create mode 100644 src/shared/worktree/retired-name-cache.test.ts create mode 100644 src/shared/worktree/retired-name-cache.ts diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 0da42f35f215..f10a96f17c04 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -189,8 +189,16 @@ function NewWorktreeModalContent({ const [selectedRepo, setSelectedRepo] = useState(null) // Why: a deleted workspace's directory can still hold agent conversation state keyed by cwd, so // its name must never be suggested again. Fetched per selected repo while the sheet is open. - // Create is never gated on it: the host skips retired candidates before doing any git work. - const { names: retiredWorktreeNames } = useRetiredWorktreeNames(client, selectedRepo?.id) + // Keyed on the path set rather than the array so a poll that changes nothing does not refetch. + const retiredNamesRefreshKey = useMemo( + () => [...(existingWorktreePaths ?? [])].sort().join('\0'), + [existingWorktreePaths] + ) + const retiredWorktreeNames = useRetiredWorktreeNames( + client, + selectedRepo?.id, + retiredNamesRefreshKey + ) const { drawerView, formSheetVisible, formSheetInteractive, transitionDrawer, openSourceDrawer } = useNewWorktreeDrawerNavigation(visible) const createInFlightRef = useRef(false) @@ -662,6 +670,8 @@ function NewWorktreeModalContent({ client, repoId: selectedRepo.id, baseName, + // `baseName` is the suggestion exactly when the user typed nothing, so no identity check + // is needed — desktop's seeded composer needs one (useComposerState `nameWasGenerated`). nameWasGenerated: !trimmedName, createdWithAgentId, comment: trimmedNote, diff --git a/mobile/src/worktree/use-retired-worktree-names.test.tsx b/mobile/src/worktree/use-retired-worktree-names.test.tsx new file mode 100644 index 000000000000..34fbe9a6506d --- /dev/null +++ b/mobile/src/worktree/use-retired-worktree-names.test.tsx @@ -0,0 +1,116 @@ +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { describe, expect, it } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import { useRetiredWorktreeNames } from './use-retired-worktree-names' + +type Pending = { resolve: (response: unknown) => void; reject: (err: Error) => void } + +/** Renders the hook against a deferred RPC client so a test decides exactly when each + * `worktree.listRetiredNames` lands, and for which repo. */ +function mountNames() { + const pending: Pending[] = [] + const requests: { method: string; params: unknown }[] = [] + let latest: readonly string[] = [] + + const client = { + sendRequest: (method: string, params: unknown) => { + requests.push({ method, params }) + return new Promise((resolve, reject) => pending.push({ resolve, reject })) + } + } as unknown as RpcClient + + function Probe({ repoId, refreshKey }: { repoId: string | null; refreshKey: string }) { + latest = useRetiredWorktreeNames(client, repoId, refreshKey) + return null + } + + let renderer!: ReturnType + act(() => { + renderer = create(createElement(Probe, { repoId: 'repo-1', refreshKey: 'a' })) + }) + return { + get names(): readonly string[] { + return latest + }, + requests, + rerender(props: { repoId: string | null; refreshKey: string }) { + act(() => { + renderer.update(createElement(Probe, props)) + }) + }, + async settle(index: number, retiredNamesByRepo: Record) { + await act(async () => { + pending[index]!.resolve({ result: { retiredNamesByRepo } }) + await Promise.resolve() + }) + }, + async fail(index: number) { + await act(async () => { + pending[index]!.reject(new Error('host unreachable')) + await Promise.resolve() + }) + } + } +} + +describe('useRetiredWorktreeNames', () => { + it('reads the selected repo out of the response envelope', async () => { + const probe = mountNames() + expect(probe.requests[0]).toEqual({ + method: 'worktree.listRetiredNames', + params: { repo: 'id:repo-1' } + }) + await probe.settle(0, { 'repo-1': ['nautilus'], 'repo-2': ['seahorse'] }) + expect(probe.names).toEqual(['nautilus']) + }) + + it('answers empty for a host that omits the field', async () => { + const probe = mountNames() + await probe.settle(0, {}) + expect(probe.names).toEqual([]) + }) + + // Regression: this hook used to reset to [] on any error, un-retiring every name for the rest of + // the sheet session. Desktop always held the previous answer; both now share that rule. + it('keeps previously loaded names when a refresh fails', async () => { + const probe = mountNames() + await probe.settle(0, { 'repo-1': ['nautilus'] }) + expect(probe.names).toEqual(['nautilus']) + + probe.rerender({ repoId: 'repo-1', refreshKey: 'b' }) + await probe.fail(1) + + expect(probe.names).toEqual(['nautilus']) + }) + + // Regression: the effect used to depend on [client, repoId] only, so a workspace created while + // the sheet was open never made it into the pool. + it('refetches when the workspace list changes', async () => { + const probe = mountNames() + await probe.settle(0, { 'repo-1': ['nautilus'] }) + + probe.rerender({ repoId: 'repo-1', refreshKey: 'b' }) + expect(probe.requests).toHaveLength(2) + // The previous answer stays visible while the refetch is in flight. + expect(probe.names).toEqual(['nautilus']) + + await probe.settle(1, { 'repo-1': ['nautilus', 'seahorse'] }) + expect(probe.names).toEqual(['nautilus', 'seahorse']) + }) + + it('drops names when the repo changes rather than showing another repo pool', async () => { + const probe = mountNames() + await probe.settle(0, { 'repo-1': ['nautilus'] }) + + probe.rerender({ repoId: 'repo-2', refreshKey: 'a' }) + expect(probe.names).toEqual([]) + }) + + it('reports nothing without a selected repo, and asks the host nothing', () => { + const probe = mountNames() + probe.rerender({ repoId: null, refreshKey: 'a' }) + expect(probe.names).toEqual([]) + expect(probe.requests).toHaveLength(1) + }) +}) diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts index a641b3f9d4b4..ee3872a69487 100644 --- a/mobile/src/worktree/use-retired-worktree-names.ts +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -1,57 +1,50 @@ import { useEffect, useState } from 'react' +import { + readRetiredNamesForRepo, + retiredNamesAfterRefresh, + selectRetiredNames, + type RetiredNamesLoad +} from '../../../src/shared/worktree/retired-name-cache' import type { RpcClient } from '../transport/rpc-client' /** Names already spent in a repo, including workspaces that have since been deleted. * * Why a targeted request rather than the workspace catalog: the catalog is served by `worktree.ps`, * which carries rows only. Retired names are needed just while the create sheet is open and only - * for one repo, so this mirrors the desktop hook and asks for exactly that. + * for one repo, so this asks for exactly that. * - * Hosts predating the field omit it, and any failure yields an empty list, so this degrades to - * deduping against live workspaces alone — the behavior before retirement existed. */ + * `refreshKey` must change on every workspace-list mutation. Caching rules live in + * `retired-name-cache` so this and the desktop hook cannot drift on what a failure means, and no + * loading state is reported because create is never gated on this fetch. */ export function useRetiredWorktreeNames( client: RpcClient | null | undefined, - repoId: string | null | undefined -): { names: readonly string[]; loading: boolean } { - const [loaded, setLoaded] = useState<{ - repoId: string - names: readonly string[] - } | null>(null) + repoId: string | null | undefined, + refreshKey: unknown +): readonly string[] { + const [loaded, setLoaded] = useState(null) + const activeRepoId = client && repoId ? repoId : null useEffect(() => { - if (!client || !repoId) { + if (!client || !activeRepoId) { setLoaded(null) return } let cancelled = false + const settle = (names: readonly string[] | null): void => { + if (!cancelled) { + setLoaded((previous) => retiredNamesAfterRefresh(previous, activeRepoId, names)) + } + } void client - .sendRequest('worktree.listRetiredNames', { repo: `id:${repoId}` }) - .then((response) => { - if (cancelled) { - return - } - const result = (response as { result?: unknown }).result as - | { retiredNamesByRepo?: Record } - | undefined - const names = result?.retiredNamesByRepo?.[repoId] - setLoaded({ - repoId, - // A host can answer with a malformed row; a non-string would throw when normalized. - names: Array.isArray(names) ? names.filter((name) => typeof name === 'string') : [] - }) - }) - .catch(() => { - if (!cancelled) { - setLoaded({ repoId, names: [] }) - } - }) + .sendRequest('worktree.listRetiredNames', { repo: `id:${activeRepoId}` }) + .then((response) => + settle(readRetiredNamesForRepo((response as { result?: unknown }).result, activeRepoId)) + ) + .catch(() => settle(null)) return () => { cancelled = true } - }, [client, repoId]) + }, [activeRepoId, client, refreshKey]) - return { - names: loaded && loaded.repoId === repoId ? loaded.names : [], - loading: Boolean(client && repoId) && loaded?.repoId !== repoId - } + return selectRetiredNames(loaded, activeRepoId) } diff --git a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts index bf1ebebe5faf..64827392bb7a 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts @@ -1,7 +1,7 @@ -import { basename } from '@/lib/path' import { normalizeSuggestedName, - selectSuggestedCreatureName + selectSuggestedCreatureName, + suggestionPathBasename } from '../../../../shared/worktree-name-suggestion' type WorktreePathLike = { @@ -14,7 +14,9 @@ function collectUsedNames(worktreesByRepo: Record): const usedNames = new Set() for (const worktrees of Object.values(worktreesByRepo)) { for (const worktree of worktrees) { - usedNames.add(normalizeSuggestedName(basename(worktree.path))) + // Shared basename, not `@/lib/path`'s: mobile keys collisions the same way, and two copies of + // the key could drift into suggesting a name that is in fact taken. + usedNames.add(normalizeSuggestedName(suggestionPathBasename(worktree.path))) } } return usedNames diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index 8f9f56b5573e..8356f379a84d 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -1601,9 +1601,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS .join('\0'), [repoId, worktreesByRepo] ) - // Create is never gated on this load: the host skips retired candidates before any git work, so - // a pending fetch can only cost a suggestion, never correctness. - const { names: retiredWorktreeNames } = useRetiredWorktreeNames(repoId, retiredNamesRefreshKey) + const retiredWorktreeNames = useRetiredWorktreeNames(repoId, retiredNamesRefreshKey) const fallbackCreatureName = useMemo( () => getSuggestedCreatureName(worktreesByRepo, undefined, retiredWorktreeNames), [worktreesByRepo, retiredWorktreeNames] @@ -3650,6 +3648,9 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS } // Why: only a name Orca generated may be retired — the creature pool contains ordinary words // ("orca", "runner", "molly") a user can type deliberately and expect to reuse. + // The identity check is what a linked PR/issue seed makes necessary here; mobile's blank-create + // path (NewWorktreeModal, `nameWasGenerated: !trimmedName`) has no other seed, so it can't + // share this expression. Same rule, two submit paths — change both together. const nameWasGenerated = !name.trim() && workspaceName === fallbackCreatureName const submitBaseBranch = smartGitHubResolution.kind === 'pr-start-point' diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts index 452771caf144..2c795a7c536e 100644 --- a/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts @@ -20,7 +20,7 @@ describe('useRetiredWorktreeNames', () => { ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } ) - await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(['nautilus'])) let resolveSecond: (names: string[]) => void = () => {} listRetiredNames.mockReturnValueOnce( @@ -30,11 +30,10 @@ describe('useRetiredWorktreeNames', () => { ) rerender({ key: 'b' }) - expect(result.current.names).toEqual(['nautilus']) - expect(result.current.loading).toBe(true) + expect(result.current).toEqual(['nautilus']) resolveSecond(['nautilus', 'seahorse']) - await waitFor(() => expect(result.current.names).toEqual(['nautilus', 'seahorse'])) + await waitFor(() => expect(result.current).toEqual(['nautilus', 'seahorse'])) }) it('returns a referentially stable array across refreshes that change nothing', async () => { @@ -45,12 +44,12 @@ describe('useRetiredWorktreeNames', () => { ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } ) - await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) - const first = result.current.names + await waitFor(() => expect(result.current).toEqual(['nautilus'])) + const first = result.current rerender({ key: 'b' }) - expect(result.current.names).toBe(first) + expect(result.current).toBe(first) }) it('drops names when the repo changes rather than showing another repo pool', async () => { @@ -59,12 +58,12 @@ describe('useRetiredWorktreeNames', () => { ({ repoId }: { repoId: string }) => useRetiredWorktreeNames(repoId, 'key'), { initialProps: { repoId: 'repo-1' } } ) - await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(['nautilus'])) listRetiredNames.mockReturnValueOnce(new Promise(() => {})) rerender({ repoId: 'repo-2' }) - expect(result.current.names).toEqual([]) + expect(result.current).toEqual([]) }) it('keeps previously loaded names when a refresh fails', async () => { @@ -73,13 +72,25 @@ describe('useRetiredWorktreeNames', () => { ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } ) - await waitFor(() => expect(result.current.names).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(['nautilus'])) - vi.spyOn(console, 'warn').mockImplementation(() => {}) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) listRetiredNames.mockRejectedValueOnce(new Error('host unreachable')) rerender({ key: 'b' }) - await waitFor(() => expect(result.current.loading).toBe(false)) - expect(result.current.names).toEqual(['nautilus']) + await waitFor(() => expect(warn).toHaveBeenCalled()) + expect(result.current).toEqual(['nautilus']) + }) + + it('refetches when the refresh key changes', async () => { + listRetiredNames.mockResolvedValue(['nautilus']) + const { rerender } = renderHook( + ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), + { initialProps: { key: 'a' } } + ) + await waitFor(() => expect(listRetiredNames).toHaveBeenCalledTimes(1)) + + rerender({ key: 'b' }) + await waitFor(() => expect(listRetiredNames).toHaveBeenCalledTimes(2)) }) }) diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.ts index f68c5c91e1b4..c4a7e9488423 100644 --- a/src/renderer/src/hooks/useRetiredWorktreeNames.ts +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.ts @@ -1,6 +1,9 @@ import { useEffect, useState } from 'react' - -const NO_RETIRED_NAMES: readonly string[] = [] +import { + retiredNamesAfterRefresh, + selectRetiredNames, + type RetiredNamesLoad +} from '../../../shared/worktree/retired-name-cache' /** Names already spent in a repo, including workspaces that have since been deleted. * @@ -8,26 +11,17 @@ const NO_RETIRED_NAMES: readonly string[] = [] * row behind, but its directory may still hold agent conversation state keyed by that path. Only * the host-side registry remembers it, so name suggestions must ask for it explicitly. * - * Stale-while-revalidate across `refreshKey`, reset only when the repo changes. A refresh fires on - * every workspace-list mutation, so create-multiple refetches after each create — dropping to - * empty in between would suggest a spent name in exactly that window, which is when - * `resetForNextCreate` clears the field. Holding the previous answer also keeps the returned array - * referentially stable, so the suggestion memo downstream does not rerun on every refetch. + * `refreshKey` must change on every workspace-list mutation, so create-multiple refetches after + * each create. Caching rules live in `retired-name-cache` because the mobile hook obeys the same + * ones over a different transport. * - * Failure returns an empty set, which degrades to the pre-existing behavior (a spent name can be - * suggested) rather than blocking workspace creation. */ + * Deliberately reports no loading state: create is never gated on this fetch — the host skips + * retired candidates before any git work, so a pending fetch can only cost a suggestion. */ export function useRetiredWorktreeNames( repoId: string | null | undefined, refreshKey: unknown -): { - names: readonly string[] - loading: boolean -} { - const [loaded, setLoaded] = useState<{ - repoId: string - refreshKey: unknown - names: readonly string[] - } | null>(null) +): readonly string[] { + const [loaded, setLoaded] = useState(null) useEffect(() => { if (!repoId) { @@ -35,22 +29,16 @@ export function useRetiredWorktreeNames( return } let cancelled = false + const settle = (names: readonly string[] | null): void => { + if (!cancelled) { + setLoaded((previous) => retiredNamesAfterRefresh(previous, repoId, names)) + } + } void window.api.worktrees .listRetiredNames({ repoId }) - .then((names) => { - if (!cancelled) { - setLoaded({ repoId, refreshKey, names }) - } - }) + .then(settle) .catch((err) => { - if (!cancelled) { - // Keep whatever a previous refresh loaded; a transient failure must not un-retire names. - setLoaded((previous) => ({ - repoId, - refreshKey, - names: previous?.repoId === repoId ? previous.names : NO_RETIRED_NAMES - })) - } + settle(null) console.warn(`Failed to load retired workspace names for repo ${repoId}:`, err) }) return () => { @@ -58,8 +46,5 @@ export function useRetiredWorktreeNames( } }, [refreshKey, repoId]) - return { - names: loaded && loaded.repoId === repoId ? loaded.names : NO_RETIRED_NAMES, - loading: Boolean(repoId) && (loaded?.repoId !== repoId || loaded?.refreshKey !== refreshKey) - } + return selectRetiredNames(loaded, repoId) } diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 8bd5e98c7b64..2b243aafac3d 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -63,6 +63,7 @@ import { legacyBaseRefSearchResult } from '../../../shared/base-ref-search-resul import { EMPTY_PTY_MAIN_DELIVERY_DIAGNOSTICS } from '../../../shared/pty-delivery-diagnostics' import { createE2EConfig } from '../../../shared/e2e-config' import { relativePathInsideRoot } from '../../../shared/cross-platform-path' +import { readRetiredNamesForRepo } from '../../../shared/worktree/retired-name-cache' import { applyPRBotAuthorOverride, normalizePRBotAuthorOverrides @@ -1776,12 +1777,10 @@ function createWorktreesApi(): NonNullable['worktrees']> { // degrades the suggestion to the pre-existing behavior rather than blocking workspace create. listRetiredNames: async ({ repoId }) => { try { - const result = await callRuntimeResult<{ retiredNamesByRepo?: Record }>( - 'worktree.listRetiredNames', - { repo: repoId } + return readRetiredNamesForRepo( + await callRuntimeResult('worktree.listRetiredNames', { repo: repoId }), + repoId ) - const names = result.retiredNamesByRepo?.[repoId] - return Array.isArray(names) ? names.filter((name) => typeof name === 'string') : [] } catch { return [] } diff --git a/src/shared/worktree/retired-name-cache.test.ts b/src/shared/worktree/retired-name-cache.test.ts new file mode 100644 index 000000000000..dacc3f0a58b5 --- /dev/null +++ b/src/shared/worktree/retired-name-cache.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { + NO_RETIRED_NAMES, + readRetiredNamesForRepo, + retiredNamesAfterRefresh, + selectRetiredNames +} from './retired-name-cache' + +describe('readRetiredNamesForRepo', () => { + it('reads the requested repo only', () => { + const result = { retiredNamesByRepo: { 'repo-1': ['nautilus'], 'repo-2': ['seahorse'] } } + expect(readRetiredNamesForRepo(result, 'repo-1')).toEqual(['nautilus']) + }) + + it.each([ + ['a host predating the method', {}], + ['a repo with no entry', { retiredNamesByRepo: { other: ['nautilus'] } }], + ['a non-array row', { retiredNamesByRepo: { 'repo-1': 'nautilus' } }], + ['a null result', null], + ['a non-object result', 'nope'] + ])('answers empty for %s', (_label, result) => { + expect(readRetiredNamesForRepo(result, 'repo-1')).toEqual([]) + }) + + it('drops non-string elements, which would throw when normalized', () => { + const result = { retiredNamesByRepo: { 'repo-1': ['nautilus', 42, null, 'seahorse'] } } + expect(readRetiredNamesForRepo(result, 'repo-1')).toEqual(['nautilus', 'seahorse']) + }) +}) + +describe('retiredNamesAfterRefresh', () => { + it('takes the new names on success', () => { + const previous = { repoId: 'repo-1', names: ['nautilus'] } + expect(retiredNamesAfterRefresh(previous, 'repo-1', ['nautilus', 'seahorse'])).toEqual({ + repoId: 'repo-1', + names: ['nautilus', 'seahorse'] + }) + }) + + // The divergence this module exists to close: mobile used to reset to [] here, which un-retires + // every name in the window where the create form is asking for a suggestion. + it('holds the previous names when the refresh fails', () => { + const previous = { repoId: 'repo-1', names: ['nautilus'] } + expect(retiredNamesAfterRefresh(previous, 'repo-1', null)).toEqual({ + repoId: 'repo-1', + names: ['nautilus'] + }) + }) + + it('does not carry another repo forward through a failure', () => { + const previous = { repoId: 'repo-1', names: ['nautilus'] } + expect(retiredNamesAfterRefresh(previous, 'repo-2', null)).toEqual({ + repoId: 'repo-2', + names: NO_RETIRED_NAMES + }) + }) + + it('answers empty when the first fetch for a repo fails', () => { + expect(retiredNamesAfterRefresh(null, 'repo-1', null).names).toEqual([]) + }) +}) + +describe('selectRetiredNames', () => { + it('serves a load only to the repo it answered for', () => { + const loaded = { repoId: 'repo-1', names: ['nautilus'] } + expect(selectRetiredNames(loaded, 'repo-1')).toEqual(['nautilus']) + expect(selectRetiredNames(loaded, 'repo-2')).toEqual([]) + expect(selectRetiredNames(loaded, null)).toEqual([]) + expect(selectRetiredNames(null, 'repo-1')).toEqual([]) + }) + + it('returns the stored array itself so downstream memos do not rerun', () => { + const names = ['nautilus'] + expect(selectRetiredNames({ repoId: 'repo-1', names }, 'repo-1')).toBe(names) + }) +}) diff --git a/src/shared/worktree/retired-name-cache.ts b/src/shared/worktree/retired-name-cache.ts new file mode 100644 index 000000000000..aafdc65d2687 --- /dev/null +++ b/src/shared/worktree/retired-name-cache.ts @@ -0,0 +1,54 @@ +/** Client-side caching rules for retired workspace names, shared by the desktop hook (IPC) and the + * mobile hook (RPC). The transports differ, but what a refresh and a failure *mean* must not: the + * two hooks drifted, and mobile's copy blanked the list on any error — which un-retires names and + * is the one outcome retirement exists to prevent. + * + * Pure by construction: `src/shared` is on the main process's import graph, so no React here. */ + +export const NO_RETIRED_NAMES: readonly string[] = [] + +/** The last answer, tagged with the repo it answered for. */ +export type RetiredNamesLoad = { + repoId: string + names: readonly string[] +} + +/** Reads one repo's names out of a `worktree.listRetiredNames` result. A host predating the method + * omits the field, and any host can answer with a malformed row that would throw when normalized. */ +export function readRetiredNamesForRepo(result: unknown, repoId: string): string[] { + const names = (result as { retiredNamesByRepo?: Record } | null | undefined) + ?.retiredNamesByRepo?.[repoId] + return Array.isArray(names) + ? names.filter((name): name is string => typeof name === 'string') + : [] +} + +/** Next state once a refresh settles; `names === null` means it failed. Belongs in a `setState` + * updater rather than being applied at call time, so overlapping refreshes fold onto whatever + * actually landed last. + * + * A failure holds the same repo's previous answer: a transient failure must not un-retire names, + * and a refresh fires on every workspace-list mutation, so blanking would suggest a spent name in + * exactly the window where the create form is asking for one. */ +export function retiredNamesAfterRefresh( + previous: RetiredNamesLoad | null, + repoId: string, + names: readonly string[] | null +): RetiredNamesLoad { + return { + repoId, + names: names ?? (previous?.repoId === repoId ? previous.names : NO_RETIRED_NAMES) + } +} + +/** Stale-while-revalidate view: a load answers only for its own repo, so names never leak across a + * repo switch, and a refetch in flight keeps serving the previous answer rather than emptying. + * + * Returns the stored array itself, not a copy, so it stays referentially stable and the suggestion + * memo downstream does not rerun on every refetch. */ +export function selectRetiredNames( + loaded: RetiredNamesLoad | null, + repoId: string | null | undefined +): readonly string[] { + return loaded && loaded.repoId === repoId ? loaded.names : NO_RETIRED_NAMES +} From e2d01851767d322610b9eebef6b79a9cac8b56d6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Thu, 13 Aug 2026 23:06:31 -0700 Subject: [PATCH 18/20] fix(worktree): import shared types from their real modules Main dropped the src/shared/types barrel, so the retirement module's import resolved locally but not against the PR's merge base. --- src/main/worktree-name-retirement.test.ts | 3 ++- src/main/worktree-name-retirement.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index 9d603f68ae3d..a554b15aec61 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -3,7 +3,8 @@ import { mkdir, mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { MARINE_CREATURES } from '../shared/marine-creatures' -import type { GlobalSettings, Repo } from '../shared/types' +import type { GlobalSettings } from '../shared/global-settings-types' +import type { Repo } from '../shared/repo-types' import { collectRetiredNamesFromLeafNames, discoverRetiredWorktreeNames, diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index 16d3c3ce0246..c9a3f0b7569b 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -4,7 +4,8 @@ import { join } from 'node:path' import { MARINE_CREATURES } from '../shared/marine-creatures' import { getRepoExecutionHostId } from '../shared/execution-host' import { isFolderRepo } from '../shared/repo-kind' -import type { GlobalSettings, Repo } from '../shared/types' +import type { GlobalSettings } from '../shared/global-settings-types' +import type { Repo } from '../shared/repo-types' import { encodeClaudeProjectPath, isClaudeProjectDirInScope From 5c51039c0d45625e3eb7387ec753707142c2ba36 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 14 Aug 2026 13:59:51 -0700 Subject: [PATCH 19/20] refactor(worktree): bound the retirement registry by tier compaction, not eviction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retirement is a correctness guarantee — a spent name's directory may still hold agent conversation state keyed by that cwd — so the 2000-entry cap was the wrong shape: reaching it handed a name back. At the owner's measured rate (~6.6 pool names retired per day in one repo) the cap was ~9 months out. Names come from a fixed 552-entry pool and the suggester only reaches tier N+1 once every tier-N name is taken, so a completed tier is exactly a set that no longer needs listing. A row is now a watermark plus the names above it: reads answer at-or-below the watermark with no lookup, and compaction drops the 552 entries the watermark now covers. Bounded at one pool per repo forever, with no eviction and nothing un-retired. Tiers can complete out of order (a create-time collision can spend `nautilus-2` while tier 1 is open), so compaction loops and higher-tier names simply wait. The RPC result carries the watermark beside the names as a new field; a client predating it reads the names only and under-retires the compacted tiers, which degrades to the pre-retirement behavior rather than breaking. --- .../worktree-name-suggestion.test.ts | 28 ++- .../components/worktree-name-suggestion.ts | 21 ++- .../use-retired-worktree-names.test.tsx | 37 +++- .../worktree/use-retired-worktree-names.ts | 17 +- src/main/ipc/worktree-remote.ts | 19 +- src/main/ipc/worktrees-windows.test.ts | 10 +- src/main/ipc/worktrees.test.ts | 10 +- src/main/ipc/worktrees.ts | 7 +- .../profile-project-state-file.ts | 5 +- .../profile-project-transfer-payload.ts | 13 +- .../profile-project-transfer.test.ts | 7 +- ...rsistence-worktree-name-retirement.test.ts | 159 +++++++++++++--- src/main/persistence.ts | 104 +++++------ .../runtime/fit-override-integration.test.ts | 2 +- .../graph-sync-mobile-snapshot-gating.test.ts | 2 +- .../graph-sync-payload-partition.test.ts | 2 +- src/main/runtime/mobile-presence-lock.test.ts | 2 +- .../mobile-subscribe-integration.test.ts | 2 +- src/main/runtime/orca-runtime.test.ts | 8 +- src/main/runtime/orca-runtime.ts | 41 +++- .../runtime/remote-desktop-driver.test.ts | 2 +- .../rpc/methods/worktree-catalog-methods.ts | 4 +- .../methods/worktree-retired-names.test.ts | 34 ++++ src/main/runtime/rpc/methods/worktree.test.ts | 17 -- .../runtime/terminal-query-responder.test.ts | 2 +- src/main/worktree-name-retirement.test.ts | 26 +-- src/main/worktree-name-retirement.ts | 31 +-- src/preload/api/worktree-api.ts | 6 +- .../sidebar/worktree-name-suggestions.test.ts | 17 +- .../sidebar/worktree-name-suggestions.ts | 15 +- .../src/hooks/useRetiredWorktreeNames.test.ts | 41 ++-- .../src/hooks/useRetiredWorktreeNames.ts | 11 +- src/renderer/src/web/web-preload-api.ts | 7 +- src/shared/persisted-state-types.ts | 7 +- src/shared/worktree-name-suggestion.test.ts | 14 ++ src/shared/worktree-name-suggestion.ts | 27 +-- .../worktree/retired-name-cache.test.ts | 96 ++++++---- src/shared/worktree/retired-name-cache.ts | 60 ++++-- .../worktree/retired-name-registry.test.ts | 176 ++++++++++++++++++ src/shared/worktree/retired-name-registry.ts | 133 +++++++++++++ 40 files changed, 908 insertions(+), 314 deletions(-) create mode 100644 src/main/runtime/rpc/methods/worktree-retired-names.test.ts create mode 100644 src/shared/worktree/retired-name-registry.test.ts create mode 100644 src/shared/worktree/retired-name-registry.ts diff --git a/mobile/src/components/worktree-name-suggestion.test.ts b/mobile/src/components/worktree-name-suggestion.test.ts index 2569871c77a1..d14f186a2f21 100644 --- a/mobile/src/components/worktree-name-suggestion.test.ts +++ b/mobile/src/components/worktree-name-suggestion.test.ts @@ -4,6 +4,7 @@ import { getSuggestedCreatureName } from './worktree-name-suggestion' const pickFirst = () => 0 const lower = (index: number) => MARINE_CREATURES[index].toLowerCase() +const retiring = (...names: string[]) => ({ exhaustedTiers: 0, names }) describe('getSuggestedCreatureName (mobile)', () => { it('picks an unused name', () => { @@ -25,26 +26,37 @@ describe('getSuggestedCreatureName (mobile)', () => { it('never reissues a retired name whose workspace is already deleted', () => { // Parity with desktop: the deleted workspace's directory may still hold agent // conversation state keyed by cwd, so the name must not come back. - expect(getSuggestedCreatureName([], pickFirst, [MARINE_CREATURES[0]])).toBe(lower(1)) + expect(getSuggestedCreatureName([], pickFirst, retiring(MARINE_CREATURES[0]))).toBe(lower(1)) }) it('treats retired names case-insensitively', () => { - expect(getSuggestedCreatureName([], pickFirst, [MARINE_CREATURES[0].toUpperCase()])).toBe( - lower(1) - ) + expect( + getSuggestedCreatureName([], pickFirst, retiring(MARINE_CREATURES[0].toUpperCase())) + ).toBe(lower(1)) }) it('applies retirement on top of live paths rather than instead of them', () => { expect( - getSuggestedCreatureName([`/home/u/worktrees/${MARINE_CREATURES[0]}`], pickFirst, [ - MARINE_CREATURES[1] - ]) + getSuggestedCreatureName( + [`/home/u/worktrees/${MARINE_CREATURES[0]}`], + pickFirst, + retiring(MARINE_CREATURES[1]) + ) ).toBe(lower(2)) }) it('degrades to a suffixed tier when the pool is spent, skipping retired variants', () => { const allPaths = MARINE_CREATURES.map((name) => `/home/u/worktrees/${name}`) - expect(getSuggestedCreatureName(allPaths, pickFirst, [`${lower(0)}-2`])).toBe(`${lower(1)}-2`) + expect(getSuggestedCreatureName(allPaths, pickFirst, retiring(`${lower(0)}-2`))).toBe( + `${lower(1)}-2` + ) + }) + + it('skips every tier the host reports as compacted rather than looking its names up', () => { + // Those names are absent from the wire payload because they are ALL spent, not available. + expect(getSuggestedCreatureName([], pickFirst, { exhaustedTiers: 2, names: [] })).toBe( + `${lower(0)}-3` + ) }) it('falls back to live-only dedupe when the host sends no retired names', () => { diff --git a/mobile/src/components/worktree-name-suggestion.ts b/mobile/src/components/worktree-name-suggestion.ts index 585fb0821811..701f66959e13 100644 --- a/mobile/src/components/worktree-name-suggestion.ts +++ b/mobile/src/components/worktree-name-suggestion.ts @@ -3,29 +3,34 @@ import { selectSuggestedCreatureName, suggestionPathBasename } from '../../../src/shared/worktree-name-suggestion' +import { + EMPTY_RETIRED_NAME_REGISTRY, + type RetiredNameRegistry +} from '../../../src/shared/worktree/retired-name-registry' // Why: this used to hand-duplicate the desktop algorithm and the two drifted apart by // construction. Both now call the shared core so a name suggested on a phone and one suggested on // the desktop obey the same rules. The dedupe is on the on-disk directory basename, not the // user-facing displayName, because that is what actually collides. -/** `retiredNames` are names already spent in the selected repo, including workspaces that have - * since been deleted — their directories may still hold agent conversation state keyed by cwd, so - * reissuing the name would hand it to the next occupant. +/** `retired` holds names already spent in the selected repo, including workspaces that have since + * been deleted — their directories may still hold agent conversation state keyed by cwd, so + * reissuing the name would hand it to the next occupant. Its `exhaustedTiers` watermark covers + * the tiers the host has compacted away, whose names it therefore no longer sends individually. * - * Hosts older than this field send nothing, in which case this degrades to deduping against live - * paths only, exactly as it did before. */ + * Hosts older than these fields send nothing, in which case this degrades to deduping against + * live paths only, exactly as it did before. */ export function getSuggestedCreatureName( existingPaths: readonly string[], random: () => number = Math.random, - retiredNames: readonly string[] = [] + retired: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY ): string { const used = new Set() for (const path of existingPaths) { used.add(normalizeSuggestedName(suggestionPathBasename(path))) } - for (const retiredName of retiredNames) { + for (const retiredName of retired.names) { used.add(normalizeSuggestedName(retiredName)) } - return selectSuggestedCreatureName(used, random) + return selectSuggestedCreatureName(used, random, retired.exhaustedTiers) } diff --git a/mobile/src/worktree/use-retired-worktree-names.test.tsx b/mobile/src/worktree/use-retired-worktree-names.test.tsx index 34fbe9a6506d..9258e5308074 100644 --- a/mobile/src/worktree/use-retired-worktree-names.test.tsx +++ b/mobile/src/worktree/use-retired-worktree-names.test.tsx @@ -2,6 +2,10 @@ import { createElement } from 'react' import { act, create } from 'react-test-renderer' import { describe, expect, it } from 'vitest' import type { RpcClient } from '../transport/rpc-client' +import { + EMPTY_RETIRED_NAME_REGISTRY, + type RetiredNameRegistry +} from '../../../src/shared/worktree/retired-name-registry' import { useRetiredWorktreeNames } from './use-retired-worktree-names' type Pending = { resolve: (response: unknown) => void; reject: (err: Error) => void } @@ -11,7 +15,7 @@ type Pending = { resolve: (response: unknown) => void; reject: (err: Error) => v function mountNames() { const pending: Pending[] = [] const requests: { method: string; params: unknown }[] = [] - let latest: readonly string[] = [] + let latest: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY const client = { sendRequest: (method: string, params: unknown) => { @@ -30,18 +34,25 @@ function mountNames() { renderer = create(createElement(Probe, { repoId: 'repo-1', refreshKey: 'a' })) }) return { - get names(): readonly string[] { + get registry(): RetiredNameRegistry { return latest }, + get names(): readonly string[] { + return latest.names + }, requests, rerender(props: { repoId: string | null; refreshKey: string }) { act(() => { renderer.update(createElement(Probe, props)) }) }, - async settle(index: number, retiredNamesByRepo: Record) { + async settle( + index: number, + retiredNamesByRepo: Record, + retiredNameTiersByRepo: Record = {} + ) { await act(async () => { - pending[index]!.resolve({ result: { retiredNamesByRepo } }) + pending[index]!.resolve({ result: { retiredNamesByRepo, retiredNameTiersByRepo } }) await Promise.resolve() }) }, @@ -68,7 +79,23 @@ describe('useRetiredWorktreeNames', () => { it('answers empty for a host that omits the field', async () => { const probe = mountNames() await probe.settle(0, {}) - expect(probe.names).toEqual([]) + expect(probe.registry).toEqual(EMPTY_RETIRED_NAME_REGISTRY) + }) + + it('carries the compaction watermark through, so spent tiers are not suggested back', async () => { + const probe = mountNames() + await probe.settle(0, { 'repo-1': ['nautilus-2'] }, { 'repo-1': 1 }) + expect(probe.registry).toEqual({ exhaustedTiers: 1, names: ['nautilus-2'] }) + }) + + it('holds the watermark too when a refresh fails', async () => { + const probe = mountNames() + await probe.settle(0, { 'repo-1': [] }, { 'repo-1': 3 }) + + probe.rerender({ repoId: 'repo-1', refreshKey: 'b' }) + await probe.fail(1) + + expect(probe.registry.exhaustedTiers).toBe(3) }) // Regression: this hook used to reset to [] on any error, un-retiring every name for the rest of diff --git a/mobile/src/worktree/use-retired-worktree-names.ts b/mobile/src/worktree/use-retired-worktree-names.ts index ee3872a69487..13252c639c36 100644 --- a/mobile/src/worktree/use-retired-worktree-names.ts +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -1,10 +1,11 @@ import { useEffect, useState } from 'react' import { - readRetiredNamesForRepo, + readRetiredNameRegistryForRepo, retiredNamesAfterRefresh, - selectRetiredNames, + selectRetiredNameRegistry, type RetiredNamesLoad } from '../../../src/shared/worktree/retired-name-cache' +import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry' import type { RpcClient } from '../transport/rpc-client' /** Names already spent in a repo, including workspaces that have since been deleted. @@ -20,7 +21,7 @@ export function useRetiredWorktreeNames( client: RpcClient | null | undefined, repoId: string | null | undefined, refreshKey: unknown -): readonly string[] { +): RetiredNameRegistry { const [loaded, setLoaded] = useState(null) const activeRepoId = client && repoId ? repoId : null @@ -30,15 +31,17 @@ export function useRetiredWorktreeNames( return } let cancelled = false - const settle = (names: readonly string[] | null): void => { + const settle = (registry: RetiredNameRegistry | null): void => { if (!cancelled) { - setLoaded((previous) => retiredNamesAfterRefresh(previous, activeRepoId, names)) + setLoaded((previous) => retiredNamesAfterRefresh(previous, activeRepoId, registry)) } } void client .sendRequest('worktree.listRetiredNames', { repo: `id:${activeRepoId}` }) .then((response) => - settle(readRetiredNamesForRepo((response as { result?: unknown }).result, activeRepoId)) + settle( + readRetiredNameRegistryForRepo((response as { result?: unknown }).result, activeRepoId) + ) ) .catch(() => settle(null)) return () => { @@ -46,5 +49,5 @@ export function useRetiredWorktreeNames( } }, [activeRepoId, client, refreshKey]) - return selectRetiredNames(loaded, activeRepoId) + return selectRetiredNameRegistry(loaded, activeRepoId) } diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index 5697b6a14f2a..dd0f2e6d4d49 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -139,7 +139,8 @@ import { getWorktreeCreateCandidate, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' -import { getRetiredWorktreeNamesForRepo } from '../worktree-name-retirement' +import { getRetiredNameRegistryForRepo } from '../worktree-name-retirement' +import { createRetiredNameLookup } from '../../shared/worktree/retired-name-registry' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1555,8 +1556,10 @@ export async function createRemoteWorktree( let selectedExistingLocalBranchName: string | null = null let lastBranchConflictKind: 'local' | 'remote' | null = null let remotePathResolved = false - const retiredNames = args.nameWasGenerated - ? new Set(getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings)) + const isRetiredName = args.nameWasGenerated + ? createRetiredNameLookup( + getRetiredNameRegistryForRepo(store, repo, store.getRepos(), settings) + ) : null // Why: duplicate PR/MR checkouts still need a workspace; suffix branch/path while preserving review metadata and push target. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -1564,7 +1567,7 @@ export async function createRemoteWorktree( effectiveRequestedName = args.name.trim() ? getWorktreeCreateCandidate(args.name, suffix) : effectiveSanitizedName - if (retiredNames?.has(effectiveSanitizedName)) { + if (isRetiredName?.(effectiveSanitizedName)) { continue } branchName = await resolveCreateBranchNameSsh( @@ -2104,8 +2107,10 @@ export async function createLocalWorktree( let lastBranchConflictKind: 'local' | 'remote' | null = null let lastExistingPR: Awaited> | null = null let lastExistingReviewNumber: number | null = null - const retiredNames = args.nameWasGenerated - ? new Set(getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings)) + const isRetiredName = args.nameWasGenerated + ? createRetiredNameLookup( + getRetiredNameRegistryForRepo(store, repo, store.getRepos(), settings) + ) : null // Why: a create-from-review branch override may already exist locally; suffix both branch and path instead of blocking the user. for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { @@ -2113,7 +2118,7 @@ export async function createLocalWorktree( effectiveRequestedName = requestedName.trim() ? getWorktreeCreateCandidate(requestedName, suffix) : effectiveSanitizedName - if (retiredNames?.has(effectiveSanitizedName)) { + if (isRetiredName?.(effectiveSanitizedName)) { continue } lastExistingReviewNumber = null diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index a25c8a42a579..995c60318959 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -162,7 +162,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { setWorktreeMeta: vi.fn(), removeWorktreeMeta: vi.fn(), addRetiredWorktreeName: vi.fn(), - getRetiredWorktreeNames: vi.fn(), + getRetiredWorktreeNameRegistry: vi.fn(), mergeRetiredWorktreeNames: vi.fn() } @@ -206,7 +206,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { store.setWorktreeMeta.mockReset() store.removeWorktreeMeta.mockReset() store.addRetiredWorktreeName.mockReset() - store.getRetiredWorktreeNames.mockReset() + store.getRetiredWorktreeNameRegistry.mockReset() store.mergeRetiredWorktreeNames.mockReset() resetRetirementCollisionKeyCacheForTests() @@ -245,7 +245,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) resolveSetupRunnerShellMock.mockReturnValue(undefined) store.getWorktreeMeta.mockReturnValue(undefined) - store.getRetiredWorktreeNames.mockReturnValue([]) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: [] }) store.setWorktreeMeta.mockReturnValue({}) resolveLocalGitUsernameMock.mockResolvedValue('') getDefaultBaseRefMock.mockReturnValue('origin/main') @@ -330,7 +330,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) it('skips a retired generated name when the physical leaf is decorated', async () => { - store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['nautilus'] }) computeWorktreePathMock.mockReturnValue('C:\\workspaces\\repo-nautilus-2') ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\repo-nautilus-2') listWorktreesMock.mockResolvedValue([ @@ -355,7 +355,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { it('leaves a user-typed name reusable even when the same name is retired', async () => { // Why: the creature pool contains ordinary words ("orca", "runner", "molly"). Silently // renaming a deliberate `nautilus` to `nautilus-2` — and burning it — is the wrong trade. - store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['nautilus'] }) computeWorktreePathMock.mockReturnValue('C:\\workspaces\\nautilus') ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\nautilus') listWorktreesMock.mockResolvedValue([ diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index fc3bef3702de..2b500118752b 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -352,7 +352,7 @@ describe('registerWorktreeHandlers', () => { getFolderWorkspaces: vi.fn(), getProjectGroups: vi.fn(), addRetiredWorktreeName: vi.fn(), - getRetiredWorktreeNames: vi.fn(), + getRetiredWorktreeNameRegistry: vi.fn(), mergeRetiredWorktreeNames: vi.fn() } let runtimeStub: { @@ -438,7 +438,7 @@ describe('registerWorktreeHandlers', () => { store.getFolderWorkspaces, store.getProjectGroups, store.addRetiredWorktreeName, - store.getRetiredWorktreeNames, + store.getRetiredWorktreeNameRegistry, store.mergeRetiredWorktreeNames, killAllProcessesForWorktreeMock, clearProviderPtyStateMock, @@ -493,7 +493,7 @@ describe('registerWorktreeHandlers', () => { }) store.getWorktreeMeta.mockReturnValue(undefined) store.getAllWorktreeMeta.mockReturnValue({}) - store.getRetiredWorktreeNames.mockReturnValue([]) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: [] }) resetRetirementCollisionKeyCacheForTests() store.setWorktreeMeta.mockReturnValue({}) store.getProjectHostSetups.mockReturnValue([ @@ -4748,7 +4748,7 @@ describe('registerWorktreeHandlers', () => { store.getRepo.mockReturnValue(repo) getSshGitProviderMock.mockReturnValue(provider) getActiveMultiplexerMock.mockReturnValue(mux) - store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['nautilus'] }) store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) const result = await handlers['worktrees:create'](null, { @@ -4839,7 +4839,7 @@ describe('registerWorktreeHandlers', () => { request: vi.fn().mockResolvedValue(undefined), notify: vi.fn() }) - store.getRetiredWorktreeNames.mockReturnValue(['nautilus']) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['nautilus'] }) store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) const result = await handlers['worktrees:create'](null, { diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 0d82e6c0674c..34115ce8d80e 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -123,8 +123,9 @@ import { } from './worktree-logic' import { ensureRetiredWorktreeNamesBackfilled, - getRetiredWorktreeNamesForRepo + getRetiredNameRegistryForRepo } from '../worktree-name-retirement' +import { EMPTY_RETIRED_NAME_REGISTRY } from '../../shared/worktree/retired-name-registry' import { dedupeWorktreesByPath } from './worktree-path-comparison' import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' import { @@ -1941,7 +1942,7 @@ export function registerWorktreeHandlers( ipcMain.handle('worktrees:listRetiredNames', async (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) if (!repo) { - return [] + return EMPTY_RETIRED_NAME_REGISTRY } try { await ensureRetiredWorktreeNamesBackfilled(store, repo, store.getSettings()) @@ -1949,7 +1950,7 @@ export function registerWorktreeHandlers( // Best effort: without the seed we only under-retire, which is the pre-existing behavior. console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) } - return getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), store.getSettings()) + return getRetiredNameRegistryForRepo(store, repo, store.getRepos(), store.getSettings()) }) ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { diff --git a/src/main/orca-profiles/profile-project-state-file.ts b/src/main/orca-profiles/profile-project-state-file.ts index 08cde3986436..e72babef2f40 100644 --- a/src/main/orca-profiles/profile-project-state-file.ts +++ b/src/main/orca-profiles/profile-project-state-file.ts @@ -11,6 +11,7 @@ import type { Project, ProjectHostSetup } from '../../shared/project-types' import type { Repo } from '../../shared/repo-types' import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types' import type { SparsePreset } from '../../shared/worktree/create-types' +import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' import { getOrcaProfileDataFile } from './profile-index-store' export type TransferProfileState = PersistedState @@ -43,7 +44,9 @@ export function readProfileState(profileId: string, userDataPath: string): Trans projectGroups: arrayOrEmpty(parsed.projectGroups), folderWorkspaces: arrayOrEmpty(parsed.folderWorkspaces), sparsePresetsByRepo: recordOrEmpty(parsed.sparsePresetsByRepo), - retiredWorktreeNamesByRepo: recordOrEmpty(parsed.retiredWorktreeNamesByRepo), + retiredWorktreeNamesByRepo: recordOrEmpty( + parsed.retiredWorktreeNamesByRepo + ), worktreeMeta: recordOrEmpty(parsed.worktreeMeta), worktreeLineageById: recordOrEmpty(parsed.worktreeLineageById), workspaceLineageByChildKey: recordOrEmpty(parsed.workspaceLineageByChildKey), diff --git a/src/main/orca-profiles/profile-project-transfer-payload.ts b/src/main/orca-profiles/profile-project-transfer-payload.ts index 3700f1d7d91e..a984b7bbf143 100644 --- a/src/main/orca-profiles/profile-project-transfer-payload.ts +++ b/src/main/orca-profiles/profile-project-transfer-payload.ts @@ -6,6 +6,7 @@ import type { WorkspaceKey } from '../../shared/folder-workspace-types' import type { PersistedState } from '../../shared/persisted-state-types' import type { Repo } from '../../shared/repo-types' import type { SparsePreset } from '../../shared/worktree/create-types' +import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' import { parseWorkspaceKey } from '../../shared/workspace-scope' import type { TransferProfileState } from './profile-project-state-file' import { rebuildRepoBackedProjectState } from './profile-project-state-file' @@ -23,9 +24,9 @@ import { export type TransferPayload = { repo: Repo sparsePresets: SparsePreset[] - /** Generated names already spent for this repo. Carried so the destination profile does not - * reissue a name whose old directory still holds agent state. */ - retiredWorktreeNames: string[] + /** Generated names already spent for this repo, compacted. Carried so the destination profile + * does not reissue a name whose old directory still holds agent state. */ + retiredNameRegistry: RetiredNameRegistry | undefined worktreeMeta: PersistedState['worktreeMeta'] worktreeLineageById: PersistedState['worktreeLineageById'] workspaceLineageByChildKey: PersistedState['workspaceLineageByChildKey'] @@ -220,7 +221,7 @@ export function createTransferPayload(args: { ...structuredClone(preset), repoId: newRepoId })), - retiredWorktreeNames: [...(sourceState.retiredWorktreeNamesByRepo?.[oldRepoId] ?? [])], + retiredNameRegistry: sourceState.retiredWorktreeNamesByRepo?.[oldRepoId], worktreeMeta: rekeyWorktreeIdRecord( sourceState.worktreeMeta, worktreeIds, @@ -278,9 +279,7 @@ export function applyPayloadToTarget( }, retiredWorktreeNamesByRepo: { ...targetState.retiredWorktreeNamesByRepo, - ...(payload.retiredWorktreeNames.length > 0 - ? { [payload.repo.id]: payload.retiredWorktreeNames } - : {}) + ...(payload.retiredNameRegistry ? { [payload.repo.id]: payload.retiredNameRegistry } : {}) }, worktreeMeta: { ...targetState.worktreeMeta, ...payload.worktreeMeta }, diff --git a/src/main/orca-profiles/profile-project-transfer.test.ts b/src/main/orca-profiles/profile-project-transfer.test.ts index 5914021f16a2..facde389e21c 100644 --- a/src/main/orca-profiles/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/profile-project-transfer.test.ts @@ -128,7 +128,7 @@ describe('profile project transfer', () => { } ] }, - retiredWorktreeNamesByRepo: { 'repo-1': ['nautilus'] }, + retiredWorktreeNamesByRepo: { 'repo-1': { exhaustedTiers: 0, names: ['nautilus'] } }, worktreeMeta: { [sourceWorktreeId]: makeWorktreeMeta({ projectHostSetupId: 'repo-1' }) }, @@ -182,7 +182,10 @@ describe('profile project transfer', () => { ]) // Why: without the re-key the destination profile reissues a name whose old directory may // still hold the previous occupant's agent conversation. - expect(target.retiredWorktreeNamesByRepo?.[targetRepoId]).toEqual(['nautilus']) + expect(target.retiredWorktreeNamesByRepo?.[targetRepoId]).toEqual({ + exhaustedTiers: 0, + names: ['nautilus'] + }) expect(target.workspaceSession.tabsByWorktree).toEqual({}) expect(readProfileState('personal').repos.map((repo) => repo.id)).toEqual(['repo-1']) }) diff --git a/src/main/persistence-worktree-name-retirement.test.ts b/src/main/persistence-worktree-name-retirement.test.ts index 6522e3bae0a4..ec567fefa6c8 100644 --- a/src/main/persistence-worktree-name-retirement.test.ts +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { getDefaultPersistedState } from '../shared/constants' import { MARINE_CREATURES } from '../shared/marine-creatures' +import { createRetiredNameLookup } from '../shared/worktree/retired-name-registry' const testState = { dir: '' } @@ -16,6 +17,14 @@ vi.mock('./telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) const REPO = 'repo-1' const OTHER_REPO = 'repo-2' +const POOL = MARINE_CREATURES.map((name) => name.toLowerCase()) + +async function reloadStore() { + vi.resetModules() + const { Store, initDataPath } = await import('./persistence') + initDataPath() + return new Store() +} async function createStore(persisted: Record = {}) { mkdirSync(testState.dir, { recursive: true }) @@ -24,10 +33,7 @@ async function createStore(persisted: Record = {}) { JSON.stringify({ ...getDefaultPersistedState(testState.dir), ...persisted }), 'utf-8' ) - vi.resetModules() - const { Store, initDataPath } = await import('./persistence') - initDataPath() - return new Store() + return reloadStore() } beforeEach(() => { @@ -42,48 +48,52 @@ describe('worktree name retirement registry', () => { it('retains a retired name so it is never reissued', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, 'Nautilus') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) }) it('scopes retirement per repo so one repo does not burn another pool', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, 'nautilus') - expect(store.getRetiredWorktreeNames(OTHER_REPO)).toEqual([]) + expect(store.getRetiredWorktreeNameRegistry(OTHER_REPO).names).toEqual([]) }) it('normalizes case and whitespace so a name cannot be retired twice', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, ' NaUtIlUs ') store.addRetiredWorktreeName(REPO, 'nautilus') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) }) it('ignores an empty name or missing repo id', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, ' ') store.addRetiredWorktreeName('', 'nautilus') - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual([]) }) it('does not persist arbitrary user and issue-title names', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, 'fix-login-redirect') store.addRetiredWorktreeName(REPO, 'STA-4189-duplicate-name') - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual([]) }) it('returns a copy so callers cannot mutate the registry in place', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, 'nautilus') - store.getRetiredWorktreeNames(REPO).push('seahorse') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + ;(store.getRetiredWorktreeNameRegistry(REPO).names as string[]).push('seahorse') + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) }) it('merges backfilled names without dropping a concurrent retirement', async () => { const store = await createStore() store.addRetiredWorktreeName(REPO, 'nautilus') expect(store.mergeRetiredWorktreeNames(REPO, ['seahorse', 'starfish'])).toBe(true) - expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse', 'starfish']) + expect([...store.getRetiredWorktreeNameRegistry(REPO).names].sort()).toEqual([ + 'nautilus', + 'seahorse', + 'starfish' + ]) }) it('reports no change when a merge adds nothing new', async () => { @@ -96,20 +106,26 @@ describe('worktree name retirement registry', () => { const store = await createStore({ retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 'seahorse'] } }) - expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + expect([...store.getRetiredWorktreeNameRegistry(REPO).names].sort()).toEqual([ + 'nautilus', + 'seahorse' + ]) }) it('degrades to nothing retired when the persisted map is corrupt', async () => { // Why: a load failure costs the app; over- or under-retiring costs at most a name. const store = await createStore({ retiredWorktreeNamesByRepo: 'not-an-object' }) - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual([]) }) it('drops non-string entries but keeps the valid ones', async () => { const store = await createStore({ retiredWorktreeNamesByRepo: { [REPO]: ['nautilus', 42, null, 'Seahorse'] } }) - expect(store.getRetiredWorktreeNames(REPO).sort()).toEqual(['nautilus', 'seahorse']) + expect([...store.getRetiredWorktreeNameRegistry(REPO).names].sort()).toEqual([ + 'nautilus', + 'seahorse' + ]) }) it('drops the registry when the repo is removed, matching the sparse-preset convention', async () => { @@ -121,7 +137,7 @@ describe('worktree name retirement registry', () => { store.removeProject(REPO) - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual([]) }) it('keeps the registry when one host row is removed but the repo id survives elsewhere', async () => { @@ -139,36 +155,119 @@ describe('worktree name retirement registry', () => { store.removeProjectForHost(REPO, 'runtime:env-1') - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) store.removeProjectForHost(REPO, 'local') - expect(store.getRetiredWorktreeNames(REPO)).toEqual([]) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual([]) + }) + + it('compacts a completed tier instead of evicting, and still reports its names as retired', async () => { + // The registry is a correctness guarantee, so it can never drop a name. It stays bounded by + // folding a fully spent tier into the watermark — the one case where dropping the entries + // loses nothing, because every name in that tier is spent. + const store = await createStore() + store.mergeRetiredWorktreeNames(REPO, POOL.slice(0, -1)) + expect(store.getRetiredWorktreeNameRegistry(REPO)).toMatchObject({ exhaustedTiers: 0 }) + expect(store.getRetiredWorktreeNameRegistry(REPO).names.length).toBe(POOL.length - 1) + + store.addRetiredWorktreeName(REPO, POOL.at(-1) as string) + + const registry = store.getRetiredWorktreeNameRegistry(REPO) + expect(registry).toEqual({ exhaustedTiers: 1, names: [] }) + const isRetired = createRetiredNameLookup(registry) + expect(POOL.every((name) => isRetired(name))).toBe(true) + }) + + it('keeps out-of-order higher-tier names when a lower tier compacts', async () => { + // A create-time collision can spend `nautilus-2` while tier 1 is still open, so tiers do not + // fill in order and compacting tier 1 must not take the tier-2 name with it. + const store = await createStore() + store.addRetiredWorktreeName(REPO, 'nautilus-2') + store.mergeRetiredWorktreeNames(REPO, POOL) + + expect(store.getRetiredWorktreeNameRegistry(REPO)).toEqual({ + exhaustedTiers: 1, + names: ['nautilus-2'] + }) }) - it('bounds the per-repo registry above the pool so the cap never reissues a base name', async () => { - // The cap must sit well past the 552-name pool: evicting inside it would hand back a name whose - // agent state is still on disk, which is the bug this registry exists to prevent. + it('rolls the watermark through every tier that is already complete', async () => { const store = await createStore() - const names = MARINE_CREATURES.map((name) => name.toLowerCase()) - for (let tier = 2; tier <= 5; tier += 1) { + store.mergeRetiredWorktreeNames( + REPO, + POOL.map((name) => `${name}-2`) + ) + expect(store.getRetiredWorktreeNameRegistry(REPO).exhaustedTiers).toBe(0) + + store.mergeRetiredWorktreeNames(REPO, POOL) + + expect(store.getRetiredWorktreeNameRegistry(REPO)).toEqual({ exhaustedTiers: 2, names: [] }) + }) + + it('stays bounded by one pool no matter how many tiers are spent', async () => { + const store = await createStore() + for (let tier = 1; tier <= 6; tier += 1) { store.mergeRetiredWorktreeNames( REPO, - names.map((name) => `${name}-${tier}`) + POOL.map((name) => (tier === 1 ? name : `${name}-${tier}`)) ) } - store.mergeRetiredWorktreeNames(REPO, names) - const retained = store.getRetiredWorktreeNames(REPO) - expect(retained.length).toBe(2000) - // Oldest-first eviction, so the most recent merge survives intact. - expect(retained).toEqual(expect.arrayContaining(names)) + const registry = store.getRetiredWorktreeNameRegistry(REPO) + expect(registry).toEqual({ exhaustedTiers: 6, names: [] }) + expect(createRetiredNameLookup(registry)('nautilus-6')).toBe(true) + expect(createRetiredNameLookup(registry)('nautilus-7')).toBe(false) + }) + + it('round-trips the watermark and the names above it through save and reload', async () => { + const store = await createStore() + store.mergeRetiredWorktreeNames(REPO, POOL) + store.addRetiredWorktreeName(REPO, 'nautilus-2') + store.flush() + + expect((await reloadStore()).getRetiredWorktreeNameRegistry(REPO)).toEqual({ + exhaustedTiers: 1, + names: ['nautilus-2'] + }) + }) + + it('loads the pre-compaction plain-array shape a developer profile may still hold', async () => { + const store = await createStore({ + retiredWorktreeNamesByRepo: { [REPO]: [...POOL, 'nautilus-2'] } + }) + + expect(store.getRetiredWorktreeNameRegistry(REPO)).toEqual({ + exhaustedTiers: 1, + names: ['nautilus-2'] + }) + }) + + it('ignores a hand-written watermark that outruns the names it claims', async () => { + // Why not trust it: over-retiring costs a name, and the watermark is the cheapest thing to + // hand-edit. Clamping garbage to none keeps a bad value from silencing the whole pool. + const store = await createStore({ + retiredWorktreeNamesByRepo: { [REPO]: { exhaustedTiers: -3, names: ['nautilus'] } } + }) + + expect(store.getRetiredWorktreeNameRegistry(REPO)).toEqual({ + exhaustedTiers: 0, + names: ['nautilus'] + }) + }) + + it('drops names a persisted watermark already covers', async () => { + const store = await createStore({ + retiredWorktreeNamesByRepo: { [REPO]: { exhaustedTiers: 2, names: ['nautilus', 'orca-2'] } } + }) + + expect(store.getRetiredWorktreeNameRegistry(REPO)).toEqual({ exhaustedTiers: 2, names: [] }) }) it('drops legacy arbitrary names while loading the persisted map', async () => { const store = await createStore({ retiredWorktreeNamesByRepo: { [REPO]: ['fix-login', 'Nautilus'] } }) - expect(store.getRetiredWorktreeNames(REPO)).toEqual(['nautilus']) + expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) }) }) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 119bfdc9404c..535a15039107 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -175,6 +175,14 @@ import { } from '../shared/automation-run-retention' import { pruneWorkspaceSessionBrowserHistory } from '../shared/workspace-session-browser-history' import { normalizeRetirableGeneratedName } from './worktree-name-retirement' +import { + addRetiredNames, + clampExhaustedTiers, + compactRetiredNames, + EMPTY_RETIRED_NAME_REGISTRY, + isEmptyRetiredNameRegistry, + type RetiredNameRegistry +} from '../shared/worktree/retired-name-registry' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, getRepoIdFromWorktreeId, @@ -2324,46 +2332,44 @@ const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 // Why: bound removed-SSH-target history so remove/re-add churn can't grow the file unbounded. const MAX_REMOVED_SSH_TARGET_TOMBSTONES = 50 -// Bounds per-repo retirement so a long-lived repo can't grow the state file unbounded. -// -// DO NOT lower this to match the two bounds above. Those cap histories, where evicting the oldest -// entry is harmless. This set is a correctness guarantee, so any cap below the 552-name pool hands -// back a name whose agent conversation is still on disk — the exact bug this registry exists to -// prevent. Only `-2`/`-3` tier accumulation can reach 2000, at roughly 21KB per repo. -const MAX_RETIRED_WORKTREE_NAMES_PER_REPO = 2000 - -/** Oldest-first once the bound bites — a deliberate least-bad degradation rather than a neutral - * policy. Something must be dropped, and the oldest directories are the likeliest to have been - * reclaimed since, so their names are the safest of a bad set to reissue. */ -function boundRetiredWorktreeNames(names: readonly string[]): string[] { - return names.length > MAX_RETIRED_WORKTREE_NAMES_PER_REPO - ? names.slice(names.length - MAX_RETIRED_WORKTREE_NAMES_PER_REPO) - : [...names] +/** Why: retirement never evicts — dropping an entry hands back a name whose agent conversation is + * still on disk — so the row is bounded by compaction instead, and a persisted row is a watermark + * plus whatever sits above it. Accepts the pre-compaction plain-array row too: the feature is + * unreleased, but a developer profile or a fixture can still hold one. */ +function normalizeRetiredNameRegistry(row: unknown): RetiredNameRegistry { + const isPlainArray = Array.isArray(row) + const rawRow = row as { exhaustedTiers?: unknown; names?: unknown } | null | undefined + const rawNames = isPlainArray ? row : Array.isArray(rawRow?.names) ? rawRow.names : [] + const names = new Set() + for (const entry of rawNames) { + if (typeof entry !== 'string') { + continue + } + const normalized = normalizeRetirableGeneratedName(entry) + if (normalized) { + names.add(normalized) + } + } + return compactRetiredNames({ + exhaustedTiers: isPlainArray ? 0 : clampExhaustedTiers(rawRow?.exhaustedTiers), + names: [...names] + }) } /** Why: a corrupt or hand-edited map must degrade to "nothing retired" rather than throw during * load — over-retiring costs one name from a 552-entry pool, but a load failure costs the app. */ -function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record { +function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return {} } - const byRepo: Record = {} - for (const [repoId, names] of Object.entries(value as Record)) { - if (!repoId || !Array.isArray(names)) { + const byRepo: Record = {} + for (const [repoId, row] of Object.entries(value as Record)) { + if (!repoId) { continue } - const seen = new Set() - for (const entry of names) { - if (typeof entry !== 'string') { - continue - } - const normalized = normalizeRetirableGeneratedName(entry) - if (normalized) { - seen.add(normalized) - } - } - if (seen.size > 0) { - byRepo[repoId] = boundRetiredWorktreeNames([...seen]) + const registry = normalizeRetiredNameRegistry(row) + if (!isEmptyRetiredNameRegistry(registry)) { + byRepo[repoId] = registry } } return byRepo @@ -7250,8 +7256,13 @@ export class Store { this.scheduleSave() } - getRetiredWorktreeNames(repoId: string): string[] { - return [...(this.state.retiredWorktreeNamesByRepo?.[repoId] ?? [])] + /** Compacted, so callers get a watermark plus the names above it rather than every spent name. + * Copied because the array is stored state. */ + getRetiredWorktreeNameRegistry(repoId: string): RetiredNameRegistry { + const stored = this.state.retiredWorktreeNamesByRepo?.[repoId] + return stored + ? { exhaustedTiers: stored.exhaustedTiers, names: [...stored.names] } + : EMPTY_RETIRED_NAME_REGISTRY } /** Records a generated workspace name as spent for this repo. Called with the name main actually @@ -7261,15 +7272,7 @@ export class Store { if (!repoId || !normalized) { return } - this.state.retiredWorktreeNamesByRepo ??= {} - const existing = this.state.retiredWorktreeNamesByRepo[repoId] - if (existing?.includes(normalized)) { - return - } - this.state.retiredWorktreeNamesByRepo[repoId] = boundRetiredWorktreeNames( - existing ? [...existing, normalized] : [normalized] - ) - this.scheduleSave() + this.applyRetiredWorktreeNames(repoId, [normalized]) } /** Seeds retirements discovered by the one-time backfill. Merges rather than replaces so a @@ -7285,19 +7288,16 @@ export class Store { incoming.add(normalized) } } - if (incoming.size === 0) { + return incoming.size > 0 && this.applyRetiredWorktreeNames(repoId, incoming) + } + + private applyRetiredWorktreeNames(repoId: string, names: Iterable): boolean { + const next = addRetiredNames(this.getRetiredWorktreeNameRegistry(repoId), names) + if (!next) { return false } this.state.retiredWorktreeNamesByRepo ??= {} - const existing = this.state.retiredWorktreeNamesByRepo[repoId] ?? [] - const merged = new Set(existing) - for (const name of incoming) { - merged.add(name) - } - if (merged.size === existing.length) { - return false - } - this.state.retiredWorktreeNamesByRepo[repoId] = boundRetiredWorktreeNames([...merged]) + this.state.retiredWorktreeNamesByRepo[repoId] = next this.scheduleSave() return true } diff --git a/src/main/runtime/fit-override-integration.test.ts b/src/main/runtime/fit-override-integration.test.ts index 98a3b1655052..df3742922b5c 100644 --- a/src/main/runtime/fit-override-integration.test.ts +++ b/src/main/runtime/fit-override-integration.test.ts @@ -64,7 +64,7 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getSettings: () => ({ diff --git a/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts b/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts index b1c8d866eb61..28545391fa96 100644 --- a/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts +++ b/src/main/runtime/graph-sync-mobile-snapshot-gating.test.ts @@ -54,7 +54,7 @@ const storeBase = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getSettings: () => ({ diff --git a/src/main/runtime/graph-sync-payload-partition.test.ts b/src/main/runtime/graph-sync-payload-partition.test.ts index a3b3a930023c..5a76d5e72ad3 100644 --- a/src/main/runtime/graph-sync-payload-partition.test.ts +++ b/src/main/runtime/graph-sync-payload-partition.test.ts @@ -31,7 +31,7 @@ const storeBase = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getSettings: () => ({ diff --git a/src/main/runtime/mobile-presence-lock.test.ts b/src/main/runtime/mobile-presence-lock.test.ts index 701f87847930..8ec53b399ed8 100644 --- a/src/main/runtime/mobile-presence-lock.test.ts +++ b/src/main/runtime/mobile-presence-lock.test.ts @@ -49,7 +49,7 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getSettings: () => ({ diff --git a/src/main/runtime/mobile-subscribe-integration.test.ts b/src/main/runtime/mobile-subscribe-integration.test.ts index 75318ab8b511..f055c47e8274 100644 --- a/src/main/runtime/mobile-subscribe-integration.test.ts +++ b/src/main/runtime/mobile-subscribe-integration.test.ts @@ -70,7 +70,7 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getSettings: () => ({ diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index baf7df67fb95..65fdb7feed92 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -1330,7 +1330,7 @@ const store = { } ], addRetiredWorktreeName: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), mergeRetiredWorktreeNames: () => false, addRepo: () => {}, updateRepo: (id: string, updates: Record) => @@ -4297,7 +4297,7 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName, - getRetiredWorktreeNames: () => ['nautilus'] + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: ['nautilus'] }) }) const staleScan = deferred() const createdWorktree = { @@ -4343,7 +4343,7 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName, - getRetiredWorktreeNames: () => ['nautilus'] + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: ['nautilus'] }) }) const createdWorktree = { path: '/tmp/workspaces/nautilus', @@ -48816,7 +48816,7 @@ describe('OrcaRuntimeService', () => { return nextMeta }, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getGitHubCache: () => undefined as never, diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index d964c484de7b..0767e6b9363e 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -967,8 +967,12 @@ import { } from '../worktree-create-candidates' import { ensureRetiredWorktreeNamesBackfilled, - getRetiredWorktreeNamesForRepo + getRetiredNameRegistryForRepo } from '../worktree-name-retirement' +import { + createRetiredNameLookup, + type RetiredNameRegistry +} from '../../shared/worktree/retired-name-registry' import { normalizeSparseDirectories } from '../ipc/sparse-checkout-directories' import type { PtyBindingSourceExpectation, Store } from '../persistence' import type { StatsCollector } from '../stats/collector' @@ -1146,7 +1150,7 @@ type RuntimeStore = { getRepos: Store['getRepos'] getRepo: Store['getRepo'] addRetiredWorktreeName: Store['addRetiredWorktreeName'] - getRetiredWorktreeNames: Store['getRetiredWorktreeNames'] + getRetiredWorktreeNameRegistry: Store['getRetiredWorktreeNameRegistry'] mergeRetiredWorktreeNames: Store['mergeRetiredWorktreeNames'] addRepo: Store['addRepo'] updateRepo: Store['updateRepo'] @@ -21328,11 +21332,19 @@ export class OrcaRuntimeService { } /** Keyed by repo id on the wire even though one repo is requested: the caller asked by selector - * and needs to know which repo answered. */ - async listRetiredWorktreeNames(repoSelector: string): Promise> { + * and needs to know which repo answered. + * + * The tier watermark rides alongside the names rather than being expanded into them — expanding + * it would put 552 strings per spent tier on the wire, which is what compaction exists to + * avoid. A client predating the field reads the names only and under-retires, degrading to the + * pre-retirement behavior for compacted tiers instead of breaking. */ + async listRetiredWorktreeNames(repoSelector: string): Promise<{ + retiredNamesByRepo: Record + retiredNameTiersByRepo: Record + }> { const store = this.store if (!store) { - return {} + return { retiredNamesByRepo: {}, retiredNameTiersByRepo: {} } } const repo = await this.resolveRepoSelector(repoSelector) const settings = store.getSettings() @@ -21341,7 +21353,16 @@ export class OrcaRuntimeService { } catch (error) { console.warn(`[runtime] retirement backfill failed for repo ${repo.id}:`, error) } - return { [repo.id]: getRetiredWorktreeNamesForRepo(store, repo, store.getRepos(), settings) } + const registry: RetiredNameRegistry = getRetiredNameRegistryForRepo( + store, + repo, + store.getRepos(), + settings + ) + return { + retiredNamesByRepo: { [repo.id]: registry.names }, + retiredNameTiersByRepo: { [repo.id]: registry.exhaustedTiers } + } } async listDetectedManagedWorktrees( @@ -22549,8 +22570,10 @@ export class OrcaRuntimeService { let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false - const retiredNames = args.nameWasGenerated - ? new Set(getRetiredWorktreeNamesForRepo(this.store, repo, this.store.getRepos(), settings)) + const isRetiredName = args.nameWasGenerated + ? createRetiredNameLookup( + getRetiredNameRegistryForRepo(this.store, repo, this.store.getRepos(), settings) + ) : null // Why: runtime/mobile create-from-review callers should get a new workspace // even when the PR branch or review branch name is already in use. @@ -22559,7 +22582,7 @@ export class OrcaRuntimeService { effectiveRequestedName = args.name.trim() ? getWorktreeCreateCandidate(args.name, suffix) : effectiveSanitizedName - if (retiredNames?.has(effectiveSanitizedName)) { + if (isRetiredName?.(effectiveSanitizedName)) { continue } branchName = await resolveCreateBranchName( diff --git a/src/main/runtime/remote-desktop-driver.test.ts b/src/main/runtime/remote-desktop-driver.test.ts index 5d976ac517e2..2ff49c03bf92 100644 --- a/src/main/runtime/remote-desktop-driver.test.ts +++ b/src/main/runtime/remote-desktop-driver.test.ts @@ -58,7 +58,7 @@ const store = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getSettings: () => ({ diff --git a/src/main/runtime/rpc/methods/worktree-catalog-methods.ts b/src/main/runtime/rpc/methods/worktree-catalog-methods.ts index 9bd88984cc1e..2010a219b7c6 100644 --- a/src/main/runtime/rpc/methods/worktree-catalog-methods.ts +++ b/src/main/runtime/rpc/methods/worktree-catalog-methods.ts @@ -38,9 +38,7 @@ export const WORKTREE_CATALOG_METHODS: RpcMethod[] = [ defineMethod({ name: 'worktree.listRetiredNames', params: WorktreeDetectedListParams, - handler: async (params, { runtime }) => ({ - retiredNamesByRepo: await runtime.listRetiredWorktreeNames(params.repo) - }) + handler: async (params, { runtime }) => runtime.listRetiredWorktreeNames(params.repo) }), defineMethod({ name: 'worktree.detectedList', diff --git a/src/main/runtime/rpc/methods/worktree-retired-names.test.ts b/src/main/runtime/rpc/methods/worktree-retired-names.test.ts new file mode 100644 index 000000000000..3c4c6f3755d6 --- /dev/null +++ b/src/main/runtime/rpc/methods/worktree-retired-names.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it, vi } from 'vitest' +import { RpcDispatcher } from '../dispatcher' +import type { RpcRequest } from '../core' +import type { OrcaRuntimeService } from '../../orca-runtime' +import { WORKTREE_METHODS } from './worktree' + +// The watermark rides alongside the names rather than being expanded into them; a client +// predating the field reads the names only and under-retires the compacted tiers. +const RETIRED = { + retiredNamesByRepo: { 'repo-1': ['nautilus-2'] }, + retiredNameTiersByRepo: { 'repo-1': 1 } +} + +describe('worktree.listRetiredNames', () => { + it('returns retired names and the compaction watermark, without the worktree listing', async () => { + const runtime = { + getRuntimeId: () => 'test-runtime', + listRetiredWorktreeNames: vi.fn().mockResolvedValue(RETIRED) + } as unknown as OrcaRuntimeService + const request: RpcRequest = { + id: 'req-1', + authToken: 'tok', + method: 'worktree.listRetiredNames', + params: { repo: 'id:repo-1' } + } + + const response = await new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }).dispatch( + request + ) + + expect(runtime.listRetiredWorktreeNames).toHaveBeenCalledWith('id:repo-1') + expect(response).toMatchObject({ ok: true, result: RETIRED }) + }) +}) diff --git a/src/main/runtime/rpc/methods/worktree.test.ts b/src/main/runtime/rpc/methods/worktree.test.ts index d70e5941a0c5..0b5be4da3845 100644 --- a/src/main/runtime/rpc/methods/worktree.test.ts +++ b/src/main/runtime/rpc/methods/worktree.test.ts @@ -25,23 +25,6 @@ const passthroughDedupe = (_repo: string, _id: string | undefined, run: () => run() describe('worktree RPC methods', () => { - it('returns retired names without exposing the full worktree listing', async () => { - const runtime = { - getRuntimeId: () => 'test-runtime', - listRetiredWorktreeNames: vi.fn().mockResolvedValue({ 'repo-1': ['nautilus'] }) - } as unknown as OrcaRuntimeService - - const response = await new RpcDispatcher({ runtime, methods: WORKTREE_METHODS }).dispatch( - makeRequest('worktree.listRetiredNames', { repo: 'id:repo-1' }) - ) - - expect(runtime.listRetiredWorktreeNames).toHaveBeenCalledWith('id:repo-1') - expect(response).toMatchObject({ - ok: true, - result: { retiredNamesByRepo: { 'repo-1': ['nautilus'] } } - }) - }) - it('routes mobile session-only activation without notifying desktop clients', async () => { const runtime = { getRuntimeId: () => 'test-runtime', diff --git a/src/main/runtime/terminal-query-responder.test.ts b/src/main/runtime/terminal-query-responder.test.ts index 9d55139f6770..9db883529a00 100644 --- a/src/main/runtime/terminal-query-responder.test.ts +++ b/src/main/runtime/terminal-query-responder.test.ts @@ -37,7 +37,7 @@ const store = { getWorktreeMeta: () => undefined, setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, - getRetiredWorktreeNames: () => [], + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), addRetiredWorktreeName: () => {}, mergeRetiredWorktreeNames: () => false, getGitHubCache: () => ({ pr: {}, issue: {} }) as never, diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index a554b15aec61..e2ec1ab826f2 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -10,7 +10,7 @@ import { discoverRetiredWorktreeNames, ensureRetiredWorktreeNamesBackfilled, extractBucketLeafCandidates, - getRetiredWorktreeNamesForRepo, + getRetiredNameRegistryForRepo, normalizeRetirableGeneratedName, resetRetirementCollisionKeyCacheForTests } from './worktree-name-retirement' @@ -207,16 +207,16 @@ describe('discoverRetiredWorktreeNames', () => { }) }) -describe('getRetiredWorktreeNamesForRepo', () => { +describe('getRetiredNameRegistryForRepo', () => { const settingsFor = (nestWorkspaces: boolean): GlobalSettings => ({ workspaceDir: '/workspaces', nestWorkspaces }) as GlobalSettings const storeOf = (byRepo: Record) => { const calls: string[] = [] return { calls, - getRetiredWorktreeNames: (repoId: string) => { + getRetiredWorktreeNameRegistry: (repoId: string) => { calls.push(repoId) - return byRepo[repoId] ?? [] + return { exhaustedTiers: 0, names: byRepo[repoId] ?? [] } } } } @@ -226,7 +226,7 @@ describe('getRetiredWorktreeNamesForRepo', () => { const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] expect( - getRetiredWorktreeNamesForRepo(store, repos[1], repos, settingsFor(false)).sort() + [...getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(false)).names].sort() ).toEqual([FIRST, SECOND].sort()) }) @@ -234,9 +234,10 @@ describe('getRetiredWorktreeNamesForRepo', () => { const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - expect(getRetiredWorktreeNamesForRepo(store, repos[1], repos, settingsFor(true))).toEqual([ - SECOND - ]) + expect(getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(true))).toEqual({ + exhaustedTiers: 0, + names: [SECOND] + }) }) it('never probes a path for peers that hold no retirements', () => { @@ -258,9 +259,10 @@ describe('getRetiredWorktreeNamesForRepo', () => { ...Array.from({ length: 20 }, (_unused, index) => spyRepo(`peer-${index}`, `/repos/${index}`)) ] - expect(getRetiredWorktreeNamesForRepo(store, repos[0], repos, settingsFor(false))).toEqual([ - FIRST - ]) + expect(getRetiredNameRegistryForRepo(store, repos[0], repos, settingsFor(false))).toEqual({ + exhaustedTiers: 0, + names: [FIRST] + }) expect(pathReads.filter((id) => id.startsWith('peer-'))).toEqual([]) }) @@ -269,7 +271,7 @@ describe('getRetiredWorktreeNamesForRepo', () => { const folderRepo = { ...makeRepo('folder', '/repos/folder'), kind: 'folder' as const } expect( - getRetiredWorktreeNamesForRepo(store, folderRepo, [folderRepo], settingsFor(false)) + getRetiredNameRegistryForRepo(store, folderRepo, [folderRepo], settingsFor(false)).names ).toEqual([]) }) }) diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index c9a3f0b7569b..ba73ba2525dc 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -1,8 +1,14 @@ import { readdir } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' -import { MARINE_CREATURES } from '../shared/marine-creatures' import { getRepoExecutionHostId } from '../shared/execution-host' +import { + CREATURE_POOL_NAMES, + EMPTY_RETIRED_NAME_REGISTRY, + isEmptyRetiredNameRegistry, + mergeRetiredNameRegistries, + type RetiredNameRegistry +} from '../shared/worktree/retired-name-registry' import { isFolderRepo } from '../shared/repo-kind' import type { GlobalSettings } from '../shared/global-settings-types' import type { Repo } from '../shared/repo-types' @@ -20,12 +26,11 @@ import { import { worktreePathComparisonKey } from './ipc/worktree-path-comparison' import { hasCachedWslHome, parseWslPath } from './wsl' -const POOL_NAMES: ReadonlySet = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) const RETIREMENT_PROBE_NAME = 'orca-retirement-probe' const scansByStore = new WeakMap>>>() type RetirementReadStore = { - getRetiredWorktreeNames(repoId: string): string[] + getRetiredWorktreeNameRegistry(repoId: string): RetiredNameRegistry } type RetirementBackfillStore = { mergeRetiredWorktreeNames(repoId: string, names: Iterable): boolean @@ -48,7 +53,7 @@ export function normalizeRetirableGeneratedName(name: string): string | null { base = stripped stripped = base.replace(/-\d+$/, '') } - return base && POOL_NAMES.has(base) ? normalized : null + return base && CREATURE_POOL_NAMES.has(base) ? normalized : null } /** Why: over-retiring costs one name from a 552-entry pool; under-retiring reissues a path whose @@ -143,34 +148,32 @@ export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSe * The peer scan is deliberately lazy: a repo's own retirements never touch a path, and a peer's * namespace is derived only once that peer is known to hold retirements. Deriving one costs a * blocking `wsl.exe` call for a WSL repo, so it must not be paid per repo on every create. */ -export function getRetiredWorktreeNamesForRepo( +export function getRetiredNameRegistryForRepo( store: RetirementReadStore, repo: Repo, repos: readonly Repo[], settings: RetirementPathSettings -): string[] { +): RetiredNameRegistry { if (isFolderRepo(repo)) { - return [] + return EMPTY_RETIRED_NAME_REGISTRY } - const names = new Set(store.getRetiredWorktreeNames(repo.id)) + let registry = store.getRetiredWorktreeNameRegistry(repo.id) let collisionKey: string | null = null for (const candidate of repos) { if (candidate.id === repo.id || isFolderRepo(candidate)) { continue } - const candidateNames = store.getRetiredWorktreeNames(candidate.id) - if (candidateNames.length === 0) { + const candidateRegistry = store.getRetiredWorktreeNameRegistry(candidate.id) + if (isEmptyRetiredNameRegistry(candidateRegistry)) { continue } collisionKey ??= getRetirementCollisionKey(repo, settings) if (getRetirementCollisionKey(candidate, settings) !== collisionKey) { continue } - for (const name of candidateNames) { - names.add(name) - } + registry = mergeRetiredNameRegistries(registry, candidateRegistry) } - return [...names] + return registry } function parentPath(path: string): string { diff --git a/src/preload/api/worktree-api.ts b/src/preload/api/worktree-api.ts index b8cf651265ca..7a85bd51a320 100644 --- a/src/preload/api/worktree-api.ts +++ b/src/preload/api/worktree-api.ts @@ -9,6 +9,7 @@ import type { ProviderRequestId } from '../../shared/detected-worktree-provider-contract' import type { ExecutionHostId } from '../../shared/execution-host' +import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' import type { FolderWorkspacePathStatus, FolderWorkspacePathStatusRequest @@ -43,8 +44,9 @@ import type { export type WorktreeApi = { list: (args: { repoId: string }) => Promise /** Generated names already spent in this repo, including deleted workspaces. Name suggestions - * exclude these so a recreated workspace never lands on a prior occupant's path. */ - listRetiredNames: (args: { repoId: string }) => Promise + * exclude these so a recreated workspace never lands on a prior occupant's path. Compacted: a + * fully spent tier is reported as the watermark rather than as its 552 names. */ + listRetiredNames: (args: { repoId: string }) => Promise listDetected: { ( args: ListDetectedWorktreesArgs diff --git a/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts b/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts index fe9403b8e8ca..f75660dbcb06 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.test.ts @@ -11,6 +11,7 @@ import { const pickFirst = () => 0 // Suggestions are lowercased (branch-name convention), so expectations are too. const lower = (index: number) => MARINE_CREATURES[index].toLowerCase() +const retiring = (...names: string[]) => ({ exhaustedTiers: 0, names }) describe('getSuggestedCreatureName', () => { it('picks the first unused name when the RNG selects index 0', () => { @@ -59,13 +60,13 @@ describe('getSuggestedCreatureName', () => { it('never reissues a retired name whose workspace is already deleted', () => { // The bug this guards: the deleted workspace's path still holds agent conversation // history, so handing the name out again gives the next occupant someone else's chat. - expect(getSuggestedCreatureName({}, pickFirst, [MARINE_CREATURES[0]])).toBe(lower(1)) + expect(getSuggestedCreatureName({}, pickFirst, retiring(MARINE_CREATURES[0]))).toBe(lower(1)) }) it('treats retired names case-insensitively', () => { - expect(getSuggestedCreatureName({}, pickFirst, [MARINE_CREATURES[0].toUpperCase()])).toBe( - lower(1) - ) + expect( + getSuggestedCreatureName({}, pickFirst, retiring(MARINE_CREATURES[0].toUpperCase())) + ).toBe(lower(1)) }) it('retires names on top of live worktrees rather than replacing that check', () => { @@ -73,7 +74,7 @@ describe('getSuggestedCreatureName', () => { getSuggestedCreatureName( { 'repo-1': [{ path: `/tmp/worktrees/${MARINE_CREATURES[0]}` }] }, pickFirst, - [MARINE_CREATURES[1]] + retiring(MARINE_CREATURES[1]) ) ).toBe(lower(2)) }) @@ -81,9 +82,9 @@ describe('getSuggestedCreatureName', () => { it('skips a retired suffixed variant when falling back past an exhausted pool', () => { // Tier numbering must not rewind onto a spent variant after its workspace is deleted. const allUsed = MARINE_CREATURES.map((name) => ({ path: `/tmp/worktrees/${name}` })) - expect(getSuggestedCreatureName({ 'repo-1': allUsed }, pickFirst, [`${lower(0)}-2`])).toBe( - `${lower(1)}-2` - ) + expect( + getSuggestedCreatureName({ 'repo-1': allUsed }, pickFirst, retiring(`${lower(0)}-2`)) + ).toBe(`${lower(1)}-2`) }) it('treats used names case-insensitively', () => { diff --git a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts index 64827392bb7a..295137b92225 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts @@ -3,6 +3,10 @@ import { selectSuggestedCreatureName, suggestionPathBasename } from '../../../../shared/worktree-name-suggestion' +import { + EMPTY_RETIRED_NAME_REGISTRY, + type RetiredNameRegistry +} from '../../../../shared/worktree/retired-name-registry' type WorktreePathLike = { path: string @@ -22,24 +26,27 @@ function collectUsedNames(worktreesByRepo: Record): return usedNames } -/** `retiredNames` are names already spent in the active repo, including ones whose workspace was +/** `retired` holds names already spent in the active repo, including ones whose workspace was * deleted. Reissuing one would place the new workspace on the prior occupant's path, where agent * CLIs would hand it that workspace's conversation history — so spent names are never offered * again, and the pool degrades to suffixed variants instead of recycling. * + * Its `exhaustedTiers` watermark stands in for the tiers the registry has compacted away; those + * names are absent from `names` because they are all spent, not because they are available. + * * Live dedup stays cross-repo while retirement is per-repo: two live workspaces sharing a name * are confusing in a flat sidebar, but a name retired under one repo says nothing about the same * name under another, whose path never collided. */ export function getSuggestedCreatureName( worktreesByRepo: Record, random: () => number = Math.random, - retiredNames: Iterable = [] + retired: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY ): string { const usedNames = collectUsedNames(worktreesByRepo) - for (const retiredName of retiredNames) { + for (const retiredName of retired.names) { usedNames.add(normalizeSuggestedName(retiredName)) } - return selectSuggestedCreatureName(usedNames, random) + return selectSuggestedCreatureName(usedNames, random, retired.exhaustedTiers) } export function shouldApplySuggestedName(name: string, previousSuggestedName: string): boolean { diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts index 2c795a7c536e..16b33fcdc032 100644 --- a/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts @@ -5,6 +5,7 @@ import { renderHook, waitFor } from '@testing-library/react' import { useRetiredWorktreeNames } from './useRetiredWorktreeNames' const listRetiredNames = vi.fn() +const registry = (names: string[], exhaustedTiers = 0) => ({ exhaustedTiers, names }) beforeEach(() => { listRetiredNames.mockReset() @@ -15,36 +16,36 @@ describe('useRetiredWorktreeNames', () => { it('keeps the previous names while a refresh is in flight', async () => { // Why: refreshKey changes on every workspace-list mutation, so create-multiple refetches after // each create. Dropping to empty in between would suggest a spent name in exactly that window. - listRetiredNames.mockResolvedValueOnce(['nautilus']) + listRetiredNames.mockResolvedValueOnce(registry(['nautilus'])) const { result, rerender } = renderHook( ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } ) - await waitFor(() => expect(result.current).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus']))) - let resolveSecond: (names: string[]) => void = () => {} + let resolveSecond: (loaded: ReturnType) => void = () => {} listRetiredNames.mockReturnValueOnce( - new Promise((resolve) => { + new Promise>((resolve) => { resolveSecond = resolve }) ) rerender({ key: 'b' }) - expect(result.current).toEqual(['nautilus']) + expect(result.current).toEqual(registry(['nautilus'])) - resolveSecond(['nautilus', 'seahorse']) - await waitFor(() => expect(result.current).toEqual(['nautilus', 'seahorse'])) + resolveSecond(registry(['nautilus', 'seahorse'], 1)) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus', 'seahorse'], 1))) }) - it('returns a referentially stable array across refreshes that change nothing', async () => { - // The suggestion memo downstream keys on this array; a new identity per refetch reruns it. - const names = ['nautilus'] - listRetiredNames.mockResolvedValue(names) + it('returns a referentially stable registry across refreshes that change nothing', async () => { + // The suggestion memo downstream keys on this object; a new identity per refetch reruns it. + const loaded = registry(['nautilus']) + listRetiredNames.mockResolvedValue(loaded) const { result, rerender } = renderHook( ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } ) - await waitFor(() => expect(result.current).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus']))) const first = result.current rerender({ key: 'b' }) @@ -53,37 +54,37 @@ describe('useRetiredWorktreeNames', () => { }) it('drops names when the repo changes rather than showing another repo pool', async () => { - listRetiredNames.mockResolvedValueOnce(['nautilus']) + listRetiredNames.mockResolvedValueOnce(registry(['nautilus'])) const { result, rerender } = renderHook( ({ repoId }: { repoId: string }) => useRetiredWorktreeNames(repoId, 'key'), { initialProps: { repoId: 'repo-1' } } ) - await waitFor(() => expect(result.current).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus']))) - listRetiredNames.mockReturnValueOnce(new Promise(() => {})) + listRetiredNames.mockReturnValueOnce(new Promise(() => {})) rerender({ repoId: 'repo-2' }) - expect(result.current).toEqual([]) + expect(result.current).toEqual(registry([])) }) it('keeps previously loaded names when a refresh fails', async () => { - listRetiredNames.mockResolvedValueOnce(['nautilus']) + listRetiredNames.mockResolvedValueOnce(registry(['nautilus'])) const { result, rerender } = renderHook( ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } ) - await waitFor(() => expect(result.current).toEqual(['nautilus'])) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus']))) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) listRetiredNames.mockRejectedValueOnce(new Error('host unreachable')) rerender({ key: 'b' }) await waitFor(() => expect(warn).toHaveBeenCalled()) - expect(result.current).toEqual(['nautilus']) + expect(result.current).toEqual(registry(['nautilus'])) }) it('refetches when the refresh key changes', async () => { - listRetiredNames.mockResolvedValue(['nautilus']) + listRetiredNames.mockResolvedValue(registry(['nautilus'])) const { rerender } = renderHook( ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), { initialProps: { key: 'a' } } diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.ts index c4a7e9488423..32097cde6fb0 100644 --- a/src/renderer/src/hooks/useRetiredWorktreeNames.ts +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.ts @@ -1,9 +1,10 @@ import { useEffect, useState } from 'react' import { retiredNamesAfterRefresh, - selectRetiredNames, + selectRetiredNameRegistry, type RetiredNamesLoad } from '../../../shared/worktree/retired-name-cache' +import type { RetiredNameRegistry } from '../../../shared/worktree/retired-name-registry' /** Names already spent in a repo, including workspaces that have since been deleted. * @@ -20,7 +21,7 @@ import { export function useRetiredWorktreeNames( repoId: string | null | undefined, refreshKey: unknown -): readonly string[] { +): RetiredNameRegistry { const [loaded, setLoaded] = useState(null) useEffect(() => { @@ -29,9 +30,9 @@ export function useRetiredWorktreeNames( return } let cancelled = false - const settle = (names: readonly string[] | null): void => { + const settle = (registry: RetiredNameRegistry | null): void => { if (!cancelled) { - setLoaded((previous) => retiredNamesAfterRefresh(previous, repoId, names)) + setLoaded((previous) => retiredNamesAfterRefresh(previous, repoId, registry)) } } void window.api.worktrees @@ -46,5 +47,5 @@ export function useRetiredWorktreeNames( } }, [refreshKey, repoId]) - return selectRetiredNames(loaded, repoId) + return selectRetiredNameRegistry(loaded, repoId) } diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 44b0659aa371..8b331ded24e3 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -65,7 +65,8 @@ import { legacyBaseRefSearchResult } from '../../../shared/base-ref-search-resul import { EMPTY_PTY_MAIN_DELIVERY_DIAGNOSTICS } from '../../../shared/pty-delivery-diagnostics' import { createE2EConfig } from '../../../shared/e2e-config' import { relativePathInsideRoot } from '../../../shared/cross-platform-path' -import { readRetiredNamesForRepo } from '../../../shared/worktree/retired-name-cache' +import { readRetiredNameRegistryForRepo } from '../../../shared/worktree/retired-name-cache' +import { EMPTY_RETIRED_NAME_REGISTRY } from '../../../shared/worktree/retired-name-registry' import { applyPRBotAuthorOverride, normalizePRBotAuthorOverrides @@ -1803,12 +1804,12 @@ function createWorktreesApi(): NonNullable['worktrees']> { // degrades the suggestion to the pre-existing behavior rather than blocking workspace create. listRetiredNames: async ({ repoId }) => { try { - return readRetiredNamesForRepo( + return readRetiredNameRegistryForRepo( await callRuntimeResult('worktree.listRetiredNames', { repo: repoId }), repoId ) } catch { - return [] + return EMPTY_RETIRED_NAME_REGISTRY } }, listDetected: async ({ repoId }) => callRuntimeDetectedWorktrees(repoId), diff --git a/src/shared/persisted-state-types.ts b/src/shared/persisted-state-types.ts index 5ea842e1b5e4..c66c335188c8 100644 --- a/src/shared/persisted-state-types.ts +++ b/src/shared/persisted-state-types.ts @@ -19,6 +19,7 @@ import type { ProjectGroup } from './project-group-types' import type { Project, ProjectHostSetup } from './project-types' import type { Repo } from './repo-types' import type { SparsePreset } from './worktree/create-types' +import type { RetiredNameRegistry } from './worktree/retired-name-registry' import type { WorkspaceLineage, WorktreeLineage } from './worktree/lineage-types' import type { WorktreeMeta } from './worktree/meta-types' import type { WorkspaceSessionState } from './workspace-session-state-types' @@ -68,8 +69,10 @@ export type PersistedState = { * that cwd. Grows monotonically within a repo — entries are never removed on workspace deletion * — and is dropped wholesale when the repo is removed. Readers union across every repo that * creates into the same cwd namespace, so the storage key stays the stable repo id while the - * guarantee follows the path. */ - retiredWorktreeNamesByRepo?: Record + * guarantee follows the path. + * + * Stored compacted, not as a flat list: a fully spent tier collapses into the row's watermark. */ + retiredWorktreeNamesByRepo?: Record /** Per paired device last tab selection by worktree; keeps mobile navigation across host restarts. */ mobileClientTabSelectionsByDeviceId?: PersistedMobileClientTabSelections worktreeMeta: Record diff --git a/src/shared/worktree-name-suggestion.test.ts b/src/shared/worktree-name-suggestion.test.ts index a24f9581903b..9d6cd3607eb3 100644 --- a/src/shared/worktree-name-suggestion.test.ts +++ b/src/shared/worktree-name-suggestion.test.ts @@ -54,6 +54,20 @@ describe('selectSuggestedCreatureName', () => { expect(selectSuggestedCreatureName(allUsed, pickFirst)).toBe(`${lower(0)}-3`) }) + it('starts above the exhausted-tier watermark instead of looking those names up', () => { + // The registry compacts a fully spent tier away, so its names are absent from the used set + // precisely because they are all taken. Starting at tier 1 would hand one straight back. + expect(selectSuggestedCreatureName([], pickFirst, 2)).toBe(`${lower(0)}-3`) + }) + + it('keeps the watermark and the used set both in force', () => { + expect(selectSuggestedCreatureName([`${lower(0)}-3`], pickFirst, 2)).toBe(`${lower(1)}-3`) + }) + + it('ignores a nonsense watermark rather than skipping the pool', () => { + expect(selectSuggestedCreatureName([], pickFirst, -4)).toBe(lower(0)) + }) + it('returns a lowercase name to match branch convention', () => { // Pool entries are capitalized; branch names are conventionally lowercase. const suggested = selectSuggestedCreatureName([], pickFirst) diff --git a/src/shared/worktree-name-suggestion.ts b/src/shared/worktree-name-suggestion.ts index c9c23838206e..c2cc2450d5b1 100644 --- a/src/shared/worktree-name-suggestion.ts +++ b/src/shared/worktree-name-suggestion.ts @@ -1,4 +1,5 @@ import { MARINE_CREATURES } from './marine-creatures' +import { clampExhaustedTiers, creatureNameAtTier } from './worktree/retired-name-registry' /** Shared selection core for generated workspace names. * @@ -36,29 +37,29 @@ function pickRandom(items: readonly T[], random: () => number): T { * `usedNames` must include retired names as well as live ones. A name whose workspace was deleted * still owns its old directory path in any agent CLI that keys conversation state by cwd, so * reissuing it hands the next occupant someone else's history. Once every base name is spent the - * pool degrades to `name-2`, `name-3`, and those variants are equally subject to retirement. */ + * pool degrades to `name-2`, `name-3`, and those variants are equally subject to retirement. + * + * `exhaustedTiers` is the retirement registry's compaction watermark. The registry stops listing + * a tier's names individually once every one of them is spent, so those tiers must be skipped + * here rather than looked up — they are absent from `usedNames` precisely because they are gone. */ export function selectSuggestedCreatureName( usedNames: Iterable, - random: () => number = Math.random + random: () => number = Math.random, + exhaustedTiers = 0 ): string { const used = new Set() for (const name of usedNames) { used.add(normalizeSuggestedName(name)) } - const available = MARINE_CREATURES.map(normalizeSuggestedName).filter((name) => !used.has(name)) - if (available.length > 0) { - return pickRandom(available, random) - } - - let suffix = 2 + let tier = clampExhaustedTiers(exhaustedTiers) + 1 while (true) { - const numbered = MARINE_CREATURES.map( - (name) => `${normalizeSuggestedName(name)}-${suffix}` + const available = MARINE_CREATURES.map((name) => + creatureNameAtTier(normalizeSuggestedName(name), tier) ).filter((name) => !used.has(name)) - if (numbered.length > 0) { - return pickRandom(numbered, random) + if (available.length > 0) { + return pickRandom(available, random) } - suffix += 1 + tier += 1 } } diff --git a/src/shared/worktree/retired-name-cache.test.ts b/src/shared/worktree/retired-name-cache.test.ts index dacc3f0a58b5..dc471ad7c062 100644 --- a/src/shared/worktree/retired-name-cache.test.ts +++ b/src/shared/worktree/retired-name-cache.test.ts @@ -1,15 +1,47 @@ import { describe, expect, it } from 'vitest' import { - NO_RETIRED_NAMES, - readRetiredNamesForRepo, + readRetiredNameRegistryForRepo, retiredNamesAfterRefresh, - selectRetiredNames + selectRetiredNameRegistry } from './retired-name-cache' +import { EMPTY_RETIRED_NAME_REGISTRY } from './retired-name-registry' -describe('readRetiredNamesForRepo', () => { +const loadOf = (repoId: string, names: readonly string[], exhaustedTiers = 0) => ({ + repoId, + registry: { exhaustedTiers, names } +}) + +describe('readRetiredNameRegistryForRepo', () => { it('reads the requested repo only', () => { const result = { retiredNamesByRepo: { 'repo-1': ['nautilus'], 'repo-2': ['seahorse'] } } - expect(readRetiredNamesForRepo(result, 'repo-1')).toEqual(['nautilus']) + expect(readRetiredNameRegistryForRepo(result, 'repo-1')).toEqual({ + exhaustedTiers: 0, + names: ['nautilus'] + }) + }) + + it('carries the compaction watermark alongside the names', () => { + const result = { + retiredNamesByRepo: { 'repo-1': ['nautilus-2'] }, + retiredNameTiersByRepo: { 'repo-1': 1, 'repo-2': 3 } + } + expect(readRetiredNameRegistryForRepo(result, 'repo-1')).toEqual({ + exhaustedTiers: 1, + names: ['nautilus-2'] + }) + }) + + it.each([ + ['a host predating the watermark field', { retiredNamesByRepo: { 'repo-1': ['nautilus'] } }], + [ + 'a garbage watermark', + { + retiredNamesByRepo: { 'repo-1': ['nautilus'] }, + retiredNameTiersByRepo: { 'repo-1': 'lots' } + } + ] + ])('degrades to no watermark for %s', (_label, result) => { + expect(readRetiredNameRegistryForRepo(result, 'repo-1').exhaustedTiers).toBe(0) }) it.each([ @@ -19,58 +51,58 @@ describe('readRetiredNamesForRepo', () => { ['a null result', null], ['a non-object result', 'nope'] ])('answers empty for %s', (_label, result) => { - expect(readRetiredNamesForRepo(result, 'repo-1')).toEqual([]) + expect(readRetiredNameRegistryForRepo(result, 'repo-1')).toEqual(EMPTY_RETIRED_NAME_REGISTRY) }) it('drops non-string elements, which would throw when normalized', () => { const result = { retiredNamesByRepo: { 'repo-1': ['nautilus', 42, null, 'seahorse'] } } - expect(readRetiredNamesForRepo(result, 'repo-1')).toEqual(['nautilus', 'seahorse']) + expect(readRetiredNameRegistryForRepo(result, 'repo-1').names).toEqual(['nautilus', 'seahorse']) }) }) describe('retiredNamesAfterRefresh', () => { - it('takes the new names on success', () => { - const previous = { repoId: 'repo-1', names: ['nautilus'] } - expect(retiredNamesAfterRefresh(previous, 'repo-1', ['nautilus', 'seahorse'])).toEqual({ - repoId: 'repo-1', - names: ['nautilus', 'seahorse'] - }) + it('takes the new registry on success', () => { + expect( + retiredNamesAfterRefresh(loadOf('repo-1', ['nautilus']), 'repo-1', { + exhaustedTiers: 1, + names: ['nautilus-2'] + }) + ).toEqual(loadOf('repo-1', ['nautilus-2'], 1)) }) // The divergence this module exists to close: mobile used to reset to [] here, which un-retires // every name in the window where the create form is asking for a suggestion. - it('holds the previous names when the refresh fails', () => { - const previous = { repoId: 'repo-1', names: ['nautilus'] } - expect(retiredNamesAfterRefresh(previous, 'repo-1', null)).toEqual({ - repoId: 'repo-1', - names: ['nautilus'] - }) + it('holds the previous registry when the refresh fails', () => { + expect(retiredNamesAfterRefresh(loadOf('repo-1', ['nautilus'], 2), 'repo-1', null)).toEqual( + loadOf('repo-1', ['nautilus'], 2) + ) }) it('does not carry another repo forward through a failure', () => { - const previous = { repoId: 'repo-1', names: ['nautilus'] } - expect(retiredNamesAfterRefresh(previous, 'repo-2', null)).toEqual({ + expect(retiredNamesAfterRefresh(loadOf('repo-1', ['nautilus'], 2), 'repo-2', null)).toEqual({ repoId: 'repo-2', - names: NO_RETIRED_NAMES + registry: EMPTY_RETIRED_NAME_REGISTRY }) }) it('answers empty when the first fetch for a repo fails', () => { - expect(retiredNamesAfterRefresh(null, 'repo-1', null).names).toEqual([]) + expect(retiredNamesAfterRefresh(null, 'repo-1', null).registry).toEqual( + EMPTY_RETIRED_NAME_REGISTRY + ) }) }) -describe('selectRetiredNames', () => { +describe('selectRetiredNameRegistry', () => { it('serves a load only to the repo it answered for', () => { - const loaded = { repoId: 'repo-1', names: ['nautilus'] } - expect(selectRetiredNames(loaded, 'repo-1')).toEqual(['nautilus']) - expect(selectRetiredNames(loaded, 'repo-2')).toEqual([]) - expect(selectRetiredNames(loaded, null)).toEqual([]) - expect(selectRetiredNames(null, 'repo-1')).toEqual([]) + const loaded = loadOf('repo-1', ['nautilus'], 1) + expect(selectRetiredNameRegistry(loaded, 'repo-1')).toEqual(loaded.registry) + expect(selectRetiredNameRegistry(loaded, 'repo-2')).toEqual(EMPTY_RETIRED_NAME_REGISTRY) + expect(selectRetiredNameRegistry(loaded, null)).toEqual(EMPTY_RETIRED_NAME_REGISTRY) + expect(selectRetiredNameRegistry(null, 'repo-1')).toEqual(EMPTY_RETIRED_NAME_REGISTRY) }) - it('returns the stored array itself so downstream memos do not rerun', () => { - const names = ['nautilus'] - expect(selectRetiredNames({ repoId: 'repo-1', names }, 'repo-1')).toBe(names) + it('returns the stored registry itself so downstream memos do not rerun', () => { + const loaded = loadOf('repo-1', ['nautilus']) + expect(selectRetiredNameRegistry(loaded, 'repo-1')).toBe(loaded.registry) }) }) diff --git a/src/shared/worktree/retired-name-cache.ts b/src/shared/worktree/retired-name-cache.ts index aafdc65d2687..3c68960dd481 100644 --- a/src/shared/worktree/retired-name-cache.ts +++ b/src/shared/worktree/retired-name-cache.ts @@ -1,3 +1,9 @@ +import { + clampExhaustedTiers, + EMPTY_RETIRED_NAME_REGISTRY, + type RetiredNameRegistry +} from './retired-name-registry' + /** Client-side caching rules for retired workspace names, shared by the desktop hook (IPC) and the * mobile hook (RPC). The transports differ, but what a refresh and a failure *mean* must not: the * two hooks drifted, and mobile's copy blanked the list on any error — which un-retires names and @@ -5,25 +11,40 @@ * * Pure by construction: `src/shared` is on the main process's import graph, so no React here. */ -export const NO_RETIRED_NAMES: readonly string[] = [] - /** The last answer, tagged with the repo it answered for. */ export type RetiredNamesLoad = { repoId: string - names: readonly string[] + registry: RetiredNameRegistry } -/** Reads one repo's names out of a `worktree.listRetiredNames` result. A host predating the method - * omits the field, and any host can answer with a malformed row that would throw when normalized. */ -export function readRetiredNamesForRepo(result: unknown, repoId: string): string[] { - const names = (result as { retiredNamesByRepo?: Record } | null | undefined) - ?.retiredNamesByRepo?.[repoId] - return Array.isArray(names) - ? names.filter((name): name is string => typeof name === 'string') - : [] +/** Reads one repo's registry out of a `worktree.listRetiredNames` result. A host predating the + * method omits the field, and any host can answer with a malformed row that would throw when + * normalized. + * + * `retiredNameTiersByRepo` is the compaction watermark and arrived after the names field. A host + * that omits it has simply never compacted; a client that ignored it would under-retire, which is + * the direction that degrades to the pre-retirement behavior rather than breaking. */ +export function readRetiredNameRegistryForRepo( + result: unknown, + repoId: string +): RetiredNameRegistry { + const row = result as + | { + retiredNamesByRepo?: Record + retiredNameTiersByRepo?: Record + } + | null + | undefined + const names = row?.retiredNamesByRepo?.[repoId] + return { + exhaustedTiers: clampExhaustedTiers(row?.retiredNameTiersByRepo?.[repoId]), + names: Array.isArray(names) + ? names.filter((name): name is string => typeof name === 'string') + : [] + } } -/** Next state once a refresh settles; `names === null` means it failed. Belongs in a `setState` +/** Next state once a refresh settles; `registry === null` means it failed. Belongs in a `setState` * updater rather than being applied at call time, so overlapping refreshes fold onto whatever * actually landed last. * @@ -33,22 +54,23 @@ export function readRetiredNamesForRepo(result: unknown, repoId: string): string export function retiredNamesAfterRefresh( previous: RetiredNamesLoad | null, repoId: string, - names: readonly string[] | null + registry: RetiredNameRegistry | null ): RetiredNamesLoad { return { repoId, - names: names ?? (previous?.repoId === repoId ? previous.names : NO_RETIRED_NAMES) + registry: + registry ?? (previous?.repoId === repoId ? previous.registry : EMPTY_RETIRED_NAME_REGISTRY) } } /** Stale-while-revalidate view: a load answers only for its own repo, so names never leak across a * repo switch, and a refetch in flight keeps serving the previous answer rather than emptying. * - * Returns the stored array itself, not a copy, so it stays referentially stable and the suggestion - * memo downstream does not rerun on every refetch. */ -export function selectRetiredNames( + * Returns the stored registry itself, not a copy, so it stays referentially stable and the + * suggestion memo downstream does not rerun on every refetch. */ +export function selectRetiredNameRegistry( loaded: RetiredNamesLoad | null, repoId: string | null | undefined -): readonly string[] { - return loaded && loaded.repoId === repoId ? loaded.names : NO_RETIRED_NAMES +): RetiredNameRegistry { + return loaded && loaded.repoId === repoId ? loaded.registry : EMPTY_RETIRED_NAME_REGISTRY } diff --git a/src/shared/worktree/retired-name-registry.test.ts b/src/shared/worktree/retired-name-registry.test.ts new file mode 100644 index 000000000000..3d42abb6e9e1 --- /dev/null +++ b/src/shared/worktree/retired-name-registry.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, it } from 'vitest' +import { MARINE_CREATURES } from '../marine-creatures' +import { selectSuggestedCreatureName } from '../worktree-name-suggestion' +import { + addRetiredNames, + clampExhaustedTiers, + compactRetiredNames, + createRetiredNameLookup, + creatureNameTier, + EMPTY_RETIRED_NAME_REGISTRY, + mergeRetiredNameRegistries +} from './retired-name-registry' + +const POOL = MARINE_CREATURES.map((name) => name.toLowerCase()) +const tier = (n: number) => POOL.map((name) => (n === 1 ? name : `${name}-${n}`)) + +describe('creatureNameTier', () => { + it.each([ + ['nautilus', 1], + ['Nautilus', 1], + [' nautilus ', 1], + ['nautilus-2', 2], + ['nautilus-10', 10], + ['nautilus-999999', 999999] + ])('reads %s as tier %s', (name, expected) => { + expect(creatureNameTier(name)).toBe(expected) + }) + + it.each([ + // A user-typed name must never be covered by a watermark, or a spent tier would silently + // retire names the pool has no claim on. + ['fix-login-2'], + ['fix-login'], + // The suggester never emits these, so no tier can ever complete for them. + ['nautilus-2-3'], + ['nautilus-1'], + ['nautilus-0'], + ['nautilus-02'], + ['nautilus-1000000'] + ])('leaves %s outside every tier', (name) => { + expect(creatureNameTier(name)).toBeNull() + }) +}) + +describe('compactRetiredNames', () => { + it('does not move the watermark while one name of the tier is missing', () => { + const registry = compactRetiredNames({ exhaustedTiers: 0, names: POOL.slice(0, -1) }) + expect(registry.exhaustedTiers).toBe(0) + expect(registry.names.length).toBe(POOL.length - 1) + }) + + it('folds a completed tier into the watermark and drops its names', () => { + expect(compactRetiredNames({ exhaustedTiers: 0, names: tier(1) })).toEqual({ + exhaustedTiers: 1, + names: [] + }) + }) + + it('rolls through consecutive tiers that completed out of order', () => { + const registry = compactRetiredNames({ + exhaustedTiers: 0, + names: [...tier(3), ...tier(2), ...tier(1)] + }) + expect(registry).toEqual({ exhaustedTiers: 3, names: [] }) + }) + + it('stops at the first incomplete tier and keeps everything above it', () => { + const registry = compactRetiredNames({ + exhaustedTiers: 0, + names: [...tier(1), 'nautilus-3', 'nautilus-2-3'] + }) + expect(registry.exhaustedTiers).toBe(1) + expect([...registry.names].sort()).toEqual(['nautilus-2-3', 'nautilus-3']) + }) + + it('drops names a higher watermark already covers', () => { + expect( + compactRetiredNames({ exhaustedTiers: 2, names: ['nautilus', 'orca-2', 'orca-3'] }) + ).toEqual({ exhaustedTiers: 2, names: ['orca-3'] }) + }) + + it.each([ + ['a negative watermark', -1], + ['a fractional watermark', 1.5], + ['a non-number watermark', 'many'], + ['no watermark', undefined] + ])('clamps %s to none rather than trusting it', (_label, value) => { + expect(clampExhaustedTiers(value)).toBe(0) + expect(compactRetiredNames({ exhaustedTiers: value as number, names: [] }).exhaustedTiers).toBe( + 0 + ) + }) +}) + +describe('createRetiredNameLookup', () => { + it('reports a compacted tier as retired without listing its names', () => { + const lookup = createRetiredNameLookup({ exhaustedTiers: 2, names: [] }) + expect(POOL.every((name) => lookup(name))).toBe(true) + expect(POOL.every((name) => lookup(`${name}-2`))).toBe(true) + expect(lookup('nautilus-3')).toBe(false) + }) + + it('does not retire a user-typed name that merely ends in a spent tier number', () => { + expect(createRetiredNameLookup({ exhaustedTiers: 5, names: [] })('fix-login-2')).toBe(false) + }) + + it('still answers for explicit names above the watermark', () => { + const lookup = createRetiredNameLookup({ exhaustedTiers: 1, names: ['nautilus-3'] }) + expect(lookup('NAUTILUS-3')).toBe(true) + expect(lookup('orca-3')).toBe(false) + }) +}) + +describe('addRetiredNames', () => { + it('reports no change when every name is already covered by the watermark', () => { + expect(addRetiredNames({ exhaustedTiers: 1, names: [] }, ['nautilus'])).toBeNull() + }) + + it('compacts as soon as the added name completes the tier', () => { + const before = { exhaustedTiers: 0, names: POOL.slice(0, -1) } + expect(addRetiredNames(before, [POOL.at(-1) as string])).toEqual({ + exhaustedTiers: 1, + names: [] + }) + }) + + it('keeps an out-of-order higher-tier name through a lower tier compacting', () => { + const before = { exhaustedTiers: 0, names: [...POOL.slice(0, -1), 'nautilus-2'] } + expect(addRetiredNames(before, [POOL.at(-1) as string])).toEqual({ + exhaustedTiers: 1, + names: ['nautilus-2'] + }) + }) +}) + +describe('mergeRetiredNameRegistries', () => { + it('takes the higher watermark and drops what it covers', () => { + expect( + mergeRetiredNameRegistries( + { exhaustedTiers: 2, names: ['nautilus-3'] }, + { exhaustedTiers: 0, names: ['nautilus', 'orca-2', 'seahorse-4'] } + ) + ).toEqual({ exhaustedTiers: 2, names: ['nautilus-3', 'seahorse-4'] }) + }) + + it('completes a tier out of two partial peers', () => { + const half = Math.floor(POOL.length / 2) + expect( + mergeRetiredNameRegistries( + { exhaustedTiers: 0, names: POOL.slice(0, half) }, + { exhaustedTiers: 0, names: POOL.slice(half) } + ) + ).toEqual({ exhaustedTiers: 1, names: [] }) + }) +}) + +describe('end-to-end retirement guarantee', () => { + const pickFirst = () => 0 + + it('never suggests a name that has been retired, compacted or not', () => { + let registry = EMPTY_RETIRED_NAME_REGISTRY + const issued: string[] = [] + // Two full tiers plus one, so the run crosses compaction twice and lands above the watermark. + for (let index = 0; index < POOL.length * 2 + 1; index += 1) { + const name = selectSuggestedCreatureName(registry.names, pickFirst, registry.exhaustedTiers) + expect(issued).not.toContain(name) + issued.push(name) + registry = addRetiredNames(registry, [name]) ?? registry + } + + expect(new Set(issued).size).toBe(issued.length) + expect(registry).toEqual({ exhaustedTiers: 2, names: [`${POOL[0]}-3`] }) + const isRetired = createRetiredNameLookup(registry) + expect(issued.every((name) => isRetired(name))).toBe(true) + }) +}) diff --git a/src/shared/worktree/retired-name-registry.ts b/src/shared/worktree/retired-name-registry.ts new file mode 100644 index 000000000000..0fd75ce5a766 --- /dev/null +++ b/src/shared/worktree/retired-name-registry.ts @@ -0,0 +1,133 @@ +import { MARINE_CREATURES } from '../marine-creatures' + +/** Retirement is permanent — a spent name's directory may still hold agent conversation state + * keyed by that path — so the registry can never evict. It compacts instead. + * + * Names come from a fixed pool and the suggester only reaches tier N+1 once every tier-N name is + * taken, so a completed tier is exactly a set of 552 entries that no longer need to be listed + * individually: `exhaustedTiers` covers every tier at or below it, `names` holds only what sits + * above it. That bounds a repo at roughly one pool's worth of entries forever, with no eviction + * and nothing un-retired. */ +export type RetiredNameRegistry = { + exhaustedTiers: number + names: readonly string[] +} + +export const EMPTY_RETIRED_NAME_REGISTRY: RetiredNameRegistry = { exhaustedTiers: 0, names: [] } + +export const CREATURE_POOL_NAMES: ReadonlySet = new Set( + MARINE_CREATURES.map((name) => name.toLowerCase()) +) + +// Matches the widest tier `creatureNameTier` will parse: a watermark past it could never be +// reached by a name, so it would only silence lookups. +const MAX_EXHAUSTED_TIERS = 999_999 + +/** Tier 1 is the bare pool name; tier N is `name-N`. */ +export function creatureNameAtTier(poolName: string, tier: number): string { + return tier === 1 ? poolName : `${poolName}-${tier}` +} + +/** Null for anything the suggester never emits — a non-pool base, or a repeat-suffixed collision + * variant like `nautilus-2-3` — so no watermark can ever cover those. Load-bearing for user-typed + * names: `fix-login-2` must not read as retired just because tier 2 is spent. */ +export function creatureNameTier(name: string): number | null { + const normalized = name.trim().toLowerCase() + if (CREATURE_POOL_NAMES.has(normalized)) { + return 1 + } + const match = /^(.+)-([1-9]\d{0,5})$/.exec(normalized) + if (!match || !CREATURE_POOL_NAMES.has(match[1])) { + return null + } + // `nautilus-1` is not the tier-1 name — the bare name is — so it stays explicit. + const tier = Number(match[2]) + return tier >= 2 ? tier : null +} + +export function clampExhaustedTiers(value: unknown): number { + return typeof value === 'number' && Number.isInteger(value) && value > 0 + ? Math.min(value, MAX_EXHAUSTED_TIERS) + : 0 +} + +/** Membership without reconstructing a compacted tier: at or below the watermark answers with no + * lookup at all. Built once per create attempt because the create loop probes up to 100 names. */ +export function createRetiredNameLookup(registry: RetiredNameRegistry): (name: string) => boolean { + const explicit = new Set(registry.names) + const exhaustedTiers = clampExhaustedTiers(registry.exhaustedTiers) + return (name) => { + const normalized = name.trim().toLowerCase() + if (explicit.has(normalized)) { + return true + } + const tier = creatureNameTier(normalized) + return tier !== null && tier <= exhaustedTiers + } +} + +function tierIsComplete(names: ReadonlySet, tier: number): boolean { + for (const poolName of CREATURE_POOL_NAMES) { + if (!names.has(creatureNameAtTier(poolName, tier))) { + return false + } + } + return true +} + +/** Folds every completed tier into the watermark and drops the names it now covers. + * + * Loops rather than checking one tier: tiers complete out of order, because a create-time + * collision can spend `nautilus-2` while tier 1 is still open. Those higher-tier names simply + * wait in the explicit set until their own tier completes. */ +export function compactRetiredNames(registry: RetiredNameRegistry): RetiredNameRegistry { + let exhaustedTiers = clampExhaustedTiers(registry.exhaustedTiers) + const names = new Set(registry.names) + while (exhaustedTiers < MAX_EXHAUSTED_TIERS && tierIsComplete(names, exhaustedTiers + 1)) { + exhaustedTiers += 1 + } + for (const name of names) { + const tier = creatureNameTier(name) + if (tier !== null && tier <= exhaustedTiers) { + names.delete(name) + } + } + return { exhaustedTiers, names: [...names] } +} + +/** Returns null when nothing changed, so callers can skip the write. Names must already have + * passed the caller's retirement gate — this only does set math. */ +export function addRetiredNames( + registry: RetiredNameRegistry, + incoming: Iterable +): RetiredNameRegistry | null { + const isRetired = createRetiredNameLookup(registry) + const added: string[] = [] + for (const name of incoming) { + if (!isRetired(name)) { + added.push(name) + } + } + return added.length === 0 + ? null + : compactRetiredNames({ + exhaustedTiers: registry.exhaustedTiers, + names: [...registry.names, ...added] + }) +} + +/** Union of two registries. The higher watermark wins and absorbs the other's names, so peers at + * different compaction points do not re-expand each other's spent tiers. */ +export function mergeRetiredNameRegistries( + base: RetiredNameRegistry, + incoming: RetiredNameRegistry +): RetiredNameRegistry { + return compactRetiredNames({ + exhaustedTiers: Math.max(base.exhaustedTiers, incoming.exhaustedTiers), + names: [...base.names, ...incoming.names] + }) +} + +export function isEmptyRetiredNameRegistry(registry: RetiredNameRegistry): boolean { + return registry.exhaustedTiers === 0 && registry.names.length === 0 +} From 440419bf461a454f098a299cf3565a5ae639ea8d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 14 Aug 2026 18:09:14 -0700 Subject: [PATCH 20/20] fix(worktree): preserve generated name retirement across failures --- mobile/src/tasks/blank-workspace-create.ts | 1 + .../src/tasks/worktree-create-retry.test.ts | 19 ++ mobile/src/tasks/worktree-create-retry.ts | 6 +- src/main/git/remove-worktree.test.ts | 42 ++++ src/main/git/worktree.ts | 9 +- src/main/ipc/worktree-remote.ts | 224 +++++++++++------- src/main/ipc/worktrees.test.ts | 22 +- src/main/ipc/worktrees.ts | 11 +- .../profile-project-retired-name-transfer.ts | 29 +++ .../profile-project-state-file.ts | 3 + .../profile-project-transfer-payload.ts | 101 ++------ .../profile-project-transfer-worktree-ids.ts | 87 +++++++ .../profile-project-transfer.test.ts | 16 ++ ...rsistence-worktree-name-retirement.test.ts | 26 ++ src/main/persistence.ts | 38 ++- src/main/runtime/orca-runtime.test.ts | 76 +++++- src/main/runtime/orca-runtime.ts | 163 +++++++------ src/main/worktree-create-candidates.test.ts | 22 ++ src/main/worktree-create-candidates.ts | 15 ++ src/main/worktree-name-retirement.test.ts | 51 ++-- src/main/worktree-name-retirement.ts | 119 +++++++--- .../src/store/slices/worktrees.test.ts | 27 +++ src/renderer/src/store/slices/worktrees.ts | 6 +- src/shared/constants.ts | 1 + .../worktree-create-retry-policy.test.ts | 7 + .../worktree-create-retry-policy.ts | 49 ++++ src/shared/persisted-state-types.ts | 7 +- 27 files changed, 852 insertions(+), 325 deletions(-) create mode 100644 src/main/orca-profiles/profile-project-retired-name-transfer.ts create mode 100644 src/main/orca-profiles/profile-project-transfer-worktree-ids.ts create mode 100644 src/main/worktree-create-candidates.test.ts diff --git a/mobile/src/tasks/blank-workspace-create.ts b/mobile/src/tasks/blank-workspace-create.ts index a84ac55a3a1e..d81d75d5a694 100644 --- a/mobile/src/tasks/blank-workspace-create.ts +++ b/mobile/src/tasks/blank-workspace-create.ts @@ -24,6 +24,7 @@ export async function createBlankWorkspace(args: { return createWorktreeWithNameRetry({ client: args.client, baseName: args.baseName, + nameWasGenerated: args.nameWasGenerated, supportsIdempotentCutoverRetry: args.supportsIdempotentCutoverRetry, buildParams: (name) => { const params: Record = { diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts index a03be2ad24b8..35fa050b6204 100644 --- a/mobile/src/tasks/worktree-create-retry.test.ts +++ b/mobile/src/tasks/worktree-create-retry.test.ts @@ -154,6 +154,25 @@ describe('createWorktreeWithNameRetry', () => { expect(attempts[1]!.params.name).toBe('topic-2') }) + it('advances generated retries without nesting suffixes', async () => { + const attempts: Attempt[] = [] + const client = scriptedClient( + [{ errorMessage: 'already exists locally' }, { id: 'wt-generated' }], + attempts + ) + + const result = await createWorktreeWithNameRetry({ + client, + baseName: 'nautilus-2', + nameWasGenerated: true, + buildParams: (name) => ({ repo: 'id:r', name, nameWasGenerated: true }), + supportsIdempotentCutoverRetry: false + }) + + expect(result).toEqual({ worktreeId: 'wt-generated', name: 'nautilus-3' }) + expect(attempts.map((attempt) => attempt.params.name)).toEqual(['nautilus-2', 'nautilus-3']) + }) + it('does not replay an ambiguous cutover when the host lacks idempotency support', async () => { const attempts: Attempt[] = [] const client = scriptedClient([{ throws: new LogicalClientCutoverError() }], attempts) diff --git a/mobile/src/tasks/worktree-create-retry.ts b/mobile/src/tasks/worktree-create-retry.ts index ccc46f2057b0..6cee659b89fd 100644 --- a/mobile/src/tasks/worktree-create-retry.ts +++ b/mobile/src/tasks/worktree-create-retry.ts @@ -4,6 +4,7 @@ import { isLogicalClientCutoverError } from '../transport/stable-logical-rpc-cli import { CLIENT_WORKTREE_CREATE_MAX_ATTEMPTS, getClientWorktreeCreateCandidate, + getGeneratedWorktreeCreateRetryCandidate, isRetryableWorktreeCreateConflict } from '../../../src/shared/new-workspace/worktree-create-retry-policy' import { WORKTREE_CREATE_TIMEOUT_MS } from './workspace-create-timeout' @@ -26,6 +27,7 @@ const WORKTREE_CREATE_CUTOVER_MAX_RETRIES = 5 export type CreateWorktreeWithNameRetryArgs = { client: RpcClient baseName: string + nameWasGenerated?: boolean buildParams: (name: string) => Record supportsIdempotentCutoverRetry: boolean | Promise maxAttempts?: number @@ -49,7 +51,9 @@ export async function createWorktreeWithNameRetry( const mintMutationId = args.mintMutationId ?? defaultWorktreeCreateMutationId let lastError: string | null = null for (let attempt = 0; attempt < maxAttempts; attempt += 1) { - const candidateName = getClientWorktreeCreateCandidate(baseName, attempt) + const candidateName = args.nameWasGenerated + ? getGeneratedWorktreeCreateRetryCandidate(baseName, attempt) + : getClientWorktreeCreateCandidate(baseName, attempt) const candidateParams = buildParams(candidateName) // Why: older hosts strip unknown fields, so only stamp and replay when the // host advertises idempotency. One key per candidate makes cutover retries diff --git a/src/main/git/remove-worktree.test.ts b/src/main/git/remove-worktree.test.ts index 15e115221ea8..8ffac39e5a94 100644 --- a/src/main/git/remove-worktree.test.ts +++ b/src/main/git/remove-worktree.test.ts @@ -1600,4 +1600,46 @@ branch refs/heads/main 'git branch -D -- feature/test' ) }) + + it('marks cleanup failed when sparse rollback cannot clear metadata or remove the worktree', async () => { + mockGitCommands({ + 'git config --get push.autoSetupRemote': { + error: Object.assign(new Error('key unset'), { code: 1 }) + }, + 'git sparse-checkout set -- packages/web': { + error: new Error('sparse setup failed') + }, + 'git config --local --unset-all branch.feature/test.base': { + error: new Error('metadata cleanup failed') + }, + 'git worktree list --porcelain': { + stdout: `worktree /repo +HEAD abc123 +branch refs/heads/main + +worktree /repo-feature +HEAD def456 +branch refs/heads/feature/test +` + }, + 'git worktree remove --force /repo-feature': { + error: new Error('worktree cleanup failed') + } + }) + + const error = await addSparseWorktree('/repo', '/repo-feature', 'feature/test', [ + 'packages/web' + ]).catch((caught: unknown) => caught) + + expect(error).toMatchObject({ + cleanupFailed: true, + message: expect.stringContaining('cleanup also failed') + }) + const calls = getGitCalls() + expectGitCallOrder( + calls, + 'git config --local --unset-all branch.feature/test.base', + 'git worktree remove --force /repo-feature' + ) + }) }) diff --git a/src/main/git/worktree.ts b/src/main/git/worktree.ts index 005be57351fc..b498ebefc6d2 100644 --- a/src/main/git/worktree.ts +++ b/src/main/git/worktree.ts @@ -1067,7 +1067,14 @@ export async function addSparseWorktree( error instanceof Error ? (error as SparseWorktreeCreateError) : new Error(String(error)) if (created) { if (!options.checkoutExistingBranch) { - await unsetWorktreeCreationBase(worktreePath, branch, options) + try { + await unsetWorktreeCreationBase(worktreePath, branch, options) + } catch (cleanupError) { + console.warn( + `addSparseWorktree: failed to clear creation base for ${worktreePath}`, + cleanupError + ) + } } try { await removeWorktree(repoPath, worktreePath, true, { diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index dd0f2e6d4d49..0896ae0a0da8 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -136,10 +136,16 @@ import { } from '../project-runtime-git-options' import { getBranchNameOverrideCandidate, + getGeneratedWorktreeCreateCandidate, getWorktreeCreateCandidate, + isGeneratedWorktreeCreateName, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' -import { getRetiredNameRegistryForRepo } from '../worktree-name-retirement' +import { + failedWorktreeCreationNeedsRetirement, + getRetiredNameRegistryForRepo, + retireGeneratedWorktreeName +} from '../worktree-name-retirement' import { createRetiredNameLookup } from '../../shared/worktree/retired-name-registry' const SSH_WORKTREE_CREATE_FETCH_FRESHNESS_MS = 30_000 @@ -1556,20 +1562,30 @@ export async function createRemoteWorktree( let selectedExistingLocalBranchName: string | null = null let lastBranchConflictKind: 'local' | 'remote' | null = null let remotePathResolved = false - const isRetiredName = args.nameWasGenerated - ? createRetiredNameLookup( - getRetiredNameRegistryForRepo(store, repo, store.getRepos(), settings) - ) + const shouldRetireGeneratedName = + args.nameWasGenerated === true && isGeneratedWorktreeCreateName(sanitizedName) + const retiredNameRegistry = shouldRetireGeneratedName + ? await getRetiredNameRegistryForRepo(store, repo, store.getRepos(), settings) : null + const isRetiredName = retiredNameRegistry ? createRetiredNameLookup(retiredNameRegistry) : null // Why: duplicate PR/MR checkouts still need a workspace; suffix branch/path while preserving review metadata and push target. - for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { - effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) - effectiveRequestedName = args.name.trim() - ? getWorktreeCreateCandidate(args.name, suffix) - : effectiveSanitizedName + for (let suffix = 1, attempts = 0; attempts < WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { + effectiveSanitizedName = shouldRetireGeneratedName + ? getGeneratedWorktreeCreateCandidate( + sanitizedName, + suffix, + retiredNameRegistry?.exhaustedTiers + ) + : getWorktreeCreateCandidate(sanitizedName, suffix) + effectiveRequestedName = shouldRetireGeneratedName + ? effectiveSanitizedName + : args.name.trim() + ? getWorktreeCreateCandidate(args.name, suffix) + : effectiveSanitizedName if (isRetiredName?.(effectiveSanitizedName)) { continue } + attempts += 1 branchName = await resolveCreateBranchNameSsh( provider, repo.path, @@ -1749,20 +1765,39 @@ export async function createRemoteWorktree( await provider.exec(['sparse-checkout', 'set', '--', ...sparseDirectories], remotePath) await provider.exec(['checkout', branchName], remotePath) } catch (err) { + let rollbackSucceeded = false if (!checkoutExistingBranch) { - await unsetRemoteWorktreeCreationBase(provider, remotePath, branchName) + try { + await unsetRemoteWorktreeCreationBase(provider, remotePath, branchName) + } catch (cleanupError) { + console.warn( + '[worktree-create] Failed to clear remote sparse creation base:', + cleanupError + ) + } } - await provider - .removeWorktree(remotePath, true, { + try { + await provider.removeWorktree(remotePath, true, { deleteBranch: !checkoutExistingBranch, // Why: sparse setup failed before any work happened, so rollback removes the just-created remote branch. forceBranchDelete: !checkoutExistingBranch }) - .catch(() => undefined) + rollbackSucceeded = true + } catch (rollbackError) { + console.warn('[worktree-create] Failed to roll back remote sparse worktree:', rollbackError) + } + if (!rollbackSucceeded && shouldRetireGeneratedName) { + await retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + } throw err } } + // Why: fallible metadata work after creation must not leave a real workspace name reusable. + if (shouldRetireGeneratedName) { + await retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + } + // Re-list to get the created worktree info const gitWorktrees = await timing.time('list_created_worktree', async () => provider.listWorktrees(repo.path) @@ -1775,10 +1810,6 @@ export async function createRemoteWorktree( } const worktreeId = `${repo.id}::${created.path}` - // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. - if (args.nameWasGenerated) { - store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) - } const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch @@ -2107,20 +2138,30 @@ export async function createLocalWorktree( let lastBranchConflictKind: 'local' | 'remote' | null = null let lastExistingPR: Awaited> | null = null let lastExistingReviewNumber: number | null = null - const isRetiredName = args.nameWasGenerated - ? createRetiredNameLookup( - getRetiredNameRegistryForRepo(store, repo, store.getRepos(), settings) - ) + const shouldRetireGeneratedName = + args.nameWasGenerated === true && isGeneratedWorktreeCreateName(sanitizedName) + const retiredNameRegistry = shouldRetireGeneratedName + ? await getRetiredNameRegistryForRepo(store, repo, store.getRepos(), settings) : null + const isRetiredName = retiredNameRegistry ? createRetiredNameLookup(retiredNameRegistry) : null // Why: a create-from-review branch override may already exist locally; suffix both branch and path instead of blocking the user. - for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { - effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) - effectiveRequestedName = requestedName.trim() - ? getWorktreeCreateCandidate(requestedName, suffix) - : effectiveSanitizedName + for (let suffix = 1, attempts = 0; attempts < WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { + effectiveSanitizedName = shouldRetireGeneratedName + ? getGeneratedWorktreeCreateCandidate( + sanitizedName, + suffix, + retiredNameRegistry?.exhaustedTiers + ) + : getWorktreeCreateCandidate(sanitizedName, suffix) + effectiveRequestedName = shouldRetireGeneratedName + ? effectiveSanitizedName + : requestedName.trim() + ? getWorktreeCreateCandidate(requestedName, suffix) + : effectiveSanitizedName if (isRetiredName?.(effectiveSanitizedName)) { continue } + attempts += 1 lastExistingReviewNumber = null branchName = await resolveCreateBranchName( @@ -2292,93 +2333,106 @@ export async function createLocalWorktree( ...remoteTrackingBaseOption, ...(suggestLocalBaseRefUpdate ? { suggestLocalBaseRefUpdate } : {}) } - const addResult: AddWorktreeResult = - (await timing.time('git_worktree_add', async () => { - if (sparseDirectories.length > 0) { + let addResult: AddWorktreeResult + try { + addResult = + (await timing.time('git_worktree_add', async () => { + if (sparseDirectories.length > 0) { + if (checkoutExistingBranch) { + return addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + addProjectGitOptions(existingBranchOption) + ) + } + if (suggestLocalBaseRefUpdate) { + return addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) + ) + } + const sparseOptions = addProjectGitOptions(remoteTrackingBaseOption) + return sparseOptions + ? addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + sparseOptions + ) + : addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + ) + } + if (checkoutExistingBranch) { - return addSparseWorktree( + return addWorktree( repo.path, worktreePath, branchName, - sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, + false, addProjectGitOptions(existingBranchOption) ) } if (suggestLocalBaseRefUpdate) { - return addSparseWorktree( + return addWorktree( repo.path, worktreePath, branchName, - sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, + false, addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) ) } - const sparseOptions = addProjectGitOptions(remoteTrackingBaseOption) - return sparseOptions - ? addSparseWorktree( + const worktreeOptions = addProjectGitOptions(remoteTrackingBaseOption) + return worktreeOptions + ? addWorktree( repo.path, worktreePath, branchName, - sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - sparseOptions + false, + worktreeOptions ) - : addSparseWorktree( + : addWorktree( repo.path, worktreePath, branchName, - sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate ) - } + })) ?? {} + } catch (error) { + if (shouldRetireGeneratedName && failedWorktreeCreationNeedsRetirement(error)) { + await retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + } + throw error + } - if (checkoutExistingBranch) { - return addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate, - false, - addProjectGitOptions(existingBranchOption) - ) - } - if (suggestLocalBaseRefUpdate) { - return addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate, - false, - addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) - ) - } - const worktreeOptions = addProjectGitOptions(remoteTrackingBaseOption) - return worktreeOptions - ? addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate, - false, - worktreeOptions - ) - : addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - ) - })) ?? {} + // Why: fallible metadata work after creation must not leave a real workspace name reusable. + if (shouldRetireGeneratedName) { + await retireGeneratedWorktreeName(store, repo, settings, effectiveSanitizedName) + } let configuredPushTarget: GitPushTarget | undefined if (preparedPushTarget) { @@ -2404,10 +2458,6 @@ export async function createLocalWorktree( } const worktreeId = `${repo.id}::${created.path}` - // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. - if (args.nameWasGenerated) { - store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) - } const now = Date.now() // Why: PR/MR worktrees start from a head ref/SHA but Source Control must compare against the review target branch. const metadataBaseRef = args.compareBaseRef ?? remoteTrackingBase?.ref ?? baseBranch diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 2b500118752b..b7608eef09a7 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -5750,7 +5750,7 @@ describe('registerWorktreeHandlers', () => { ) }) - it('unsets SSH branch base config before removing a sparse worktree after setup failure', async () => { + it('attempts SSH base cleanup and still removes a sparse worktree when that cleanup fails', async () => { const repo = { id: 'repo-ssh', path: '/remote/repo', @@ -5769,6 +5769,9 @@ describe('registerWorktreeHandlers', () => { if (args[0] === 'sparse-checkout' && args[1] === 'init') { throw setupError } + if (args[0] === 'config' && args[2] === '--unset-all') { + throw new Error('metadata cleanup failed') + } return { stdout: '', stderr: '' } }), fetchRemoteTrackingRef: vi.fn().mockResolvedValue(undefined), @@ -8284,6 +8287,23 @@ describe('registerWorktreeHandlers', () => { }) }) + it('retires a generated sparse name when creation rollback also fails', async () => { + addSparseWorktreeMock.mockRejectedValueOnce( + Object.assign(new Error('sparse setup failed'), { cleanupFailed: true }) + ) + + await expect( + handlers['worktrees:create'](null, { + repoId: 'repo-1', + name: 'nautilus', + nameWasGenerated: true, + sparseCheckout: { directories: ['packages/web'] } + }) + ).rejects.toThrow('sparse setup failed') + + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', 'nautilus') + }) + it('clears sparse preset attribution when the preset id does not belong to the repo', async () => { listWorktreesMock.mockResolvedValue([ { diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 34115ce8d80e..113d68605729 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -121,10 +121,7 @@ import { isOrphanCompatiblePreflightError, isOrphanedWorktreeError } from './worktree-logic' -import { - ensureRetiredWorktreeNamesBackfilled, - getRetiredNameRegistryForRepo -} from '../worktree-name-retirement' +import { getRetiredNameRegistryForRepo } from '../worktree-name-retirement' import { EMPTY_RETIRED_NAME_REGISTRY } from '../../shared/worktree/retired-name-registry' import { dedupeWorktreesByPath } from './worktree-path-comparison' import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' @@ -1944,12 +1941,6 @@ export function registerWorktreeHandlers( if (!repo) { return EMPTY_RETIRED_NAME_REGISTRY } - try { - await ensureRetiredWorktreeNamesBackfilled(store, repo, store.getSettings()) - } catch (err) { - // Best effort: without the seed we only under-retire, which is the pre-existing behavior. - console.warn(`[worktrees] retirement backfill failed for repo ${args.repoId}:`, err) - } return getRetiredNameRegistryForRepo(store, repo, store.getRepos(), store.getSettings()) }) diff --git a/src/main/orca-profiles/profile-project-retired-name-transfer.ts b/src/main/orca-profiles/profile-project-retired-name-transfer.ts new file mode 100644 index 000000000000..7ecb952ce749 --- /dev/null +++ b/src/main/orca-profiles/profile-project-retired-name-transfer.ts @@ -0,0 +1,29 @@ +import type { Repo } from '../../shared/repo-types' +import { + mergeRetiredNameRegistries, + type RetiredNameRegistry +} from '../../shared/worktree/retired-name-registry' +import { getRemoteRetirementNamespaceKey } from '../worktree-name-retirement' +import type { TransferProfileState } from './profile-project-state-file' + +export function extractRetiredNameRegistriesByNamespace( + sourceState: TransferProfileState, + sourceRepo: Repo +): Record { + const namespaceKey = getRemoteRetirementNamespaceKey(sourceRepo, sourceState.settings) + const registry = namespaceKey + ? sourceState.retiredWorktreeNamesByNamespace?.[namespaceKey] + : undefined + return namespaceKey && registry ? { [namespaceKey]: registry } : {} +} + +export function mergeRetiredNameRegistryMaps( + base: Record, + incoming: Record +): Record { + const merged = { ...base } + for (const [key, registry] of Object.entries(incoming)) { + merged[key] = merged[key] ? mergeRetiredNameRegistries(merged[key], registry) : registry + } + return merged +} diff --git a/src/main/orca-profiles/profile-project-state-file.ts b/src/main/orca-profiles/profile-project-state-file.ts index e72babef2f40..5c623f19bad0 100644 --- a/src/main/orca-profiles/profile-project-state-file.ts +++ b/src/main/orca-profiles/profile-project-state-file.ts @@ -47,6 +47,9 @@ export function readProfileState(profileId: string, userDataPath: string): Trans retiredWorktreeNamesByRepo: recordOrEmpty( parsed.retiredWorktreeNamesByRepo ), + retiredWorktreeNamesByNamespace: recordOrEmpty( + parsed.retiredWorktreeNamesByNamespace + ), worktreeMeta: recordOrEmpty(parsed.worktreeMeta), worktreeLineageById: recordOrEmpty(parsed.worktreeLineageById), workspaceLineageByChildKey: recordOrEmpty(parsed.workspaceLineageByChildKey), diff --git a/src/main/orca-profiles/profile-project-transfer-payload.ts b/src/main/orca-profiles/profile-project-transfer-payload.ts index a984b7bbf143..b2f74fd36091 100644 --- a/src/main/orca-profiles/profile-project-transfer-payload.ts +++ b/src/main/orca-profiles/profile-project-transfer-payload.ts @@ -7,7 +7,10 @@ import type { PersistedState } from '../../shared/persisted-state-types' import type { Repo } from '../../shared/repo-types' import type { SparsePreset } from '../../shared/worktree/create-types' import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' -import { parseWorkspaceKey } from '../../shared/workspace-scope' +import { + extractRetiredNameRegistriesByNamespace, + mergeRetiredNameRegistryMaps +} from './profile-project-retired-name-transfer' import type { TransferProfileState } from './profile-project-state-file' import { rebuildRepoBackedProjectState } from './profile-project-state-file' import { mergeHostWorkspaceSessions, mergeWorkspaceSessions } from './profile-project-session-state' @@ -15,11 +18,8 @@ import { extractHostSessionsForTransfer, extractSessionForTransfer } from './profile-project-session-transfer' -import { - isRepoWorktreeId, - rekeyWorktreeId, - rekeyWorkspaceKey -} from './profile-project-worktree-identity' +import { collectTransferWorktreeIds } from './profile-project-transfer-worktree-ids' +import { rekeyWorktreeId, rekeyWorkspaceKey } from './profile-project-worktree-identity' export type TransferPayload = { repo: Repo @@ -27,6 +27,7 @@ export type TransferPayload = { /** Generated names already spent for this repo, compacted. Carried so the destination profile * does not reissue a name whose old directory still holds agent state. */ retiredNameRegistry: RetiredNameRegistry | undefined + retiredNameRegistriesByNamespace: Record worktreeMeta: PersistedState['worktreeMeta'] worktreeLineageById: PersistedState['worktreeLineageById'] workspaceLineageByChildKey: PersistedState['workspaceLineageByChildKey'] @@ -64,86 +65,6 @@ function createUniqueRepoId(state: TransferProfileState): string { return candidate } -function collectTransferWorktreeIds(state: TransferProfileState, repoId: string): Set { - const ids = new Set() - const add = (value: string | null | undefined): void => { - if (value && isRepoWorktreeId(repoId, value)) { - ids.add(value) - } - } - Object.keys(state.worktreeMeta).forEach(add) - for (const lineage of Object.values(state.worktreeLineageById)) { - add(lineage.worktreeId) - add(lineage.parentWorktreeId) - } - for (const [key, lineage] of Object.entries(state.workspaceLineageByChildKey)) { - const child = parseWorkspaceKey(key) - const parent = parseWorkspaceKey(lineage.parentWorkspaceKey) - if (child?.type === 'worktree') { - add(child.worktreeId) - } - if (parent?.type === 'worktree') { - add(parent.worktreeId) - } - } - collectSessionWorktreeIds(state.workspaceSession, repoId, ids) - for (const session of Object.values(state.workspaceSessionsByHostId ?? {})) { - collectSessionWorktreeIds(session, repoId, ids) - } - Object.keys(state.ui?.showDotfilesByWorktree ?? {}).forEach(add) - return ids -} - -function collectSessionWorktreeIds( - session: PersistedState['workspaceSession'] | undefined, - repoId: string, - ids: Set -): void { - if (!session) { - return - } - const add = (value: string | null | undefined): void => { - if (value && isRepoWorktreeId(repoId, value)) { - ids.add(value) - } - } - const addOwnerKeys = (record: Record | undefined): void => { - for (const key of Object.keys(record ?? {})) { - if (isRepoWorktreeId(repoId, key)) { - ids.add(key) - } - const parsed = parseWorkspaceKey(key) - if (parsed?.type === 'worktree' && isRepoWorktreeId(repoId, parsed.worktreeId)) { - ids.add(parsed.worktreeId) - } - } - } - addOwnerKeys(session.tabsByWorktree) - addOwnerKeys(session.openFilesByWorktree) - addOwnerKeys(session.browserTabsByWorktree) - addOwnerKeys(session.activeBrowserTabIdByWorktree) - addOwnerKeys(session.activeTabTypeByWorktree) - addOwnerKeys(session.activeTabIdByWorktree) - addOwnerKeys(session.unifiedTabs) - addOwnerKeys(session.tabGroups) - addOwnerKeys(session.tabGroupLayouts) - addOwnerKeys(session.activeGroupIdByWorktree) - addOwnerKeys(session.lastVisitedAtByWorktreeId) - addOwnerKeys(session.defaultTerminalTabsAppliedByWorktreeId) - addOwnerKeys(session.terminalTopologyRevisionByRepoId) - addOwnerKeys(session.activeFileIdByWorktree) - for (const tombstone of Object.values(session.terminalSurfaceTombstonesByPaneKey ?? {})) { - add(tombstone.worktreeId) - } - add(session.activeWorktreeId) - const activeScope = session.activeWorkspaceKey - ? parseWorkspaceKey(session.activeWorkspaceKey) - : null - if (activeScope?.type === 'worktree') { - add(activeScope.worktreeId) - } -} - function rekeyWorktreeIdRecord( record: Record, worktreeIds: ReadonlySet, @@ -222,6 +143,10 @@ export function createTransferPayload(args: { repoId: newRepoId })), retiredNameRegistry: sourceState.retiredWorktreeNamesByRepo?.[oldRepoId], + retiredNameRegistriesByNamespace: extractRetiredNameRegistriesByNamespace( + sourceState, + sourceRepo + ), worktreeMeta: rekeyWorktreeIdRecord( sourceState.worktreeMeta, worktreeIds, @@ -281,6 +206,10 @@ export function applyPayloadToTarget( ...targetState.retiredWorktreeNamesByRepo, ...(payload.retiredNameRegistry ? { [payload.repo.id]: payload.retiredNameRegistry } : {}) }, + retiredWorktreeNamesByNamespace: mergeRetiredNameRegistryMaps( + targetState.retiredWorktreeNamesByNamespace ?? {}, + payload.retiredNameRegistriesByNamespace + ), worktreeMeta: { ...targetState.worktreeMeta, ...payload.worktreeMeta }, worktreeLineageById: { ...targetState.worktreeLineageById, ...payload.worktreeLineageById }, diff --git a/src/main/orca-profiles/profile-project-transfer-worktree-ids.ts b/src/main/orca-profiles/profile-project-transfer-worktree-ids.ts new file mode 100644 index 000000000000..51d87cfc668a --- /dev/null +++ b/src/main/orca-profiles/profile-project-transfer-worktree-ids.ts @@ -0,0 +1,87 @@ +import type { PersistedState } from '../../shared/persisted-state-types' +import { parseWorkspaceKey } from '../../shared/workspace-scope' +import type { TransferProfileState } from './profile-project-state-file' +import { isRepoWorktreeId } from './profile-project-worktree-identity' + +export function collectTransferWorktreeIds( + state: TransferProfileState, + repoId: string +): Set { + const ids = new Set() + const add = (value: string | null | undefined): void => { + if (value && isRepoWorktreeId(repoId, value)) { + ids.add(value) + } + } + Object.keys(state.worktreeMeta).forEach(add) + for (const lineage of Object.values(state.worktreeLineageById)) { + add(lineage.worktreeId) + add(lineage.parentWorktreeId) + } + for (const [key, lineage] of Object.entries(state.workspaceLineageByChildKey)) { + const child = parseWorkspaceKey(key) + const parent = parseWorkspaceKey(lineage.parentWorkspaceKey) + if (child?.type === 'worktree') { + add(child.worktreeId) + } + if (parent?.type === 'worktree') { + add(parent.worktreeId) + } + } + collectSessionWorktreeIds(state.workspaceSession, repoId, ids) + for (const session of Object.values(state.workspaceSessionsByHostId ?? {})) { + collectSessionWorktreeIds(session, repoId, ids) + } + Object.keys(state.ui?.showDotfilesByWorktree ?? {}).forEach(add) + return ids +} + +function collectSessionWorktreeIds( + session: PersistedState['workspaceSession'] | undefined, + repoId: string, + ids: Set +): void { + if (!session) { + return + } + const add = (value: string | null | undefined): void => { + if (value && isRepoWorktreeId(repoId, value)) { + ids.add(value) + } + } + const addOwnerKeys = (record: Record | undefined): void => { + for (const key of Object.keys(record ?? {})) { + if (isRepoWorktreeId(repoId, key)) { + ids.add(key) + } + const parsed = parseWorkspaceKey(key) + if (parsed?.type === 'worktree' && isRepoWorktreeId(repoId, parsed.worktreeId)) { + ids.add(parsed.worktreeId) + } + } + } + addOwnerKeys(session.tabsByWorktree) + addOwnerKeys(session.openFilesByWorktree) + addOwnerKeys(session.browserTabsByWorktree) + addOwnerKeys(session.activeBrowserTabIdByWorktree) + addOwnerKeys(session.activeTabTypeByWorktree) + addOwnerKeys(session.activeTabIdByWorktree) + addOwnerKeys(session.unifiedTabs) + addOwnerKeys(session.tabGroups) + addOwnerKeys(session.tabGroupLayouts) + addOwnerKeys(session.activeGroupIdByWorktree) + addOwnerKeys(session.lastVisitedAtByWorktreeId) + addOwnerKeys(session.defaultTerminalTabsAppliedByWorktreeId) + addOwnerKeys(session.terminalTopologyRevisionByRepoId) + addOwnerKeys(session.activeFileIdByWorktree) + for (const tombstone of Object.values(session.terminalSurfaceTombstonesByPaneKey ?? {})) { + add(tombstone.worktreeId) + } + add(session.activeWorktreeId) + const activeScope = session.activeWorkspaceKey + ? parseWorkspaceKey(session.activeWorkspaceKey) + : null + if (activeScope?.type === 'worktree') { + add(activeScope.worktreeId) + } +} diff --git a/src/main/orca-profiles/profile-project-transfer.test.ts b/src/main/orca-profiles/profile-project-transfer.test.ts index facde389e21c..60973c975296 100644 --- a/src/main/orca-profiles/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/profile-project-transfer.test.ts @@ -129,6 +129,9 @@ describe('profile project transfer', () => { ] }, retiredWorktreeNamesByRepo: { 'repo-1': { exhaustedTiers: 0, names: ['nautilus'] } }, + retiredWorktreeNamesByNamespace: { + 'ssh:ssh-1:/workspace/orca-nautilus': { exhaustedTiers: 0, names: ['seahorse'] } + }, worktreeMeta: { [sourceWorktreeId]: makeWorktreeMeta({ projectHostSetupId: 'repo-1' }) }, @@ -186,6 +189,7 @@ describe('profile project transfer', () => { exhaustedTiers: 0, names: ['nautilus'] }) + expect(target.retiredWorktreeNamesByNamespace).toEqual({}) expect(target.workspaceSession.tabsByWorktree).toEqual({}) expect(readProfileState('personal').repos.map((repo) => repo.id)).toEqual(['repo-1']) }) @@ -211,6 +215,12 @@ describe('profile project transfer', () => { }) ], sshTargets: [sshTarget], + retiredWorktreeNamesByNamespace: { + 'ssh:ssh-1:posix:/srv/orca-orca-retirement-probe': { + exhaustedTiers: 0, + names: ['seahorse'] + } + }, worktreeMeta: { [sourceWorktreeId]: makeWorktreeMeta({ projectHostSetupId: 'repo-ssh' }) }, @@ -266,6 +276,12 @@ describe('profile project transfer', () => { executionHostId: 'ssh:ssh-1' }) expect(target.sshTargets).toEqual([sshTarget]) + expect(target.retiredWorktreeNamesByNamespace).toEqual({ + 'ssh:ssh-1:posix:/srv/orca-orca-retirement-probe': { + exhaustedTiers: 0, + names: ['seahorse'] + } + }) expect(target.workspaceSession.browserTabsByWorktree?.[sourceWorktreeId]?.[0]).toMatchObject({ worktreeId: sourceWorktreeId, sessionProfileId: null, diff --git a/src/main/persistence-worktree-name-retirement.test.ts b/src/main/persistence-worktree-name-retirement.test.ts index ec567fefa6c8..2554abcd16c2 100644 --- a/src/main/persistence-worktree-name-retirement.test.ts +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -140,6 +140,32 @@ describe('worktree name retirement registry', () => { expect(store.getRetiredWorktreeNameRegistry(REPO).names).toEqual([]) }) + it('reassociates remote retirements after remove and re-add mints a new repo id', async () => { + const oldRepo = { + id: REPO, + path: '/remote/repos/a', + displayName: 'a', + badgeColor: '', + addedAt: 0, + connectionId: 'ssh-1' + } + let store = await createStore() + store.addRepo(oldRepo) + const { getRetiredNameRegistryForRepo, retireGeneratedWorktreeName } = + await import('./worktree-name-retirement') + await retireGeneratedWorktreeName(store, oldRepo, store.getSettings(), 'nautilus') + store.removeProject(REPO) + store.flush() + + store = await reloadStore() + const newRepo = { ...oldRepo, id: OTHER_REPO } + store.addRepo(newRepo) + + await expect( + getRetiredNameRegistryForRepo(store, newRepo, [newRepo], store.getSettings()) + ).resolves.toEqual({ exhaustedTiers: 0, names: ['nautilus'] }) + }) + it('keeps the registry when one host row is removed but the repo id survives elsewhere', async () => { const store = await createStore() store.addRepo({ id: REPO, path: '/repos/a', displayName: 'a', badgeColor: '', addedAt: 0 }) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 535a15039107..253ea79ef1a2 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2358,7 +2358,7 @@ function normalizeRetiredNameRegistry(row: unknown): RetiredNameRegistry { /** Why: a corrupt or hand-edited map must degrade to "nothing retired" rather than throw during * load — over-retiring costs one name from a 552-entry pool, but a load failure costs the app. */ -function normalizeRetiredWorktreeNamesByRepo(value: unknown): Record { +function normalizeRetiredNameRegistryMap(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return {} } @@ -3865,9 +3865,12 @@ export class Store { (alias): alias is string => typeof alias === 'string' ) : [], - retiredWorktreeNamesByRepo: normalizeRetiredWorktreeNamesByRepo( + retiredWorktreeNamesByRepo: normalizeRetiredNameRegistryMap( parsed.retiredWorktreeNamesByRepo ), + retiredWorktreeNamesByNamespace: normalizeRetiredNameRegistryMap( + parsed.retiredWorktreeNamesByNamespace + ), sshRemotePtyLeases: (parsed.sshRemotePtyLeases ?? []) .map(normalizeSshRemotePtyLease) .filter((lease): lease is SshRemotePtyLease => lease !== null), @@ -7265,6 +7268,13 @@ export class Store { : EMPTY_RETIRED_NAME_REGISTRY } + getRetiredWorktreeNameRegistryForNamespace(namespaceKey: string): RetiredNameRegistry { + const stored = this.state.retiredWorktreeNamesByNamespace?.[namespaceKey] + return stored + ? { exhaustedTiers: stored.exhaustedTiers, names: [...stored.names] } + : EMPTY_RETIRED_NAME_REGISTRY + } + /** Records a generated workspace name as spent for this repo. Called with the name main actually * used, not the one the renderer proposed — the create path can advance past it on collision. */ addRetiredWorktreeName(repoId: string, name: string): void { @@ -7291,6 +7301,30 @@ export class Store { return incoming.size > 0 && this.applyRetiredWorktreeNames(repoId, incoming) } + mergeRetiredWorktreeNamesForNamespace(namespaceKey: string, names: Iterable): boolean { + if (!namespaceKey) { + return false + } + const normalized = new Set() + for (const name of names) { + const candidate = normalizeRetirableGeneratedName(name) + if (candidate) { + normalized.add(candidate) + } + } + const next = addRetiredNames( + this.getRetiredWorktreeNameRegistryForNamespace(namespaceKey), + normalized + ) + if (!next) { + return false + } + this.state.retiredWorktreeNamesByNamespace ??= {} + this.state.retiredWorktreeNamesByNamespace[namespaceKey] = next + this.scheduleSave() + return true + } + private applyRetiredWorktreeNames(repoId: string, names: Iterable): boolean { const next = addRetiredNames(this.getRetiredWorktreeNameRegistry(repoId), names) if (!next) { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 65fdb7feed92..eaa64ec203dc 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -28,6 +28,7 @@ const ORIGIN_REMOTE_URL = 'git@example.com:group/repo.git' const ORIGIN_HEAD_COMPONENT = reviewHeadRemoteRefComponent('origin', ORIGIN_REMOTE_URL) import { detectAgentStatusFromTitle, MAX_OSC_TITLE_CHARS } from '../../shared/agent-detection' import { + addSparseWorktree, addWorktree, assertWorktreeCleanForRemoval, listWorktrees, @@ -216,6 +217,7 @@ vi.mock('../ipc/filesystem-watcher', () => ({ const { MOCK_GIT_WORKTREES, + addSparseWorktreeMock, addWorktreeMock, removeWorktreeMock, forceDeleteLocalBranchMock, @@ -312,6 +314,7 @@ const { isMainWorktree: false } ], + addSparseWorktreeMock: vi.fn(), addWorktreeMock: vi.fn(), removeWorktreeMock: vi.fn(), forceDeleteLocalBranchMock: vi.fn(), @@ -412,6 +415,7 @@ vi.mock('../git/worktree', () => ({ listWorktrees: vi.fn().mockResolvedValue(MOCK_GIT_WORKTREES), listWorktreesStrict: vi.fn().mockResolvedValue(MOCK_GIT_WORKTREES), assertWorktreeCleanForRemoval: vi.fn().mockResolvedValue(undefined), + addSparseWorktree: addSparseWorktreeMock, addWorktree: addWorktreeMock, removeWorktree: removeWorktreeMock, forceDeleteLocalBranch: forceDeleteLocalBranchMock @@ -677,6 +681,7 @@ function resetRuntimeTestMocks(): void { } }) vi.mocked(addWorktree).mockReset() + vi.mocked(addSparseWorktree).mockReset() vi.mocked(assertWorktreeCleanForRemoval).mockReset() vi.mocked(assertWorktreeCleanForRemoval).mockResolvedValue(undefined) vi.mocked(removeWorktree).mockReset() @@ -4297,13 +4302,18 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName, - getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: ['nautilus'] }) + getRetiredWorktreeNameRegistry: () => ({ + exhaustedTiers: 0, + names: Array.from({ length: 100 }, (_unused, index) => + index === 0 ? 'nautilus' : `nautilus-${index + 1}` + ) + }) }) const staleScan = deferred() const createdWorktree = { - path: '/tmp/workspaces/repo-nautilus-2', + path: '/tmp/workspaces/repo-nautilus-101', head: 'def', - branch: 'nautilus-2', + branch: 'nautilus-101', isBare: false, isMainWorktree: false } @@ -4334,7 +4344,47 @@ describe('OrcaRuntimeService', () => { worktrees: expect.arrayContaining([expect.objectContaining({ path: createdWorktree.path })]) } ) - expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus-2') + expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus-101') + }) + + it('retires a generated name before a post-create listing failure', async () => { + const addRetiredWorktreeName = vi.fn() + const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName }) + computeWorktreePathMock.mockReturnValue('/tmp/workspaces/nautilus') + ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/nautilus') + vi.mocked(listWorktrees).mockRejectedValueOnce(new Error('listing unavailable')) + + await expect( + runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'nautilus', + nameWasGenerated: true + }) + ).rejects.toThrow('listing unavailable') + + expect(addWorktree).toHaveBeenCalled() + expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus') + }) + + it('retires a generated sparse name when creation rollback also fails', async () => { + const addRetiredWorktreeName = vi.fn() + const runtime = new OrcaRuntimeService({ ...store, addRetiredWorktreeName }) + computeWorktreePathMock.mockReturnValue('/tmp/workspaces/nautilus') + ensurePathWithinWorkspaceMock.mockReturnValue('/tmp/workspaces/nautilus') + vi.mocked(addSparseWorktree).mockRejectedValueOnce( + Object.assign(new Error('sparse setup failed'), { cleanupFailed: true }) + ) + + await expect( + runtime.createManagedWorktree({ + repoSelector: 'id:repo-1', + name: 'nautilus', + nameWasGenerated: true, + sparseCheckout: { directories: ['packages/web'] } + }) + ).rejects.toThrow('sparse setup failed') + + expect(addRetiredWorktreeName).toHaveBeenCalledWith(TEST_REPO_ID, 'nautilus') }) it('neither skips nor retires a name the user typed', async () => { @@ -44878,12 +44928,12 @@ describe('OrcaRuntimeService', () => { ) }) - it('detects agents on the SSH host before launching remote startup drafts', async () => { + it('forwards generated-name provenance while launching SSH startup drafts', async () => { detectRemoteAgentsMock.mockResolvedValue(['claude']) const created = { - path: '/remote/mobile-startup-draft', + path: '/remote/repo-nautilus-2', head: 'def', - branch: 'refs/heads/mobile-startup-draft', + branch: 'refs/heads/nautilus-2', isBare: false, isMainWorktree: false } @@ -44913,6 +44963,7 @@ describe('OrcaRuntimeService', () => { defaultTuiAgent: null, agentCmdOverrides: {} }), + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: ['nautilus'] }), getAllWorktreeMeta: () => metaById, getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], setWorktreeMeta: (worktreeId: string, meta: Partial) => { @@ -44956,15 +45007,22 @@ describe('OrcaRuntimeService', () => { const draftUrl = 'https://github.com/stablyai/orca/pull/456' const result = await runtime.createManagedWorktree({ repoSelector: TEST_REPO_ID, - name: 'mobile-startup-draft', + name: 'nautilus', + nameWasGenerated: true, startupDraft: draftUrl }) expect(detectRemoteAgentsMock).toHaveBeenCalledWith({ connectionId: 'ssh-1' }) expect(detectInstalledAgentsWithShellPathHydrationMock).not.toHaveBeenCalled() + expect(provider.addWorktree).toHaveBeenCalledWith( + '/remote/repo', + 'nautilus-2', + '/remote/repo-nautilus-2', + expect.any(Object) + ) expect(spawn).toHaveBeenCalledWith( expect.objectContaining({ - cwd: '/remote/mobile-startup-draft', + cwd: '/remote/repo-nautilus-2', command: `claude '--dangerously-skip-permissions' --prefill '${draftUrl}'`, connectionId: 'ssh-1', worktreeId: result.worktree.id diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 0767e6b9363e..3fd2f0321e98 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -962,12 +962,15 @@ import { } from '../ipc/worktree-remote' import { getBranchNameOverrideCandidate, + getGeneratedWorktreeCreateCandidate, getWorktreeCreateCandidate, + isGeneratedWorktreeCreateName, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' import { - ensureRetiredWorktreeNamesBackfilled, - getRetiredNameRegistryForRepo + failedWorktreeCreationNeedsRetirement, + getRetiredNameRegistryForRepo, + retireGeneratedWorktreeName } from '../worktree-name-retirement' import { createRetiredNameLookup, @@ -21348,12 +21351,7 @@ export class OrcaRuntimeService { } const repo = await this.resolveRepoSelector(repoSelector) const settings = store.getSettings() - try { - await ensureRetiredWorktreeNamesBackfilled(store, repo, settings) - } catch (error) { - console.warn(`[runtime] retirement backfill failed for repo ${repo.id}:`, error) - } - const registry: RetiredNameRegistry = getRetiredNameRegistryForRepo( + const registry: RetiredNameRegistry = await getRetiredNameRegistryForRepo( store, repo, store.getRepos(), @@ -22570,21 +22568,35 @@ export class OrcaRuntimeService { let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false - const isRetiredName = args.nameWasGenerated - ? createRetiredNameLookup( - getRetiredNameRegistryForRepo(this.store, repo, this.store.getRepos(), settings) - ) + const shouldRetireGeneratedName = + args.nameWasGenerated === true && isGeneratedWorktreeCreateName(sanitizedName) + const retiredNameRegistry = shouldRetireGeneratedName + ? await getRetiredNameRegistryForRepo(this.store, repo, this.store.getRepos(), settings) : null + const isRetiredName = retiredNameRegistry ? createRetiredNameLookup(retiredNameRegistry) : null // Why: runtime/mobile create-from-review callers should get a new workspace // even when the PR branch or review branch name is already in use. - for (let suffix = 1; suffix <= WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; suffix += 1) { - effectiveSanitizedName = getWorktreeCreateCandidate(sanitizedName, suffix) - effectiveRequestedName = args.name.trim() - ? getWorktreeCreateCandidate(args.name, suffix) - : effectiveSanitizedName + for ( + let suffix = 1, attempts = 0; + attempts < WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS; + suffix += 1 + ) { + effectiveSanitizedName = shouldRetireGeneratedName + ? getGeneratedWorktreeCreateCandidate( + sanitizedName, + suffix, + retiredNameRegistry?.exhaustedTiers + ) + : getWorktreeCreateCandidate(sanitizedName, suffix) + effectiveRequestedName = shouldRetireGeneratedName + ? effectiveSanitizedName + : args.name.trim() + ? getWorktreeCreateCandidate(args.name, suffix) + : effectiveSanitizedName if (isRetiredName?.(effectiveSanitizedName)) { continue } + attempts += 1 branchName = await resolveCreateBranchName( repo.path, selectedExistingLocalBranchName ?? @@ -22786,19 +22798,11 @@ export class OrcaRuntimeService { ...(suggestLocalBaseRefUpdate ? { suggestLocalBaseRefUpdate } : {}) } const defaultAddWorktreeOption = addProjectGitOptions() - const addResult: AddWorktreeResult = - (await (sparseDirectories.length > 0 - ? checkoutExistingBranch - ? addSparseWorktree( - repo.path, - worktreePath, - branchName, - sparseDirectories, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate, - addProjectGitOptions(existingBranchOption) - ) - : suggestLocalBaseRefUpdate + let addResult: AddWorktreeResult + try { + addResult = + (await (sparseDirectories.length > 0 + ? checkoutExistingBranch ? addSparseWorktree( repo.path, worktreePath, @@ -22806,9 +22810,9 @@ export class OrcaRuntimeService { sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) + addProjectGitOptions(existingBranchOption) ) - : remoteTrackingBaseOption + : suggestLocalBaseRefUpdate ? addSparseWorktree( repo.path, worktreePath, @@ -22816,9 +22820,9 @@ export class OrcaRuntimeService { sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - addProjectGitOptions(remoteTrackingBaseOption) + addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) ) - : defaultAddWorktreeOption + : remoteTrackingBaseOption ? addSparseWorktree( repo.path, worktreePath, @@ -22826,27 +22830,27 @@ export class OrcaRuntimeService { sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - defaultAddWorktreeOption - ) - : addSparseWorktree( - repo.path, - worktreePath, - branchName, - sparseDirectories, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate + addProjectGitOptions(remoteTrackingBaseOption) ) - : checkoutExistingBranch - ? addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate, - false, - addProjectGitOptions(existingBranchOption) - ) - : suggestLocalBaseRefUpdate + : defaultAddWorktreeOption + ? addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + defaultAddWorktreeOption + ) + : addSparseWorktree( + repo.path, + worktreePath, + branchName, + sparseDirectories, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + ) + : checkoutExistingBranch ? addWorktree( repo.path, worktreePath, @@ -22854,9 +22858,9 @@ export class OrcaRuntimeService { baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, false, - addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) + addProjectGitOptions(existingBranchOption) ) - : remoteTrackingBaseOption + : suggestLocalBaseRefUpdate ? addWorktree( repo.path, worktreePath, @@ -22864,9 +22868,9 @@ export class OrcaRuntimeService { baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, false, - addProjectGitOptions(remoteTrackingBaseOption) + addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) ) - : defaultAddWorktreeOption + : remoteTrackingBaseOption ? addWorktree( repo.path, worktreePath, @@ -22874,15 +22878,36 @@ export class OrcaRuntimeService { baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, false, - defaultAddWorktreeOption + addProjectGitOptions(remoteTrackingBaseOption) ) - : addWorktree( - repo.path, - worktreePath, - branchName, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - ))) ?? {} + : defaultAddWorktreeOption + ? addWorktree( + repo.path, + worktreePath, + branchName, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate, + false, + defaultAddWorktreeOption + ) + : addWorktree( + repo.path, + worktreePath, + branchName, + baseBranch, + settings.refreshLocalBaseRefOnWorktreeCreate + ))) ?? {} + } catch (error) { + if (shouldRetireGeneratedName && failedWorktreeCreationNeedsRetirement(error)) { + await retireGeneratedWorktreeName(this.store, repo, settings, effectiveSanitizedName) + } + throw error + } + + // Why: fallible metadata work after creation must not leave a real workspace name reusable. + if (shouldRetireGeneratedName) { + await retireGeneratedWorktreeName(this.store, repo, settings, effectiveSanitizedName) + } let configuredPushTarget: GitPushTarget | undefined if (preparedPushTarget) { @@ -22904,10 +22929,6 @@ export class OrcaRuntimeService { } const worktreeId = `${repo.id}::${created.path}` - // Why: repo-qualified layouts decorate the physical leaf; retire the name main actually used. - if (args.nameWasGenerated) { - this.store.addRetiredWorktreeName(repo.id, effectiveSanitizedName) - } const now = Date.now() // Why: PR/MR-created worktrees can start from a head ref/SHA while Source // Control must compare against the review target branch. @@ -23355,6 +23376,7 @@ export class OrcaRuntimeService { repo: Repo, args: { name: string + nameWasGenerated?: boolean baseBranch?: string compareBaseRef?: string branchNameOverride?: string @@ -23406,6 +23428,7 @@ export class OrcaRuntimeService { { repoId: repo.id, name: args.name, + ...(args.nameWasGenerated === true ? { nameWasGenerated: true } : {}), ...(args.displayName ? { displayName: args.displayName } : {}), ...(args.baseBranch ? { baseBranch: args.baseBranch } : {}), ...(args.compareBaseRef ? { compareBaseRef: args.compareBaseRef } : {}), diff --git a/src/main/worktree-create-candidates.test.ts b/src/main/worktree-create-candidates.test.ts new file mode 100644 index 000000000000..f39fe7cefc37 --- /dev/null +++ b/src/main/worktree-create-candidates.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { + getGeneratedWorktreeCreateCandidate, + isGeneratedWorktreeCreateName +} from './worktree-create-candidates' + +describe('generated worktree create candidates', () => { + it('advances canonical tiers instead of nesting collision suffixes', () => { + expect(getGeneratedWorktreeCreateCandidate('nautilus-2', 1)).toBe('nautilus-2') + expect(getGeneratedWorktreeCreateCandidate('nautilus-2', 2)).toBe('nautilus-3') + expect(getGeneratedWorktreeCreateCandidate('nautilus-2', 99)).toBe('nautilus-100') + expect(getGeneratedWorktreeCreateCandidate('nautilus', 1, 100)).toBe('nautilus-101') + }) + + it('canonicalizes legacy nested generated suffixes', () => { + expect(isGeneratedWorktreeCreateName('nautilus')).toBe(true) + expect(isGeneratedWorktreeCreateName('nautilus-2')).toBe(true) + expect(isGeneratedWorktreeCreateName('nautilus-2-3')).toBe(true) + expect(getGeneratedWorktreeCreateCandidate('nautilus-2-3', 1)).toBe('nautilus-4') + expect(isGeneratedWorktreeCreateName('fix-login')).toBe(false) + }) +}) diff --git a/src/main/worktree-create-candidates.ts b/src/main/worktree-create-candidates.ts index 87be13984656..71536ad6c984 100644 --- a/src/main/worktree-create-candidates.ts +++ b/src/main/worktree-create-candidates.ts @@ -1,9 +1,24 @@ +import { + getGeneratedWorktreeCreateRetryCandidate, + isGeneratedWorktreeCreateName +} from '../shared/new-workspace/worktree-create-retry-policy' + +export { isGeneratedWorktreeCreateName } + export const WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS = 100 export function getWorktreeCreateCandidate(value: string, suffix: number): string { return suffix === 1 ? value : `${value}-${suffix}` } +export function getGeneratedWorktreeCreateCandidate( + value: string, + suffix: number, + exhaustedTiers = 0 +): string { + return getGeneratedWorktreeCreateRetryCandidate(value, suffix - 1, exhaustedTiers + 1) +} + export function getBranchNameOverrideCandidate( branchNameOverride: string | undefined, suffix: number diff --git a/src/main/worktree-name-retirement.test.ts b/src/main/worktree-name-retirement.test.ts index e2ec1ab826f2..8a0e8237cafe 100644 --- a/src/main/worktree-name-retirement.test.ts +++ b/src/main/worktree-name-retirement.test.ts @@ -35,12 +35,9 @@ describe('normalizeRetirableGeneratedName', () => { expect(normalizeRetirableGeneratedName(`${FIRST}-100`)).toBe(`${FIRST}-100`) }) - it('retires a suffixed name that itself took a collision suffix', () => { - // Once the pool is spent the suggester emits `-2`; a collision on that yields - // `-2-3`. Stripping only one suffix leaves `-2`, which is not a pool name, so - // retirement would no-op at exactly the tier where every base name is already gone. - expect(normalizeRetirableGeneratedName(`${FIRST}-2-3`)).toBe(`${FIRST}-2-3`) - expect(normalizeRetirableGeneratedName(`${FIRST}-2-3-4`)).toBe(`${FIRST}-2-3-4`) + it('rejects legacy repeated suffixes that the canonical collision sequence never emits', () => { + expect(normalizeRetirableGeneratedName(`${FIRST}-2-3`)).toBeNull() + expect(normalizeRetirableGeneratedName(`${FIRST}-2-3-4`)).toBeNull() expect(normalizeRetirableGeneratedName('fix-login-2-3')).toBeNull() }) @@ -122,6 +119,18 @@ describe('discoverRetiredWorktreeNames', () => { }) }) + it('matches an NFC bucket for an NFD workspace root', async () => { + const nfdRoot = '/Users/ada/cafe\u0301' + await withFakeHome([`-Users-ada-caf--${FIRST}`], async (home) => { + const retired = await discoverRetiredWorktreeNames({ + workspaceRoots: [nfdRoot], + home, + env: {} + }) + expect(retired).toEqual(new Set([FIRST])) + }) + }) + it('matches a dot-directory root, where the separator run encodes to two dashes', async () => { await withFakeHome([`-Users-ada--orca-worktrees-${FIRST}`], async (home) => { const retired = await discoverRetiredWorktreeNames({ @@ -214,6 +223,7 @@ describe('getRetiredNameRegistryForRepo', () => { const calls: string[] = [] return { calls, + mergeRetiredWorktreeNames: () => false, getRetiredWorktreeNameRegistry: (repoId: string) => { calls.push(repoId) return { exhaustedTiers: 0, names: byRepo[repoId] ?? [] } @@ -221,28 +231,28 @@ describe('getRetiredNameRegistryForRepo', () => { } } - it('shares retirements when two repos create into the same cwd namespace', () => { + it('shares retirements when two repos create into the same cwd namespace', async () => { const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] expect( - [...getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(false)).names].sort() + [ + ...(await getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(false))).names + ].sort() ).toEqual([FIRST, SECOND].sort()) }) - it('keeps independent nested repo paths in separate retirement domains', () => { + it('keeps independent nested repo paths in separate retirement domains', async () => { const store = storeOf({ 'repo-a': [FIRST], 'repo-b': [SECOND] }) const repos = [makeRepo('repo-a', '/repos/a'), makeRepo('repo-b', '/repos/b')] - expect(getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(true))).toEqual({ + expect(await getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(true))).toEqual({ exhaustedTiers: 0, names: [SECOND] }) }) - it('never probes a path for peers that hold no retirements', () => { - // Why: deriving a peer's namespace runs computeWorktreePath, which for a WSL repo is a blocking - // wsl.exe call. Reading `path` is exactly what a probe does, so count that. + it('never probes a path for peers that hold no retirements', async () => { const pathReads: string[] = [] const spyRepo = (id: string, path: string): Repo => { const repo = makeRepo(id, path) @@ -259,19 +269,22 @@ describe('getRetiredNameRegistryForRepo', () => { ...Array.from({ length: 20 }, (_unused, index) => spyRepo(`peer-${index}`, `/repos/${index}`)) ] - expect(getRetiredNameRegistryForRepo(store, repos[0], repos, settingsFor(false))).toEqual({ - exhaustedTiers: 0, - names: [FIRST] - }) + expect(await getRetiredNameRegistryForRepo(store, repos[0], repos, settingsFor(false))).toEqual( + { + exhaustedTiers: 0, + names: [FIRST] + } + ) expect(pathReads.filter((id) => id.startsWith('peer-'))).toEqual([]) }) - it('reports nothing for a folder workspace, which has no generated worktree names', () => { + it('reports nothing for a folder workspace, which has no generated worktree names', async () => { const store = storeOf({ folder: [FIRST] }) const folderRepo = { ...makeRepo('folder', '/repos/folder'), kind: 'folder' as const } expect( - getRetiredNameRegistryForRepo(store, folderRepo, [folderRepo], settingsFor(false)).names + (await getRetiredNameRegistryForRepo(store, folderRepo, [folderRepo], settingsFor(false))) + .names ).toEqual([]) }) }) diff --git a/src/main/worktree-name-retirement.ts b/src/main/worktree-name-retirement.ts index ba73ba2525dc..53ac593011d6 100644 --- a/src/main/worktree-name-retirement.ts +++ b/src/main/worktree-name-retirement.ts @@ -3,7 +3,7 @@ import { homedir } from 'node:os' import { join } from 'node:path' import { getRepoExecutionHostId } from '../shared/execution-host' import { - CREATURE_POOL_NAMES, + creatureNameTier, EMPTY_RETIRED_NAME_REGISTRY, isEmptyRetiredNameRegistry, mergeRetiredNameRegistries, @@ -13,12 +13,11 @@ import { isFolderRepo } from '../shared/repo-kind' import type { GlobalSettings } from '../shared/global-settings-types' import type { Repo } from '../shared/repo-types' import { - encodeClaudeProjectPath, + encodeClaudeProjectPaths, isClaudeProjectDirInScope } from './ai-vault/claude-project-dir-encoding' import { computeRemoteWorktreePath, - computeWorktreePath, computeWorktreePathAsync, getWorktreePathSettings, hasRepoWorktreeBasePath @@ -31,29 +30,28 @@ const scansByStore = new WeakMap>>>() type RetirementReadStore = { getRetiredWorktreeNameRegistry(repoId: string): RetiredNameRegistry + getRetiredWorktreeNameRegistryForNamespace?(namespaceKey: string): RetiredNameRegistry } type RetirementBackfillStore = { mergeRetiredWorktreeNames(repoId: string, names: Iterable): boolean } +type RetirementWriteStore = { + addRetiredWorktreeName(repoId: string, name: string): void + mergeRetiredWorktreeNamesForNamespace?(namespaceKey: string, names: Iterable): boolean +} type RetirementPathSettings = Pick -/** Strips EVERY trailing numeric suffix, not just one. Once the pool is spent the suggester emits - * `nautilus-2`, and a collision on that yields `nautilus-2-3` — which a single strip leaves as - * `nautilus-2`, not a pool name, so retirement would silently no-op on exactly the tier where the - * pool is already exhausted. Deliberately not shared with `isAutoGeneratedCreatureBranchName`: - * auto-rename eligibility is a different question and its single-strip behavior is intended. */ +/** Only canonical generator output is persisted. Collision retries advance canonical tiers, so a + * repeat-suffixed path can never be generated again and needs no permanent registry entry. */ export function normalizeRetirableGeneratedName(name: string): string | null { const normalized = name.trim().toLowerCase() - if (normalized.length > 256) { - return null - } - let base = normalized - let stripped = base.replace(/-\d+$/, '') - while (stripped !== base) { - base = stripped - stripped = base.replace(/-\d+$/, '') - } - return base && CREATURE_POOL_NAMES.has(base) ? normalized : null + return normalized.length <= 256 && creatureNameTier(normalized) !== null ? normalized : null +} + +/** A sparse create error carries this marker only when its rollback also failed, leaving the path + * occupied even though creation rejected. */ +export function failedWorktreeCreationNeedsRetirement(error: unknown): boolean { + return typeof error === 'object' && error !== null && Reflect.get(error, 'cleanupFailed') === true } /** Why: over-retiring costs one name from a 552-entry pool; under-retiring reissues a path whose @@ -95,17 +93,33 @@ export function extractBucketLeafCandidates( return [] } -function getRetirementProbePath(repo: Repo, settings: RetirementPathSettings): string { +async function getRetirementProbePath( + repo: Repo, + settings: RetirementPathSettings +): Promise { const pathSettings = getWorktreePathSettings(repo, settings) return repo.connectionId ? computeRemoteWorktreePath(RETIREMENT_PROBE_NAME, repo.path, pathSettings, { useConfiguredAbsolutePath: hasRepoWorktreeBasePath(repo) }) - : computeWorktreePath(RETIREMENT_PROBE_NAME, repo.path, pathSettings) + : computeWorktreePathAsync(RETIREMENT_PROBE_NAME, repo.path, pathSettings) } -// Why: for a WSL repo the probe path costs a blocking `wsl.exe` call, and the create path plus -// every suggestion refresh asks for the same key. Inputs are all the key derives from. +export function getRemoteRetirementNamespaceKey( + repo: Repo, + settings: RetirementPathSettings +): string | null { + if (!repo.connectionId) { + return null + } + const pathSettings = getWorktreePathSettings(repo, settings) + const probePath = computeRemoteWorktreePath(RETIREMENT_PROBE_NAME, repo.path, pathSettings, { + useConfiguredAbsolutePath: hasRepoWorktreeBasePath(repo) + }) + return `${getRepoExecutionHostId(repo)}:${worktreePathComparisonKey(probePath)}` +} + +// Why: the create path and every suggestion refresh ask for the same namespace identity. const COLLISION_KEY_CACHE_MAX = 512 const collisionKeyCache = new Map() @@ -115,7 +129,10 @@ export function resetRetirementCollisionKeyCacheForTests(): void { /** Identifies the cwd namespace a repo creates workspaces into. Two repos that would place a * workspace of the same name at the same path share retirements; independent paths do not. */ -export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSettings): string { +async function getRetirementCollisionKey( + repo: Repo, + settings: RetirementPathSettings +): Promise { const hostId = getRepoExecutionHostId(repo) const cacheKey = [ hostId, @@ -128,7 +145,9 @@ export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSe if (cached !== undefined) { return cached } - const key = `${hostId}:${worktreePathComparisonKey(getRetirementProbePath(repo, settings))}` + const key = + getRemoteRetirementNamespaceKey(repo, settings) ?? + `${hostId}:${worktreePathComparisonKey(await getRetirementProbePath(repo, settings))}` // Why not always cache: only the WSL home *success* path is cached upstream, so a stopped distro // yields a fallback namespace. Memoizing that would strand the repo there for the whole session. const wsl = parseWslPath(repo.path) @@ -146,19 +165,30 @@ export function getRetirementCollisionKey(repo: Repo, settings: RetirementPathSe * namespace — that is where a reissued name would actually collide. * * The peer scan is deliberately lazy: a repo's own retirements never touch a path, and a peer's - * namespace is derived only once that peer is known to hold retirements. Deriving one costs a - * blocking `wsl.exe` call for a WSL repo, so it must not be paid per repo on every create. */ -export function getRetiredNameRegistryForRepo( - store: RetirementReadStore, + * namespace is derived only once that peer is known to hold retirements. */ +export async function getRetiredNameRegistryForRepo( + store: RetirementReadStore & RetirementBackfillStore, repo: Repo, repos: readonly Repo[], settings: RetirementPathSettings -): RetiredNameRegistry { +): Promise { if (isFolderRepo(repo)) { return EMPTY_RETIRED_NAME_REGISTRY } - let registry = store.getRetiredWorktreeNameRegistry(repo.id) let collisionKey: string | null = null + try { + collisionKey = await ensureRetiredWorktreeNamesBackfilled(store, repo, settings) + } catch (error) { + console.warn(`[worktrees] retirement backfill failed for repo ${repo.id}:`, error) + } + let registry = store.getRetiredWorktreeNameRegistry(repo.id) + if (repo.connectionId && store.getRetiredWorktreeNameRegistryForNamespace) { + collisionKey ??= await getRetirementCollisionKey(repo, settings) + registry = mergeRetiredNameRegistries( + registry, + store.getRetiredWorktreeNameRegistryForNamespace(collisionKey) + ) + } for (const candidate of repos) { if (candidate.id === repo.id || isFolderRepo(candidate)) { continue @@ -167,8 +197,8 @@ export function getRetiredNameRegistryForRepo( if (isEmptyRetiredNameRegistry(candidateRegistry)) { continue } - collisionKey ??= getRetirementCollisionKey(repo, settings) - if (getRetirementCollisionKey(candidate, settings) !== collisionKey) { + collisionKey ??= await getRetirementCollisionKey(repo, settings) + if ((await getRetirementCollisionKey(candidate, settings)) !== collisionKey) { continue } registry = mergeRetiredNameRegistries(registry, candidateRegistry) @@ -176,6 +206,24 @@ export function getRetiredNameRegistryForRepo( return registry } +export async function retireGeneratedWorktreeName( + store: RetirementWriteStore, + repo: Repo, + settings: RetirementPathSettings, + name: string +): Promise { + store.addRetiredWorktreeName(repo.id, name) + if (!repo.connectionId || !store.mergeRetiredWorktreeNamesForNamespace) { + return + } + try { + const namespaceKey = await getRetirementCollisionKey(repo, settings) + store.mergeRetiredWorktreeNamesForNamespace(namespaceKey, [name]) + } catch (error) { + console.warn(`[worktrees] failed to persist remote retirement namespace for ${repo.id}:`, error) + } +} + function parentPath(path: string): string { const trimmed = path.replace(/[/\\]+$/, '') const separatorIndex = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\')) @@ -189,11 +237,11 @@ export async function ensureRetiredWorktreeNamesBackfilled( store: RetirementBackfillStore, repo: Repo, settings: RetirementPathSettings -): Promise { +): Promise { // Remote workspaces keep their agent state on the execution host, which this scan cannot see, so // a re-added SSH repo does not recover its retirements the way a local one does. if (isFolderRepo(repo) || repo.connectionId) { - return + return null } const probePath = await computeWorktreePathAsync( RETIREMENT_PROBE_NAME, @@ -214,6 +262,7 @@ export async function ensureRetiredWorktreeNamesBackfilled( // Why the merge sits outside the cached scan: the scan is per cwd namespace but the registry is // per repo, so every repo that asks must receive it — not only the one that triggered it. store.mergeRetiredWorktreeNames(repo.id, await scan) + return scanKey } async function readDirectoryNames(path: string): Promise { @@ -257,7 +306,7 @@ export async function discoverRetiredWorktreeNames(args: { // filesystems, and a missed bucket reissues a live path while a spurious one costs one name. const encodedParents = args.workspaceRoots .filter((root) => root.length > 0) - .map((root) => encodeClaudeProjectPath(root).toLowerCase()) + .flatMap((root) => encodeClaudeProjectPaths(root).map((path) => path.toLowerCase())) if (encodedParents.length > 0) { const projectsDir = getClaudeProjectsDir(args.home ?? homedir(), args.env ?? process.env) for (const bucket of await readDirectoryNames(projectsDir)) { diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 068cf561e452..a7c43c8d5969 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -6244,6 +6244,33 @@ describe('worktree remote runtime mutations', () => { expect(store.getState().worktreesByRepo.repo1).toEqual([wt]) }) + it('forwards generated-name provenance through paired-runtime create', async () => { + const store = createTestStore() + const wt = makeWorktree({ id: 'repo1::/path/nautilus', repoId: 'repo1' }) + runtimeEnvironmentCall.mockResolvedValue({ + id: 'rpc-create', + ok: true, + result: { worktree: wt }, + _meta: { runtimeId: 'runtime-remote' } + }) + store.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + worktreesByRepo: { repo1: [] } + } as Partial) + const createWorktree = store.getState().createWorktree + const args: Parameters = ['repo1', 'nautilus'] + args[25] = { nameWasGenerated: true } + + await createWorktree(...args) + + expect(runtimeEnvironmentCall).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'worktree.create', + params: expect.objectContaining({ nameWasGenerated: true }) + }) + ) + }) + it('persists Jira item and source context through paired-runtime create', async () => { const store = createTestStore() const wt = makeWorktree({ diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 7443b8160081..8ba5b2881ba0 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -109,6 +109,7 @@ import { folderWorkspaceToWorktree } from '../../../../shared/folder-workspace-w import { CLIENT_WORKTREE_CREATE_MAX_ATTEMPTS, getClientWorktreeCreateCandidate, + getGeneratedWorktreeCreateRetryCandidate, isRetryableWorktreeCreateConflict } from '../../../../shared/new-workspace/worktree-create-retry-policy' import { @@ -3941,7 +3942,9 @@ export const createWorktreeSlice: StateCreator const provisionedRoot = options?.provisionedRoot try { for (let attempt = 0; attempt < CLIENT_WORKTREE_CREATE_MAX_ATTEMPTS; attempt += 1) { - const candidateName = getClientWorktreeCreateCandidate(name, attempt) + const candidateName = options?.nameWasGenerated + ? getGeneratedWorktreeCreateRetryCandidate(name, attempt) + : getClientWorktreeCreateCandidate(name, attempt) // Why: older runtimes reject exact PR branch overrides on collision, so retry both branch and worktree names. const candidateBranchNameOverride = branchNameOverride ? getClientWorktreeCreateCandidate(branchNameOverride, attempt) @@ -4020,6 +4023,7 @@ export const createWorktreeSlice: StateCreator { repo: repoId, name: candidateName, + ...(options?.nameWasGenerated ? { nameWasGenerated: true } : {}), baseBranch, ...(compareBaseRef ? { compareBaseRef } : {}), ...(candidateBranchNameOverride diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 03370a86fe61..21a093f43bd7 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -430,6 +430,7 @@ export function getDefaultPersistedState(homedir: string): PersistedState { folderWorkspaces: [], sparsePresetsByRepo: {}, retiredWorktreeNamesByRepo: {}, + retiredWorktreeNamesByNamespace: {}, worktreeMeta: {}, worktreeLineageById: {}, workspaceLineageByChildKey: {}, diff --git a/src/shared/new-workspace/worktree-create-retry-policy.test.ts b/src/shared/new-workspace/worktree-create-retry-policy.test.ts index 47cc5e79ee6b..e10ba3e9ddfb 100644 --- a/src/shared/new-workspace/worktree-create-retry-policy.test.ts +++ b/src/shared/new-workspace/worktree-create-retry-policy.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { getClientWorktreeCreateCandidate, + getGeneratedWorktreeCreateRetryCandidate, isRetryableWorktreeCreateConflict } from './worktree-create-retry-policy' @@ -10,6 +11,12 @@ describe('client worktree create retry policy', () => { expect(getClientWorktreeCreateCandidate('feature', 1)).toBe('feature-2') }) + it('keeps generated retries on canonical tiers', () => { + expect(getGeneratedWorktreeCreateRetryCandidate('nautilus-2', 0)).toBe('nautilus-2') + expect(getGeneratedWorktreeCreateRetryCandidate('nautilus-2', 1)).toBe('nautilus-3') + expect(getGeneratedWorktreeCreateRetryCandidate('nautilus-2-3', 0)).toBe('nautilus-4') + }) + it('retries only known branch and review conflicts', () => { expect(isRetryableWorktreeCreateConflict('Branch already exists locally')).toBe(true) expect(isRetryableWorktreeCreateConflict('Branch "x" already exists.')).toBe(true) diff --git a/src/shared/new-workspace/worktree-create-retry-policy.ts b/src/shared/new-workspace/worktree-create-retry-policy.ts index 295dd3c78395..e45da0d5530d 100644 --- a/src/shared/new-workspace/worktree-create-retry-policy.ts +++ b/src/shared/new-workspace/worktree-create-retry-policy.ts @@ -1,3 +1,9 @@ +import { + CREATURE_POOL_NAMES, + creatureNameAtTier, + creatureNameTier +} from '../worktree/retired-name-registry' + export const CLIENT_WORKTREE_CREATE_MAX_ATTEMPTS = 25 // Why: mixed-version runtimes can still return these legacy conflicts instead @@ -13,6 +19,49 @@ export function getClientWorktreeCreateCandidate(value: string, attempt: number) return attempt === 0 ? value : `${value}-${attempt + 1}` } +function generatedNameIdentity(value: string): { poolName: string; tier: number } | null { + const normalized = value.trim().toLowerCase() + const canonicalTier = creatureNameTier(normalized) + if (canonicalTier !== null) { + const poolName = + canonicalTier === 1 ? normalized : normalized.slice(0, normalized.lastIndexOf('-')) + return { poolName, tier: canonicalTier } + } + let poolName = normalized + let tier = 1 + let suffixCount = 0 + for (;;) { + const match = /-(\d{1,6})$/.exec(poolName) + if (!match) { + break + } + const suffix = Number(match[1]) + if (suffix < 2 || tier + suffix - 1 > 999_999) { + return null + } + tier += suffix - 1 + suffixCount += 1 + poolName = poolName.slice(0, match.index) + } + return suffixCount > 1 && CREATURE_POOL_NAMES.has(poolName) ? { poolName, tier } : null +} + +export function isGeneratedWorktreeCreateName(value: string): boolean { + return generatedNameIdentity(value) !== null +} + +export function getGeneratedWorktreeCreateRetryCandidate( + value: string, + attempt: number, + minimumTier = 1 +): string { + const identity = generatedNameIdentity(value) + if (!identity) { + return getClientWorktreeCreateCandidate(value, attempt) + } + return creatureNameAtTier(identity.poolName, Math.max(identity.tier, minimumTier) + attempt) +} + export function isRetryableWorktreeCreateConflict(message: string): boolean { return RETRYABLE_WORKTREE_CREATE_CONFLICT_PATTERNS.some((pattern) => pattern.test(message)) } diff --git a/src/shared/persisted-state-types.ts b/src/shared/persisted-state-types.ts index c66c335188c8..ee6d1f97fa70 100644 --- a/src/shared/persisted-state-types.ts +++ b/src/shared/persisted-state-types.ts @@ -67,12 +67,13 @@ export type PersistedState = { /** Generated workspace names already issued, keyed by repoId. Suppresses reissuing a name so a * recreated workspace never lands on a prior occupant's path and inherits agent state keyed to * that cwd. Grows monotonically within a repo — entries are never removed on workspace deletion - * — and is dropped wholesale when the repo is removed. Readers union across every repo that - * creates into the same cwd namespace, so the storage key stays the stable repo id while the - * guarantee follows the path. + * — and the repo-keyed copy is dropped when the repo is removed. Readers union across repos + * that create into the same cwd namespace; remote namespaces also retain a compact tombstone. * * Stored compacted, not as a flat list: a fully spent tier collapses into the row's watermark. */ retiredWorktreeNamesByRepo?: Record + /** Compacted remote cwd tombstones outlive repo ids, so remove/re-add cannot reissue a path. */ + retiredWorktreeNamesByNamespace?: Record /** Per paired device last tab selection by worktree; keeps mobile navigation across host restarts. */ mobileClientTabSelectionsByDeviceId?: PersistedMobileClientTabSelections worktreeMeta: Record