Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
b8014ee
fix(worktree): never reissue a generated workspace name
brennanb2025 Aug 13, 2026
1278cd8
fix(mobile): honor retired workspace names, on one shared implementation
brennanb2025 Aug 13, 2026
59f1105
Merge remote-tracking branch 'origin/main' into brennanb2025/retire-g…
brennanb2025 Aug 13, 2026
21a117a
fix(worktree): close retirement consistency gaps
brennanb2025 Aug 13, 2026
ba024d5
test(worktree): cover retirement runtime contracts
brennanb2025 Aug 13, 2026
b15c7e0
fix(worktree): retire generated collision names
brennanb2025 Aug 13, 2026
3b082a9
fix(worktree): enforce retired names at creation
brennanb2025 Aug 13, 2026
f336164
refactor(ai-vault): extract the Claude project-dir encoder
brennanb2025 Aug 14, 2026
54afdb3
fix(worktree): make the retirement seed scan actually match buckets
brennanb2025 Aug 14, 2026
5aef758
fix(worktree): retire only generated names, keyed by cwd namespace
brennanb2025 Aug 14, 2026
ef06e49
fix(worktree): send name provenance and stop gating Create on the fetch
brennanb2025 Aug 14, 2026
9d8ce5c
Merge remote-tracking branch 'origin/main' into brennanb2025/retire-g…
brennanb2025 Aug 14, 2026
9234cb4
fix(worktree): key retirement by repo id and prune it with the repo
brennanb2025 Aug 14, 2026
f583fae
docs(worktree): spell out why the retirement bound sits above the pool
brennanb2025 Aug 14, 2026
b87360f
fix(worktree): send name provenance from the web runtime client
brennanb2025 Aug 14, 2026
5052f1c
fix(worktree): retire names that took more than one collision suffix
brennanb2025 Aug 14, 2026
348bf5d
perf(worktree): keep the retirement backfill off the blocking WSL probe
brennanb2025 Aug 14, 2026
58e8c7d
fix(worktree): hold retired names across a refresh instead of blanking
brennanb2025 Aug 14, 2026
3d3165e
Merge remote-tracking branch 'origin/main' into brennanb2025/retire-g…
brennanb2025 Aug 14, 2026
07b207c
refactor(worktree): put the retired-name cache rules on one implement…
brennanb2025 Aug 14, 2026
9eebf38
Merge remote-tracking branch 'origin/main' into brennanb2025/retire-g…
brennanb2025 Aug 14, 2026
e2d0185
fix(worktree): import shared types from their real modules
brennanb2025 Aug 14, 2026
481bf3c
Merge remote-tracking branch 'origin/main' into brennanb2025/retire-g…
brennanb2025 Aug 14, 2026
5c51039
refactor(worktree): bound the retirement registry by tier compaction,…
brennanb2025 Aug 14, 2026
440419b
fix(worktree): preserve generated name retirement across failures
brennanb2025 Aug 15, 2026
dde6614
Merge remote-tracking branch 'origin/main' into brennanb2025/retire-g…
brennanb2025 Aug 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion mobile/src/components/NewWorktreeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -198,6 +199,18 @@ function NewWorktreeModalContent({
const [initialRepos] = useState(() => (hostId ? (getCachedRepos(hostId) as Repo[] | null) : null))
const [repos, setRepos] = useState<Repo[]>(initialRepos ?? [])
const [selectedRepo, setSelectedRepo] = useState<Repo | null>(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)
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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,
Expand Down
68 changes: 68 additions & 0 deletions mobile/src/components/worktree-name-suggestion.test.ts
Original file line number Diff line number Diff line change
@@ -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)
)
})
})
73 changes: 27 additions & 46 deletions mobile/src/components/worktree-name-suggestion.ts
Original file line number Diff line number Diff line change
@@ -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<T>(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<string>()
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)
}
24 changes: 24 additions & 0 deletions mobile/src/tasks/blank-workspace-create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ describe('createBlankWorkspace', () => {
createdWithAgentId: undefined,
comment: undefined,
setupDecision: 'inherit',
nameWasGenerated: false,
supportsIdempotentCutoverRetry: true
})

Expand All @@ -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`.
Expand All @@ -69,6 +89,7 @@ describe('createBlankWorkspace', () => {
createdWithAgentId: 'claude',
comment: 'spike',
setupDecision: 'run',
nameWasGenerated: false,
supportsIdempotentCutoverRetry: true
})

Expand Down Expand Up @@ -100,6 +121,7 @@ describe('createBlankWorkspace', () => {
createdWithAgentId: undefined,
comment: undefined,
setupDecision: 'inherit',
nameWasGenerated: false,
supportsIdempotentCutoverRetry: true
})

Expand All @@ -125,6 +147,7 @@ describe('createBlankWorkspace', () => {
createdWithAgentId: undefined,
comment: undefined,
setupDecision: 'inherit',
nameWasGenerated: false,
supportsIdempotentCutoverRetry: true
})

Expand All @@ -143,6 +166,7 @@ describe('createBlankWorkspace', () => {
createdWithAgentId: undefined,
comment: undefined,
setupDecision: 'skip',
nameWasGenerated: false,
supportsIdempotentCutoverRetry: true
})

Expand Down
5 changes: 5 additions & 0 deletions mobile/src/tasks/blank-workspace-create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean>
}): Promise<WorktreeCreateResult> {
return createWorktreeWithNameRetry({
client: args.client,
baseName: args.baseName,
nameWasGenerated: args.nameWasGenerated,
supportsIdempotentCutoverRetry: args.supportsIdempotentCutoverRetry,
buildParams: (name) => {
const params: Record<string, unknown> = {
repo: `id:${args.repoId}`,
setupDecision: args.setupDecision,
name,
...(args.nameWasGenerated ? { nameWasGenerated: true } : {}),
...agentLaunchCreateFields(args.createdWithAgentId)
}
if (args.comment) {
Expand Down
19 changes: 19 additions & 0 deletions mobile/src/tasks/worktree-create-retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion mobile/src/tasks/worktree-create-retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -26,6 +27,7 @@ const WORKTREE_CREATE_CUTOVER_MAX_RETRIES = 5
export type CreateWorktreeWithNameRetryArgs = {
client: RpcClient
baseName: string
nameWasGenerated?: boolean
buildParams: (name: string) => Record<string, unknown>
supportsIdempotentCutoverRetry: boolean | Promise<boolean>
maxAttempts?: number
Expand All @@ -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
Expand Down
Loading