diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 1941c75a1b46..b05127389f22 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, @@ -198,6 +199,18 @@ 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. + // 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) @@ -611,7 +624,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) { @@ -665,6 +680,9 @@ 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, setupDecision, 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..d14f186a2f21 --- /dev/null +++ b/mobile/src/components/worktree-name-suggestion.test.ts @@ -0,0 +1,68 @@ +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() +const retiring = (...names: string[]) => ({ exhaustedTiers: 0, names }) + +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, retiring(MARINE_CREATURES[0]))).toBe(lower(1)) + }) + + it('treats retired names case-insensitively', () => { + 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, + 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, 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', () => { + // 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..701f66959e13 100644 --- a/mobile/src/components/worktree-name-suggestion.ts +++ b/mobile/src/components/worktree-name-suggestion.ts @@ -1,55 +1,36 @@ -import { MARINE_CREATURES } from '../../../src/shared/marine-creatures' +import { + normalizeSuggestedName, + selectSuggestedCreatureName, + suggestionPathBasename +} from '../../../src/shared/worktree-name-suggestion' +import { + EMPTY_RETIRED_NAME_REGISTRY, + type RetiredNameRegistry +} from '../../../src/shared/worktree/retired-name-registry' -// 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. +/** `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 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 + random: () => number = Math.random, + retired: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY ): 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 retired.names) { + used.add(normalizeSuggestedName(retiredName)) } + return selectSuggestedCreatureName(used, random, retired.exhaustedTiers) } 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 6b6da283dcc4..d81d75d5a694 100644 --- a/mobile/src/tasks/blank-workspace-create.ts +++ b/mobile/src/tasks/blank-workspace-create.ts @@ -16,17 +16,22 @@ 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({ client: args.client, baseName: args.baseName, + nameWasGenerated: args.nameWasGenerated, supportsIdempotentCutoverRetry: args.supportsIdempotentCutoverRetry, buildParams: (name) => { const params: Record = { repo: `id:${args.repoId}`, setupDecision: args.setupDecision, name, + ...(args.nameWasGenerated ? { nameWasGenerated: true } : {}), ...agentLaunchCreateFields(args.createdWithAgentId) } if (args.comment) { 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/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..9258e5308074 --- /dev/null +++ b/mobile/src/worktree/use-retired-worktree-names.test.tsx @@ -0,0 +1,143 @@ +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 } + +/** 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: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY + + 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 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, + retiredNameTiersByRepo: Record = {} + ) { + await act(async () => { + pending[index]!.resolve({ result: { retiredNamesByRepo, retiredNameTiersByRepo } }) + 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.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 + // 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 new file mode 100644 index 000000000000..13252c639c36 --- /dev/null +++ b/mobile/src/worktree/use-retired-worktree-names.ts @@ -0,0 +1,53 @@ +import { useEffect, useState } from 'react' +import { + readRetiredNameRegistryForRepo, + retiredNamesAfterRefresh, + 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. + * + * 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 asks for exactly that. + * + * `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, + refreshKey: unknown +): RetiredNameRegistry { + const [loaded, setLoaded] = useState(null) + const activeRepoId = client && repoId ? repoId : null + + useEffect(() => { + if (!client || !activeRepoId) { + setLoaded(null) + return + } + let cancelled = false + const settle = (registry: RetiredNameRegistry | null): void => { + if (!cancelled) { + setLoaded((previous) => retiredNamesAfterRefresh(previous, activeRepoId, registry)) + } + } + void client + .sendRequest('worktree.listRetiredNames', { repo: `id:${activeRepoId}` }) + .then((response) => + settle( + readRetiredNameRegistryForRepo((response as { result?: unknown }).result, activeRepoId) + ) + ) + .catch(() => settle(null)) + return () => { + cancelled = true + } + }, [activeRepoId, client, refreshKey]) + + return selectRetiredNameRegistry(loaded, activeRepoId) +} 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 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 e20609d3a4cb..1f96523899ec 100644 --- a/src/main/git/worktree.ts +++ b/src/main/git/worktree.ts @@ -1096,7 +1096,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-logic.ts b/src/main/ipc/worktree-logic.ts index 5e3878924f27..a98133428a2e 100644 --- a/src/main/ipc/worktree-logic.ts +++ b/src/main/ipc/worktree-logic.ts @@ -5,7 +5,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 @@ -113,6 +113,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/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index d4d91dcd79be..0896ae0a0da8 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -136,9 +136,17 @@ import { } from '../project-runtime-git-options' import { getBranchNameOverrideCandidate, + getGeneratedWorktreeCreateCandidate, getWorktreeCreateCandidate, + isGeneratedWorktreeCreateName, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' +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 const SSH_WORKTREE_CREATE_FETCH_CACHE_MAX = 512 @@ -1554,12 +1562,30 @@ export async function createRemoteWorktree( let selectedExistingLocalBranchName: string | null = null let lastBranchConflictKind: 'local' | 'remote' | null = null let remotePathResolved = false + 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, @@ -1739,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) @@ -2093,12 +2138,30 @@ export async function createLocalWorktree( let lastBranchConflictKind: 'local' | 'remote' | null = null let lastExistingPR: Awaited> | null = null let lastExistingReviewNumber: number | null = null + 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( @@ -2270,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) { diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index 692c2ea6d511..995c60318959 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> @@ -159,7 +160,10 @@ describe('registerWorktreeHandlers – Windows path handling', () => { getSettings: vi.fn(), getWorktreeMeta: vi.fn(), setWorktreeMeta: vi.fn(), - removeWorktreeMeta: vi.fn() + removeWorktreeMeta: vi.fn(), + addRetiredWorktreeName: vi.fn(), + getRetiredWorktreeNameRegistry: vi.fn(), + mergeRetiredWorktreeNames: vi.fn() } beforeEach(() => { @@ -201,6 +205,10 @@ describe('registerWorktreeHandlers – Windows path handling', () => { store.getWorktreeMeta.mockReset() store.setWorktreeMeta.mockReset() store.removeWorktreeMeta.mockReset() + store.addRetiredWorktreeName.mockReset() + store.getRetiredWorktreeNameRegistry.mockReset() + store.mergeRetiredWorktreeNames.mockReset() + resetRetirementCollisionKeyCacheForTests() for (const key of Object.keys(handlers)) { delete handlers[key] @@ -237,6 +245,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) resolveSetupRunnerShellMock.mockReturnValue(undefined) store.getWorktreeMeta.mockReturnValue(undefined) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: [] }) store.setWorktreeMeta.mockReturnValue({}) resolveLocalGitUsernameMock.mockResolvedValue('') getDefaultBaseRefMock.mockReturnValue('origin/main') @@ -303,6 +312,8 @@ describe('registerWorktreeHandlers – Windows path handling', () => { false ) expect(resolveLocalGitUsernameMock).not.toHaveBeenCalled() + // 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({ @@ -318,6 +329,57 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) }) + it('skips a retired generated name when the physical leaf is decorated', async () => { + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['nautilus'] }) + computeWorktreePathMock.mockReturnValue('C:\\workspaces\\repo-nautilus-2') + ensurePathWithinWorkspaceMock.mockReturnValue('C:\\workspaces\\repo-nautilus-2') + listWorktreesMock.mockResolvedValue([ + { + path: 'C:/workspaces/repo-nautilus-2', + head: 'abc123', + branch: 'refs/heads/nautilus-2', + isBare: false, + isMainWorktree: false + } + ]) + + await handlers['worktrees:create'](null, { + repoId: 'repo-1', + name: 'nautilus', + nameWasGenerated: true + }) + + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-1', '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.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['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(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 () => { store.getSettings.mockReturnValue({ branchPrefix: 'git-username', diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index b9ea11b85c8b..b7608eef09a7 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -315,6 +315,7 @@ import { registerWorktreeHandlers } from './worktrees' import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../git/worktree-shared-directories' +import { resetRetirementCollisionKeyCacheForTests } from '../worktree-name-retirement' import { getSshProviderAuthority, resetSshProviderAuthorities, @@ -349,7 +350,10 @@ describe('registerWorktreeHandlers', () => { removeWorktreeLineage: vi.fn(), getAllWorkspaceLineage: vi.fn(), getFolderWorkspaces: vi.fn(), - getProjectGroups: vi.fn() + getProjectGroups: vi.fn(), + addRetiredWorktreeName: vi.fn(), + getRetiredWorktreeNameRegistry: vi.fn(), + mergeRetiredWorktreeNames: vi.fn() } let runtimeStub: { resolveRemoteTrackingBase: ReturnType @@ -433,6 +437,9 @@ describe('registerWorktreeHandlers', () => { store.getAllWorkspaceLineage, store.getFolderWorkspaces, store.getProjectGroups, + store.addRetiredWorktreeName, + store.getRetiredWorktreeNameRegistry, + store.mergeRetiredWorktreeNames, killAllProcessesForWorktreeMock, clearProviderPtyStateMock, getLocalPtyProviderMock, @@ -486,6 +493,8 @@ describe('registerWorktreeHandlers', () => { }) store.getWorktreeMeta.mockReturnValue(undefined) store.getAllWorktreeMeta.mockReturnValue({}) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: [] }) + resetRetirementCollisionKeyCacheForTests() store.setWorktreeMeta.mockReturnValue({}) store.getProjectHostSetups.mockReturnValue([ { @@ -4722,9 +4731,9 @@ describe('registerWorktreeHandlers', () => { isMainWorktree: true }, { - path: '/remote/repo-improve-dashboard', + path: '/remote/repo-nautilus-2', head: 'abc123', - branch: 'refs/heads/improve-dashboard', + branch: 'refs/heads/nautilus-2', isBare: false, isMainWorktree: false } @@ -4739,11 +4748,13 @@ describe('registerWorktreeHandlers', () => { store.getRepo.mockReturnValue(repo) getSshGitProviderMock.mockReturnValue(provider) getActiveMultiplexerMock.mockReturnValue(mux) + store.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['nautilus'] }) store.setWorktreeMeta.mockImplementation((_worktreeId, meta) => meta) const result = await handlers['worktrees:create'](null, { repoId: 'repo-ssh', - name: 'improve-dashboard', + name: 'nautilus', + nameWasGenerated: true, linkedIssue: 123, linkedPR: 456, createdWithAgent: 'codex', @@ -4761,8 +4772,9 @@ describe('registerWorktreeHandlers', () => { ) expect(provider.listWorktrees).toHaveBeenCalledTimes(1) expect(provider.worktreeIsClean).not.toHaveBeenCalled() + expect(store.addRetiredWorktreeName).toHaveBeenCalledWith('repo-ssh', 'nautilus-2') expect(store.setWorktreeMeta).toHaveBeenCalledWith( - 'repo-ssh::/remote/repo-improve-dashboard', + 'repo-ssh::/remote/repo-nautilus-2', expect.objectContaining({ linkedIssue: 123, linkedPR: 456, @@ -4782,6 +4794,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.getRetiredWorktreeNameRegistry.mockReturnValue({ exhaustedTiers: 0, names: ['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', @@ -5679,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', @@ -5698,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), @@ -8213,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 f85e0fad8bae..113d68605729 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -121,6 +121,8 @@ import { isOrphanCompatiblePreflightError, isOrphanedWorktreeError } from './worktree-logic' +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' import { @@ -1846,6 +1848,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') @@ -1933,6 +1936,14 @@ export function registerWorktreeHandlers( return results.flat() }) + ipcMain.handle('worktrees:listRetiredNames', async (_event, args: { repoId: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo) { + return EMPTY_RETIRED_NAME_REGISTRY + } + return getRetiredNameRegistryForRepo(store, repo, store.getRepos(), store.getSettings()) + }) + ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { const repo = store.getRepo(args.repoId) if (!repo) { 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-source-removal.ts b/src/main/orca-profiles/profile-project-source-removal.ts index c698491eb19d..37480164ebca 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 f7dedcff1798..5c623f19bad0 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,6 +44,12 @@ export function readProfileState(profileId: string, userDataPath: string): Trans projectGroups: arrayOrEmpty(parsed.projectGroups), folderWorkspaces: arrayOrEmpty(parsed.folderWorkspaces), sparsePresetsByRepo: recordOrEmpty(parsed.sparsePresetsByRepo), + 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 de7c8b73171d..b2f74fd36091 100644 --- a/src/main/orca-profiles/profile-project-transfer-payload.ts +++ b/src/main/orca-profiles/profile-project-transfer-payload.ts @@ -6,7 +6,11 @@ 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 { parseWorkspaceKey } from '../../shared/workspace-scope' +import type { RetiredNameRegistry } from '../../shared/worktree/retired-name-registry' +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' @@ -14,15 +18,16 @@ 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 sparsePresets: SparsePreset[] + /** 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'] @@ -60,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, @@ -217,6 +142,11 @@ export function createTransferPayload(args: { ...structuredClone(preset), repoId: newRepoId })), + retiredNameRegistry: sourceState.retiredWorktreeNamesByRepo?.[oldRepoId], + retiredNameRegistriesByNamespace: extractRetiredNameRegistriesByNamespace( + sourceState, + sourceRepo + ), worktreeMeta: rekeyWorktreeIdRecord( sourceState.worktreeMeta, worktreeIds, @@ -272,6 +202,15 @@ export function applyPayloadToTarget( ...targetState.sparsePresetsByRepo, ...(payload.sparsePresets.length > 0 ? { [payload.repo.id]: payload.sparsePresets } : {}) }, + retiredWorktreeNamesByRepo: { + ...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 }, workspaceLineageByChildKey: { 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 ecb61684d62a..60973c975296 100644 --- a/src/main/orca-profiles/profile-project-transfer.test.ts +++ b/src/main/orca-profiles/profile-project-transfer.test.ts @@ -128,6 +128,10 @@ 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' }) }, @@ -179,6 +183,13 @@ 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({ + exhaustedTiers: 0, + names: ['nautilus'] + }) + expect(target.retiredWorktreeNamesByNamespace).toEqual({}) expect(target.workspaceSession.tabsByWorktree).toEqual({}) expect(readProfileState('personal').repos.map((repo) => repo.id)).toEqual(['repo-1']) }) @@ -204,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' }) }, @@ -259,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 new file mode 100644 index 000000000000..2554abcd16c2 --- /dev/null +++ b/src/main/persistence-worktree-name-retirement.test.ts @@ -0,0 +1,299 @@ +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' +import { MARINE_CREATURES } from '../shared/marine-creatures' +import { createRetiredNameLookup } from '../shared/worktree/retired-name-registry' + +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' +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 }) + writeFileSync( + join(testState.dir, 'orca-data.json'), + JSON.stringify({ ...getDefaultPersistedState(testState.dir), ...persisted }), + 'utf-8' + ) + return reloadStore() +} + +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.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.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.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.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.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.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.getRetiredWorktreeNameRegistry(REPO).names].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.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.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.getRetiredWorktreeNameRegistry(REPO).names].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.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 }) + 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.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) + + store.removeProjectForHost(REPO, 'local') + + 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('rolls the watermark through every tier that is already complete', async () => { + const store = await createStore() + 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, + POOL.map((name) => (tier === 1 ? name : `${name}-${tier}`)) + ) + } + + 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.getRetiredWorktreeNameRegistry(REPO).names).toEqual(['nautilus']) + }) +}) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 99829912f2e2..253ea79ef1a2 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -174,6 +174,15 @@ import { pruneAutomationRuns } 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, @@ -2323,6 +2332,49 @@ 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: 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 normalizeRetiredNameRegistryMap(value: unknown): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return {} + } + const byRepo: Record = {} + for (const [repoId, row] of Object.entries(value as Record)) { + if (!repoId) { + continue + } + const registry = normalizeRetiredNameRegistry(row) + if (!isEmptyRetiredNameRegistry(registry)) { + byRepo[repoId] = registry + } + } + return byRepo +} + function normalizeClaudeLivePtySessionIds(value: unknown): string[] { if (!Array.isArray(value)) { return [] @@ -3813,6 +3865,12 @@ export class Store { (alias): alias is string => typeof alias === 'string' ) : [], + retiredWorktreeNamesByRepo: normalizeRetiredNameRegistryMap( + parsed.retiredWorktreeNamesByRepo + ), + retiredWorktreeNamesByNamespace: normalizeRetiredNameRegistryMap( + parsed.retiredWorktreeNamesByNamespace + ), sshRemotePtyLeases: (parsed.sshRemotePtyLeases ?? []) .map(normalizeSshRemotePtyLease) .filter((lease): lease is SshRemotePtyLease => lease !== null), @@ -4847,6 +4905,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( @@ -4862,9 +4922,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). @@ -7197,6 +7259,83 @@ export class Store { this.scheduleSave() } + /** 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 + } + + 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 { + const normalized = normalizeRetirableGeneratedName(name) + if (!repoId || !normalized) { + return + } + this.applyRetiredWorktreeNames(repoId, [normalized]) + } + + /** 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 = normalizeRetirableGeneratedName(name) + if (normalized) { + incoming.add(normalized) + } + } + 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) { + return false + } + this.state.retiredWorktreeNamesByRepo ??= {} + this.state.retiredWorktreeNamesByRepo[repoId] = next + this.scheduleSave() + return true + } + getDeletedSshConfigAliases(): string[] { return [...(this.state.deletedSshConfigAliases ?? [])] } diff --git a/src/main/runtime/fit-override-integration.test.ts b/src/main/runtime/fit-override-integration.test.ts index 9bcfa8706143..df3742922b5c 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: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + 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 5f846fee2d7d..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,6 +54,9 @@ const storeBase = { getGitHubCache: () => ({ pr: {}, issue: {} }), setWorktreeMeta: () => undefined as never, removeWorktreeMeta: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + 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 fdf0bce733c1..5a76d5e72ad3 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: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + 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..8ec53b399ed8 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: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + 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..f055c47e8274 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: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + 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 18cd130e7d81..dd3b04b3a801 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() @@ -1383,6 +1388,9 @@ const store = { addedAt: 1 } ], + addRetiredWorktreeName: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + mergeRetiredWorktreeNames: () => false, addRepo: () => {}, updateRepo: (id: string, updates: Record) => ({ @@ -4344,12 +4352,22 @@ 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, + getRetiredWorktreeNameRegistry: () => ({ + exhaustedTiers: 0, + names: Array.from({ length: 100 }, (_unused, index) => + index === 0 ? 'nautilus' : `nautilus-${index + 1}` + ) + }) + }) const staleScan = deferred() const createdWorktree = { - path: '/tmp/workspaces/cache-race', + path: '/tmp/workspaces/repo-nautilus-101', head: 'def', - branch: 'cache-race', + branch: 'nautilus-101', isBare: false, isMainWorktree: false } @@ -4363,7 +4381,8 @@ describe('OrcaRuntimeService', () => { const staleLookup = runtime.showManagedWorktree(TEST_WORKTREE_ID) const result = await runtime.createManagedWorktree({ repoSelector: 'id:repo-1', - name: 'cache-race' + name: 'nautilus', + nameWasGenerated: true }) const freshLookup = runtime.showManagedWorktree(result.worktree.id) @@ -4379,6 +4398,77 @@ describe('OrcaRuntimeService', () => { worktrees: expect.arrayContaining([expect.objectContaining({ path: createdWorktree.path })]) } ) + 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 () => { + // Why: the pool contains ordinary words. Retirement only ever applies to generated names. + const addRetiredWorktreeName = vi.fn() + const runtime = new OrcaRuntimeService({ + ...store, + addRetiredWorktreeName, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: ['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 () => { @@ -44972,12 +45062,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 } @@ -45007,6 +45097,7 @@ describe('OrcaRuntimeService', () => { defaultTuiAgent: null, agentCmdOverrides: {} }), + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: ['nautilus'] }), getAllWorktreeMeta: () => metaById, getWorktreeMeta: (worktreeId: string) => metaById[worktreeId], setWorktreeMeta: (worktreeId: string, meta: Partial) => { @@ -45050,15 +45141,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 @@ -48910,6 +49008,9 @@ describe('OrcaRuntimeService', () => { return nextMeta }, removeWorktreeMeta: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + 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 c350aa355505..554313e08572 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -967,9 +967,20 @@ import { } from '../ipc/worktree-remote' import { getBranchNameOverrideCandidate, + getGeneratedWorktreeCreateCandidate, getWorktreeCreateCandidate, + isGeneratedWorktreeCreateName, WORKTREE_CREATE_MAX_SUFFIX_ATTEMPTS } from '../worktree-create-candidates' +import { + failedWorktreeCreationNeedsRetirement, + getRetiredNameRegistryForRepo, + retireGeneratedWorktreeName +} 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,6 +1157,9 @@ export type CodexRateLimitResetRpcResult = { type RuntimeStore = { getRepos: Store['getRepos'] getRepo: Store['getRepo'] + addRetiredWorktreeName: Store['addRetiredWorktreeName'] + getRetiredWorktreeNameRegistry: Store['getRetiredWorktreeNameRegistry'] + mergeRetiredWorktreeNames: Store['mergeRetiredWorktreeNames'] addRepo: Store['addRepo'] updateRepo: Store['updateRepo'] getProjects?: Store['getProjects'] @@ -21353,6 +21367,35 @@ 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. + * + * 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 { retiredNamesByRepo: {}, retiredNameTiersByRepo: {} } + } + const repo = await this.resolveRepoSelector(repoSelector) + const settings = store.getSettings() + const registry: RetiredNameRegistry = await getRetiredNameRegistryForRepo( + store, + repo, + store.getRepos(), + settings + ) + return { + retiredNamesByRepo: { [repo.id]: registry.names }, + retiredNameTiersByRepo: { [repo.id]: registry.exhaustedTiers } + } + } + async listDetectedManagedWorktrees( repoSelector: string, connectionId?: string | null, @@ -22218,6 +22261,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 @@ -22555,13 +22601,35 @@ export class OrcaRuntimeService { let branchConflictKind: 'local' | 'remote' | null = null let worktreePath = '' let worktreePathResolved = false + 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 ?? @@ -22763,19 +22831,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, @@ -22783,9 +22843,9 @@ export class OrcaRuntimeService { sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) + addProjectGitOptions(existingBranchOption) ) - : remoteTrackingBaseOption + : suggestLocalBaseRefUpdate ? addSparseWorktree( repo.path, worktreePath, @@ -22793,9 +22853,9 @@ export class OrcaRuntimeService { sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - addProjectGitOptions(remoteTrackingBaseOption) + addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) ) - : defaultAddWorktreeOption + : remoteTrackingBaseOption ? addSparseWorktree( repo.path, worktreePath, @@ -22803,27 +22863,27 @@ export class OrcaRuntimeService { sparseDirectories, baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, - defaultAddWorktreeOption + addProjectGitOptions(remoteTrackingBaseOption) ) - : addSparseWorktree( - repo.path, - worktreePath, - branchName, - sparseDirectories, - baseBranch, - settings.refreshLocalBaseRefOnWorktreeCreate - ) - : 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, @@ -22831,9 +22891,9 @@ export class OrcaRuntimeService { baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, false, - addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) + addProjectGitOptions(existingBranchOption) ) - : remoteTrackingBaseOption + : suggestLocalBaseRefUpdate ? addWorktree( repo.path, worktreePath, @@ -22841,9 +22901,9 @@ export class OrcaRuntimeService { baseBranch, settings.refreshLocalBaseRefOnWorktreeCreate, false, - addProjectGitOptions(remoteTrackingBaseOption) + addProjectGitOptions({ ...remoteTrackingBaseOption, suggestLocalBaseRefUpdate }) ) - : defaultAddWorktreeOption + : remoteTrackingBaseOption ? addWorktree( repo.path, worktreePath, @@ -22851,15 +22911,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) { @@ -23328,6 +23409,7 @@ export class OrcaRuntimeService { repo: Repo, args: { name: string + nameWasGenerated?: boolean baseBranch?: string compareBaseRef?: string branchNameOverride?: string @@ -23379,6 +23461,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/runtime/remote-desktop-driver.test.ts b/src/main/runtime/remote-desktop-driver.test.ts index 2a75853b1bee..2ff49c03bf92 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: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getSettings: () => ({ workspaceDir: '/tmp/workspaces', nestWorkspaces: false, diff --git a/src/main/runtime/rpc/methods/worktree-catalog-methods.ts b/src/main/runtime/rpc/methods/worktree-catalog-methods.ts index a5e741fc78ee..2010a219b7c6 100644 --- a/src/main/runtime/rpc/methods/worktree-catalog-methods.ts +++ b/src/main/runtime/rpc/methods/worktree-catalog-methods.ts @@ -35,6 +35,11 @@ export const WORKTREE_CATALOG_METHODS: RpcMethod[] = [ supportsWorktreeVisibilitySourceDefaults(context) ) }), + defineMethod({ + name: 'worktree.listRetiredNames', + params: WorktreeDetectedListParams, + handler: async (params, { runtime }) => runtime.listRetiredWorktreeNames(params.repo) + }), defineMethod({ name: 'worktree.detectedList', params: WorktreeDetectedListParams, 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-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-schemas.ts b/src/main/runtime/rpc/methods/worktree-schemas.ts index 794289387051..2b3292241283 100644 --- a/src/main/runtime/rpc/methods/worktree-schemas.ts +++ b/src/main/runtime/rpc/methods/worktree-schemas.ts @@ -105,6 +105,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 1ff3732ea3fd..88f3b87a324f 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 { resolveRuntimeNavigationTarget } from '../../../../shared/runtime-navigation' import { resolveRpcWorkspaceCreatorProvenance } from '../workspace-creator-context' import { @@ -89,66 +90,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. diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 14c69ceb960e..3759ac356c1d 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -430,6 +430,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/runtime/terminal-query-responder.test.ts b/src/main/runtime/terminal-query-responder.test.ts index cdcd10dfbc34..9db883529a00 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: () => {}, + getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }), + addRetiredWorktreeName: () => {}, + mergeRetiredWorktreeNames: () => false, getGitHubCache: () => ({ pr: {}, issue: {} }) as never, getSettings: () => ({ workspaceDir: '/tmp/workspaces', diff --git a/src/main/window/renderer-document-navigation.test.ts b/src/main/window/renderer-document-navigation.test.ts index 62538b597151..8e4a1fee2088 100644 --- a/src/main/window/renderer-document-navigation.test.ts +++ b/src/main/window/renderer-document-navigation.test.ts @@ -45,22 +45,17 @@ describe('renderer document navigation', () => { it('cancels only the matching main-frame provisional navigation', () => { const cancel = vi.fn() - const fixture = createFixture('http://localhost:5173/', vi.fn(() => cancel)) + const fixture = createFixture( + 'http://localhost:5173/', + vi.fn(() => cancel) + ) fixture.navigate?.({}, 'http://localhost:5173/reload', false, true) fixture.failProvisionalLoad?.({}, -3, 'aborted', 'other', true, 1, 1) fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload', false, 1, 1) expect(cancel).not.toHaveBeenCalled() - fixture.failProvisionalLoad?.( - {}, - -3, - 'aborted', - 'http://localhost:5173/reload', - true, - 1, - 1 - ) + fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload', true, 1, 1) expect(cancel).toHaveBeenCalledOnce() }) @@ -73,31 +68,18 @@ describe('renderer document navigation', () => { fixture.navigate?.({}, 'http://localhost:5173/reload-b', false, true) expect(onStarted).toHaveBeenCalledOnce() - fixture.failProvisionalLoad?.( - {}, - -3, - 'aborted', - 'http://localhost:5173/reload-a', - true, - 1, - 1 - ) + fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload-a', true, 1, 1) expect(cancel).not.toHaveBeenCalled() - fixture.failProvisionalLoad?.( - {}, - -3, - 'aborted', - 'http://localhost:5173/reload-b', - true, - 1, - 1 - ) + fixture.failProvisionalLoad?.({}, -3, 'aborted', 'http://localhost:5173/reload-b', true, 1, 1) expect(cancel).toHaveBeenCalledOnce() }) it('does not cancel a navigation after its document commits', () => { const cancel = vi.fn() - const fixture = createFixture('file:///opt/orca/renderer/index.html', vi.fn(() => cancel)) + const fixture = createFixture( + 'file:///opt/orca/renderer/index.html', + vi.fn(() => cancel) + ) fixture.navigate?.({}, 'file:///opt/orca/renderer/index.html?reload=1', false, true) fixture.commitNavigation?.( @@ -124,7 +106,10 @@ describe('renderer document navigation', () => { it('cancels when a later will-navigate listener blocks the navigation', async () => { const cancel = vi.fn() - const fixture = createFixture('http://localhost:5173/', vi.fn(() => cancel)) + const fixture = createFixture( + 'http://localhost:5173/', + vi.fn(() => cancel) + ) const event = { defaultPrevented: false } fixture.navigate?.({}, 'http://localhost:5173/reload', false, true) 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 new file mode 100644 index 000000000000..8a0e8237cafe --- /dev/null +++ b/src/main/worktree-name-retirement.test.ts @@ -0,0 +1,339 @@ +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 } from '../shared/global-settings-types' +import type { Repo } from '../shared/repo-types' +import { + collectRetiredNamesFromLeafNames, + discoverRetiredWorktreeNames, + ensureRetiredWorktreeNamesBackfilled, + extractBucketLeafCandidates, + getRetiredNameRegistryForRepo, + normalizeRetirableGeneratedName, + resetRetirementCollisionKeyCacheForTests +} from './worktree-name-retirement' + +const FIRST = MARINE_CREATURES[0].toLowerCase() +const SECOND = MARINE_CREATURES[1].toLowerCase() + +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 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() + }) + + 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() + }) +}) + +describe('extractBucketLeafCandidates', () => { + it('takes everything past the encoded parent as the leaf', () => { + expect(extractBucketLeafCandidates(`-w-orca-${FIRST}`, ['-w-orca'])).toEqual([FIRST]) + }) + + 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('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('yields nothing for the parent bucket itself', () => { + expect(extractBucketLeafCandidates('-w-orca', ['-w-orca'])).toEqual([]) + }) +}) + +describe('collectRetiredNamesFromLeafNames', () => { + it('keeps pool names and drops everything else', () => { + expect(collectRetiredNamesFromLeafNames([FIRST, SECOND, 'fix-login'])).toEqual( + new Set([FIRST, SECOND]) + ) + }) + + 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('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({ + workspaceRoots: ['/Users/ada/.orca/worktrees'], + home, + env: {} + }) + expect(retired).toEqual(new Set([FIRST])) + }) + }) + + 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('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('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 }) + } + }) + }) + + 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('getRetiredNameRegistryForRepo', () => { + const settingsFor = (nestWorkspaces: boolean): GlobalSettings => + ({ workspaceDir: '/workspaces', nestWorkspaces }) as GlobalSettings + const storeOf = (byRepo: Record) => { + const calls: string[] = [] + return { + calls, + mergeRetiredWorktreeNames: () => false, + getRetiredWorktreeNameRegistry: (repoId: string) => { + calls.push(repoId) + return { exhaustedTiers: 0, names: byRepo[repoId] ?? [] } + } + } + } + + 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( + [ + ...(await getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(false))).names + ].sort() + ).toEqual([FIRST, SECOND].sort()) + }) + + 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(await getRetiredNameRegistryForRepo(store, repos[1], repos, settingsFor(true))).toEqual({ + exhaustedTiers: 0, + names: [SECOND] + }) + }) + + 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) + return Object.defineProperty(repo, 'path', { + get: () => { + pathReads.push(id) + return path + } + }) as Repo + } + const store = storeOf({ 'repo-a': [FIRST] }) + const repos = [ + spyRepo('repo-a', '/repos/a'), + ...Array.from({ length: 20 }, (_unused, index) => spyRepo(`peer-${index}`, `/repos/${index}`)) + ] + + 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', async () => { + const store = storeOf({ folder: [FIRST] }) + const folderRepo = { ...makeRepo('folder', '/repos/folder'), kind: 'folder' as const } + + expect( + (await getRetiredNameRegistryForRepo(store, folderRepo, [folderRepo], settingsFor(false))) + .names + ).toEqual([]) + }) +}) + +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: { repoId: string; names: string[] }[] = [] + const store = { + mergeRetiredWorktreeNames: (repoId: string, names: Iterable) => { + merged.push({ repoId, names: [...names] }) + return true + } + } + const settings = { workspaceDir: workspaceRoot, nestWorkspaces: false } + + try { + await ensureRetiredWorktreeNamesBackfilled(store, makeRepo('repo-a', '/repos/a'), settings) + expect(merged).toEqual([{ repoId: 'repo-a', names: [FIRST] }]) + + // 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).toEqual([ + { repoId: 'repo-a', names: [FIRST] }, + { repoId: 'repo-b', names: [FIRST] } + ]) + } 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: (_repoId: 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 new file mode 100644 index 000000000000..53ac593011d6 --- /dev/null +++ b/src/main/worktree-name-retirement.ts @@ -0,0 +1,318 @@ +import { readdir } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' +import { getRepoExecutionHostId } from '../shared/execution-host' +import { + creatureNameTier, + 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' +import { + encodeClaudeProjectPaths, + isClaudeProjectDirInScope +} from './ai-vault/claude-project-dir-encoding' +import { + computeRemoteWorktreePath, + computeWorktreePathAsync, + getWorktreePathSettings, + hasRepoWorktreeBasePath +} from './ipc/worktree-logic' +import { worktreePathComparisonKey } from './ipc/worktree-path-comparison' +import { hasCachedWslHome, parseWslPath } from './wsl' + +const RETIREMENT_PROBE_NAME = 'orca-retirement-probe' +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 + +/** 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() + 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 + * agent history is still on disk. So this matches generously and never tries to be exact. */ +export function collectRetiredNamesFromLeafNames(leafNames: Iterable): Set { + const retired = new Set() + for (const leafName of leafNames) { + if (typeof leafName !== 'string' || leafName.length === 0) { + continue + } + 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 [] +} + +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) + }) + : computeWorktreePathAsync(RETIREMENT_PROBE_NAME, repo.path, pathSettings) +} + +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() + +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. */ +async function getRetirementCollisionKey( + repo: Repo, + settings: RetirementPathSettings +): Promise { + 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 = + 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) + if (wsl && !hasCachedWslHome(wsl.distro)) { + return key + } + if (collisionKeyCache.size >= COLLISION_KEY_CACHE_MAX) { + collisionKeyCache.clear() + } + collisionKeyCache.set(cacheKey, key) + 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. */ +export async function getRetiredNameRegistryForRepo( + store: RetirementReadStore & RetirementBackfillStore, + repo: Repo, + repos: readonly Repo[], + settings: RetirementPathSettings +): Promise { + if (isFolderRepo(repo)) { + return EMPTY_RETIRED_NAME_REGISTRY + } + 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 + } + const candidateRegistry = store.getRetiredWorktreeNameRegistry(candidate.id) + if (isEmptyRetiredNameRegistry(candidateRegistry)) { + continue + } + collisionKey ??= await getRetirementCollisionKey(repo, settings) + if ((await getRetirementCollisionKey(candidate, settings)) !== collisionKey) { + continue + } + registry = mergeRetiredNameRegistries(registry, candidateRegistry) + } + 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('\\')) + return separatorIndex < 0 ? '' : trimmed.slice(0, separatorIndex) +} + +/** 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 +): 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 null + } + 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) + } + let scan = storeScans.get(scanKey) + if (!scan) { + scan = discoverRetiredWorktreeNames({ workspaceRoots: [parentPath(probePath)] }) + storeScans.set(scanKey, scan) + } + // 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 { + 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 [] + } +} + +/** 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 leafNames: string[] = [] + for (const root of args.workspaceRoots) { + 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) + .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)) { + leafNames.push(...extractBucketLeafCandidates(bucket, encodedParents)) + } + } + + return collectRetiredNamesFromLeafNames(leafNames) +} 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)! diff --git a/src/preload/api/worktree-api.ts b/src/preload/api/worktree-api.ts index b6564d3f5db0..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 @@ -42,6 +43,10 @@ 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. 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/preload/index.ts b/src/preload/index.ts index fb87c4f43f9c..9be513fa9809 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -783,6 +783,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..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', () => { @@ -56,6 +57,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, retiring(MARINE_CREATURES[0]))).toBe(lower(1)) + }) + + it('treats retired names case-insensitively', () => { + expect( + getSuggestedCreatureName({}, pickFirst, retiring(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, + retiring(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, retiring(`${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..295137b92225 100644 --- a/src/renderer/src/components/sidebar/worktree-name-suggestions.ts +++ b/src/renderer/src/components/sidebar/worktree-name-suggestions.ts @@ -1,5 +1,12 @@ -import { MARINE_CREATURES } from '@/constants/marine-creatures' -import { basename } from '@/lib/path' +import { + normalizeSuggestedName, + selectSuggestedCreatureName, + suggestionPathBasename +} from '../../../../shared/worktree-name-suggestion' +import { + EMPTY_RETIRED_NAME_REGISTRY, + type RetiredNameRegistry +} from '../../../../shared/worktree/retired-name-registry' type WorktreePathLike = { path: string @@ -11,49 +18,39 @@ 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 } -function pickRandom(items: readonly T[], random: () => number): T { - return items[Math.floor(random() * items.length)] -} - +/** `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 + random: () => number = Math.random, + retired: RetiredNameRegistry = EMPTY_RETIRED_NAME_REGISTRY ): string { const usedNames = collectUsedNames(worktreesByRepo) - - // 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 + for (const retiredName of retired.names) { + usedNames.add(normalizeSuggestedName(retiredName)) } + return selectSuggestedCreatureName(usedNames, random, retired.exhaustedTiers) } 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/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index 1b26a98dfe56..2993d6dc4d4c 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -163,6 +163,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, @@ -1592,9 +1593,19 @@ 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 retiredNamesRefreshKey = useMemo( + () => + (worktreesByRepo[repoId] ?? []) + .map((worktree) => worktree.path) + .sort() + .join('\0'), + [repoId, worktreesByRepo] + ) + const retiredWorktreeNames = useRetiredWorktreeNames(repoId, retiredNamesRefreshKey) const fallbackCreatureName = useMemo( - () => getSuggestedCreatureName(worktreesByRepo), - [worktreesByRepo] + () => getSuggestedCreatureName(worktreesByRepo, undefined, retiredWorktreeNames), + [worktreesByRepo, retiredWorktreeNames] ) const workspaceSeedName = useMemo( () => @@ -3636,6 +3647,12 @@ 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. + // 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' ? smartGitHubResolution.baseBranch @@ -3886,6 +3903,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS { linkedWorkItem: toFolderWorkspaceLinkedTask(submitLinkedWorkItem), linkedTaskSourceContext: taskSourceContext, + nameWasGenerated, ...(!backendStartup && startupPlan?.draftPrompt ? { startupDraft: startupPlan.draftPrompt } : {}) @@ -4034,6 +4052,7 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS sourceIntentBlocksCreate, taskSourceContext, workspaceSeedName, + fallbackCreatureName, isProjectGroupTarget, submitFolderTarget ]) @@ -4170,6 +4189,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 @@ -4502,6 +4523,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 diff --git a/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts new file mode 100644 index 000000000000..16b33fcdc032 --- /dev/null +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.test.ts @@ -0,0 +1,97 @@ +// @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() +const registry = (names: string[], exhaustedTiers = 0) => ({ exhaustedTiers, names }) + +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(registry(['nautilus'])) + const { result, rerender } = renderHook( + ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), + { initialProps: { key: 'a' } } + ) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus']))) + + let resolveSecond: (loaded: ReturnType) => void = () => {} + listRetiredNames.mockReturnValueOnce( + new Promise>((resolve) => { + resolveSecond = resolve + }) + ) + rerender({ key: 'b' }) + + expect(result.current).toEqual(registry(['nautilus'])) + + resolveSecond(registry(['nautilus', 'seahorse'], 1)) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus', 'seahorse'], 1))) + }) + + 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(registry(['nautilus']))) + const first = result.current + + rerender({ key: 'b' }) + + expect(result.current).toBe(first) + }) + + it('drops names when the repo changes rather than showing another repo pool', async () => { + listRetiredNames.mockResolvedValueOnce(registry(['nautilus'])) + const { result, rerender } = renderHook( + ({ repoId }: { repoId: string }) => useRetiredWorktreeNames(repoId, 'key'), + { initialProps: { repoId: 'repo-1' } } + ) + await waitFor(() => expect(result.current).toEqual(registry(['nautilus']))) + + listRetiredNames.mockReturnValueOnce(new Promise(() => {})) + rerender({ repoId: 'repo-2' }) + + expect(result.current).toEqual(registry([])) + }) + + it('keeps previously loaded names when a refresh fails', async () => { + listRetiredNames.mockResolvedValueOnce(registry(['nautilus'])) + const { result, rerender } = renderHook( + ({ key }: { key: string }) => useRetiredWorktreeNames('repo-1', key), + { initialProps: { key: 'a' } } + ) + 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(registry(['nautilus'])) + }) + + it('refetches when the refresh key changes', async () => { + listRetiredNames.mockResolvedValue(registry(['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 new file mode 100644 index 000000000000..32097cde6fb0 --- /dev/null +++ b/src/renderer/src/hooks/useRetiredWorktreeNames.ts @@ -0,0 +1,51 @@ +import { useEffect, useState } from 'react' +import { + retiredNamesAfterRefresh, + 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. + * + * 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. + * + * `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. + * + * 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 +): RetiredNameRegistry { + const [loaded, setLoaded] = useState(null) + + useEffect(() => { + if (!repoId) { + setLoaded(null) + return + } + let cancelled = false + const settle = (registry: RetiredNameRegistry | null): void => { + if (!cancelled) { + setLoaded((previous) => retiredNamesAfterRefresh(previous, repoId, registry)) + } + } + void window.api.worktrees + .listRetiredNames({ repoId }) + .then(settle) + .catch((err) => { + settle(null) + console.warn(`Failed to load retired workspace names for repo ${repoId}:`, err) + }) + return () => { + cancelled = true + } + }, [refreshKey, repoId]) + + return selectRetiredNameRegistry(loaded, repoId) +} diff --git a/src/renderer/src/lib/pending-worktree-creation.ts b/src/renderer/src/lib/pending-worktree-creation.ts index 383657a1afac..173b4e199475 100644 --- a/src/renderer/src/lib/pending-worktree-creation.ts +++ b/src/renderer/src/lib/pending-worktree-creation.ts @@ -63,6 +63,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 535a1870fe80..93cd5cee2e48 100644 --- a/src/renderer/src/lib/worktree-creation-flow.ts +++ b/src/renderer/src/lib/worktree-creation-flow.ts @@ -137,6 +137,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 d97e1994a072..cd06fc82acc9 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -213,6 +213,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 provisionedRoot?: { runtimeId: string executionHostId: ExecutionHostId diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index aeacf05ab216..8245c033a710 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -4905,6 +4905,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({ @@ -6199,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/create/create-worktree.ts b/src/renderer/src/store/slices/worktrees/create/create-worktree.ts index 0ecdbf6bae16..a21207805a96 100644 --- a/src/renderer/src/store/slices/worktrees/create/create-worktree.ts +++ b/src/renderer/src/store/slices/worktrees/create/create-worktree.ts @@ -3,6 +3,7 @@ import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-sli import { CLIENT_WORKTREE_CREATE_MAX_ATTEMPTS, getClientWorktreeCreateCandidate, + getGeneratedWorktreeCreateRetryCandidate, isRetryableWorktreeCreateConflict } from '../../../../../../shared/new-workspace/worktree-create-retry-policy' import { parseWorkspaceKey, folderWorkspaceKey } from '../../../../../../shared/workspace-scope' @@ -61,7 +62,9 @@ export function createCreateWorktree( 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) @@ -77,6 +80,7 @@ export function createCreateWorktree( const createArgs = { repoId, name: candidateName, + ...(options?.nameWasGenerated ? { nameWasGenerated: true } : {}), baseBranch, ...(compareBaseRef ? { compareBaseRef } : {}), ...(candidateBranchNameOverride @@ -139,6 +143,7 @@ export function createCreateWorktree( { repo: repoId, name: candidateName, + ...(options?.nameWasGenerated ? { nameWasGenerated: true } : {}), baseBranch, ...(compareBaseRef ? { compareBaseRef } : {}), ...(candidateBranchNameOverride diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index c908d854c970..6b9414b762ee 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -3621,6 +3621,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([ { @@ -3660,8 +3666,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 580dce653b63..8b331ded24e3 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -65,6 +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 { readRetiredNameRegistryForRepo } from '../../../shared/worktree/retired-name-cache' +import { EMPTY_RETIRED_NAME_REGISTRY } from '../../../shared/worktree/retired-name-registry' import { applyPRBotAuthorOverride, normalizePRBotAuthorOverrides @@ -1798,6 +1800,18 @@ function createWorktreesApi(): NonNullable['worktrees']> { withRuntimeWorktreeOwner(worktree, owned.hostId) ) }, + // 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 { + return readRetiredNameRegistryForRepo( + await callRuntimeResult('worktree.listRetiredNames', { repo: repoId }), + repoId + ) + } catch { + return EMPTY_RETIRED_NAME_REGISTRY + } + }, listDetected: async ({ repoId }) => callRuntimeDetectedWorktrees(repoId), listAll: () => listAllRuntimeWorktrees(), create: async (args) => { @@ -1805,6 +1819,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, diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 9edd051d9a38..21a093f43bd7 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -429,6 +429,8 @@ export function getDefaultPersistedState(homedir: string): PersistedState { projectGroups: [], 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 da8757cae28a..ee6d1f97fa70 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' @@ -63,6 +64,16 @@ 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 within a repo — entries are never removed on workspace deletion + * — 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 diff --git a/src/shared/worktree-name-suggestion.test.ts b/src/shared/worktree-name-suggestion.test.ts new file mode 100644 index 000000000000..9d6cd3607eb3 --- /dev/null +++ b/src/shared/worktree-name-suggestion.test.ts @@ -0,0 +1,83 @@ +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('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) + 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..c2cc2450d5b1 --- /dev/null +++ b/src/shared/worktree-name-suggestion.ts @@ -0,0 +1,65 @@ +import { MARINE_CREATURES } from './marine-creatures' +import { clampExhaustedTiers, creatureNameAtTier } from './worktree/retired-name-registry' + +/** 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. + * + * `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, + exhaustedTiers = 0 +): string { + const used = new Set() + for (const name of usedNames) { + used.add(normalizeSuggestedName(name)) + } + + let tier = clampExhaustedTiers(exhaustedTiers) + 1 + while (true) { + const available = MARINE_CREATURES.map((name) => + creatureNameAtTier(normalizeSuggestedName(name), tier) + ).filter((name) => !used.has(name)) + if (available.length > 0) { + return pickRandom(available, random) + } + tier += 1 + } +} diff --git a/src/shared/worktree/create-types.ts b/src/shared/worktree/create-types.ts index 8f1c0f79c074..c3c5c24a876f 100644 --- a/src/shared/worktree/create-types.ts +++ b/src/shared/worktree/create-types.ts @@ -59,6 +59,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. */ 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..dc471ad7c062 --- /dev/null +++ b/src/shared/worktree/retired-name-cache.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { + readRetiredNameRegistryForRepo, + retiredNamesAfterRefresh, + selectRetiredNameRegistry +} from './retired-name-cache' +import { EMPTY_RETIRED_NAME_REGISTRY } from './retired-name-registry' + +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(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([ + ['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(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(readRetiredNameRegistryForRepo(result, 'repo-1').names).toEqual(['nautilus', 'seahorse']) + }) +}) + +describe('retiredNamesAfterRefresh', () => { + 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 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', () => { + expect(retiredNamesAfterRefresh(loadOf('repo-1', ['nautilus'], 2), 'repo-2', null)).toEqual({ + repoId: 'repo-2', + registry: EMPTY_RETIRED_NAME_REGISTRY + }) + }) + + it('answers empty when the first fetch for a repo fails', () => { + expect(retiredNamesAfterRefresh(null, 'repo-1', null).registry).toEqual( + EMPTY_RETIRED_NAME_REGISTRY + ) + }) +}) + +describe('selectRetiredNameRegistry', () => { + it('serves a load only to the repo it answered for', () => { + 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 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 new file mode 100644 index 000000000000..3c68960dd481 --- /dev/null +++ b/src/shared/worktree/retired-name-cache.ts @@ -0,0 +1,76 @@ +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 + * 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. */ + +/** The last answer, tagged with the repo it answered for. */ +export type RetiredNamesLoad = { + repoId: string + registry: RetiredNameRegistry +} + +/** 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; `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. + * + * 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, + registry: RetiredNameRegistry | null +): RetiredNamesLoad { + return { + repoId, + 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 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 +): 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 +}