diff --git a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts index ef3ad65375a..32566fd4eb3 100644 --- a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts +++ b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts @@ -26,7 +26,7 @@ import { takeWslMappedDriveMovesDue, type WslDriveUncConversionOutcome } from '../../wsl/filesystem/wsl-drive-unc-conversion-startup' -import { resolveWslMappedDrivePath } from '../../wsl/filesystem/wsl-mapped-drive-share' +import { readWslMappedDriveShareNow } from '../../wsl/filesystem/wsl-mapped-drive-share' import { wslHostsGateOpen, wslHostsOptedIn } from '../../wsl/host-lifecycle/wsl-host-gate' import { createWslMoveDriverDeps } from './wsl-move-driver-wiring' import { getTrustedUIRendererWebContents } from '../ui' @@ -70,7 +70,7 @@ export function registerWslDriveUncConversionHandlers( userDataPath, profileId: activeProfileId, readDriveMounts: readWslDistroDriveMounts, - readMappedDriveShare: (letter) => resolveWslMappedDrivePath(`${letter}:\\`), + readMappedDriveShare: (letter) => readWslMappedDriveShareNow(letter), readProfileState: async () => { await store.flushPendingOrThrowAsync() return readProfileProjectTransferState(activeProfileId, getProfileUserDataPath()).state @@ -149,19 +149,27 @@ function parseRequest(value: unknown): WslDriveUncConversionRequest { const repoIds = 'repoIds' in record ? record.repoIds : undefined const folderWorkspaceIds = 'folderWorkspaceIds' in record ? record.folderWorkspaceIds : [] const mappedDriveLetter = 'mappedDriveLetter' in record ? record.mappedDriveLetter : undefined + const mappedDriveShare = 'mappedDriveShare' in record ? record.mappedDriveShare : undefined if ( typeof distro !== 'string' || !distro || !isIdList(repoIds) || !isIdList(folderWorkspaceIds) || (mappedDriveLetter !== undefined && - (typeof mappedDriveLetter !== 'string' || !/^[A-Za-z]$/.test(mappedDriveLetter))) + (typeof mappedDriveLetter !== 'string' || !/^[A-Za-z]$/.test(mappedDriveLetter))) || + (mappedDriveShare !== undefined && (typeof mappedDriveShare !== 'string' || !mappedDriveShare)) ) { throw new Error('wsl_drive_unc_invalid_args') } return mappedDriveLetter === undefined ? { distro, repoIds, folderWorkspaceIds } - : { distro, repoIds, folderWorkspaceIds, mappedDriveLetter } + : { + distro, + repoIds, + folderWorkspaceIds, + mappedDriveLetter, + ...(mappedDriveShare === undefined ? {} : { mappedDriveShare }) + } } function isIdList(value: unknown): value is string[] { diff --git a/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.test.ts b/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.test.ts index 7120c640f2e..ac96abceed5 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.test.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.test.ts @@ -49,7 +49,7 @@ function deps(overrides: Partial = {}): WslDriveUn userDataPath: root, profileId: 'profile-1', readDriveMounts: async () => [{ mountPoint: '/mnt/c', windowsRoot: 'C:\\' }], - readMappedDriveShare: async () => null, + readMappedDriveShare: async () => ({ share: null }), readProfileState: async () => state(), pause: vi.fn(async () => ({ panes: [] })), runWindowsGit: vi.fn(async (args: string[]) => @@ -172,12 +172,17 @@ describe('startWslDriveUncConversion for a mapped drive', () => { return value } - const MAPPED_REQUEST = { distro: 'Ubuntu', repoIds: ['repo-a'], mappedDriveLetter: 'w' } + const MAPPED_REQUEST = { + distro: 'Ubuntu', + repoIds: ['repo-a'], + mappedDriveLetter: 'w', + mappedDriveShare: SHARE + } it('journals the respelling with the drive mapping read now, and never asks Windows Git', async () => { const run = deps({ readProfileState: async () => mappedState(), - readMappedDriveShare: vi.fn(async () => SHARE) + readMappedDriveShare: vi.fn(async () => ({ share: SHARE })) }) expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ outcome: 'restarting', @@ -198,7 +203,7 @@ describe('startWslDriveUncConversion for a mapped drive', () => { it('refuses when the drive no longer maps into the distro', async () => { const run = deps({ readProfileState: async () => mappedState(), - readMappedDriveShare: async () => String.raw`\\wsl.localhost\Debian` + readMappedDriveShare: async () => ({ share: String.raw`\\wsl.localhost\Debian` }) }) expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ outcome: 'refused', @@ -208,6 +213,29 @@ describe('startWslDriveUncConversion for a mapped drive', () => { expect(listWslDriveUncConversions(root)).toEqual([]) }) + it('refuses a drive remapped to another folder of the distro since the window looked', async () => { + const run = deps({ + readProfileState: async () => mappedState(), + readMappedDriveShare: async () => ({ share: String.raw`\\wsl.localhost\Ubuntu\home` }) + }) + expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ + outcome: 'refused', + blockers: [{ kind: 'drive-not-mapped' }] + }) + }) + + it('asks to try again when Windows did not answer in time, changing nothing', async () => { + const run = deps({ + readProfileState: async () => mappedState(), + readMappedDriveShare: async () => 'unverifiable' + }) + expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ + outcome: 'refused', + blockers: [{ kind: 'drive-unverifiable' }] + }) + expect(run.pause).not.toHaveBeenCalled() + }) + it('refuses a project already saved under its share path', async () => { const run = deps({ readProfileState: async () => { @@ -221,7 +249,7 @@ describe('startWslDriveUncConversion for a mapped drive', () => { }) return value }, - readMappedDriveShare: async () => SHARE + readMappedDriveShare: async () => ({ share: SHARE }) }) expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ outcome: 'refused', diff --git a/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.ts b/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.ts index b51884f3840..3125f83f817 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.ts @@ -33,7 +33,8 @@ import { type WslDriveUncTarget } from './wsl-drive-unc-project-scope' import { collectWslMappedDriveScope } from './wsl-mapped-drive-project-scope' -import { parseWslUncPath, wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths' +import { wslMappedDriveMatches, type WslMappedDriveRead } from './wsl-mapped-drive-share' +import { wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths' import { wslDriveUncRespelling, type WslMappedDrive @@ -50,8 +51,8 @@ export type WslDriveUncConversionRunDeps = Pick< profileId: string /** The distro's Windows-drive mounts; null when unreadable, which refuses every path. */ readDriveMounts: (distro: string) => Promise - /** The distro share a drive letter maps to (`\\wsl.localhost\`); null for any other drive. */ - readMappedDriveShare: (letter: string) => Promise + /** Where a drive letter maps right now, never cached: this decides what gets rewritten. */ + readMappedDriveShare: (letter: string) => Promise /** The saved profile, flushed first: the dry run must see what the restart will rewrite. */ readProfileState: () => Promise pause: (scope: WslMoveTerminalScope) => Promise<{ panes: readonly unknown[] } | WslMoveRefusal> @@ -70,9 +71,10 @@ export async function startWslDriveUncConversion( if (journals.some((journal) => journal.phase === 'prepared')) { return refused([{ kind: 'conversion-pending' }]) } - const mappedDrive = request.mappedDriveLetter - ? await readMappedDrive(deps, request.mappedDriveLetter, request.distro) - : undefined + const mappedDrive = request.mappedDriveLetter ? await readMappedDrive(deps, request) : undefined + if (mappedDrive === 'unverifiable') { + return refused([{ kind: 'drive-unverifiable' }]) + } if (mappedDrive === null) { return refused([{ kind: 'drive-not-mapped' }]) } @@ -149,19 +151,21 @@ export async function startWslDriveUncConversion( return { outcome: 'restarting', migrationId } } -/** The drive's share, read now; null when it no longer maps into `distro`. */ +/** The drive's share, read now; null when it no longer maps where the window showed. */ async function readMappedDrive( deps: Pick, - letter: string, - distro: string -): Promise { + request: WslDriveUncConversionRequest +): Promise { + const letter = request.mappedDriveLetter ?? '' if (!/^[A-Za-z]$/.test(letter)) { return null } - const share = await deps.readMappedDriveShare(letter) - // A drive may map a folder inside the distro; the share is that folder's UNC path. - return share && parseWslUncPath(share)?.distro.toLowerCase() === distro.toLowerCase() - ? { letter: letter.toUpperCase(), share } + const read = await deps.readMappedDriveShare(letter) + if (read === 'unverifiable') { + return read + } + return wslMappedDriveMatches(read.share, request.distro, request.mappedDriveShare) + ? { letter: letter.toUpperCase(), share: read.share } : null } diff --git a/src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.ts b/src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.ts index bc75a456c39..773393db00d 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.ts @@ -31,6 +31,13 @@ import { journalDomainDatabasePath } from '../../native-chat/agent-session-journ import { rewriteWslDriveUncState } from './wsl-drive-unc-state-rewrite' import { WSL_DRIVE_UNC_STATE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-drive-unc-state-dispositions' import type { WslMappedDriveMoveDue } from '../../../shared/wsl-move/wsl-drive-unc-conversion-types' +import { + readWslMappedDriveShareNow, + wslMappedDriveMatches, + type WslMappedDriveRead +} from './wsl-mapped-drive-share' + +const STARTUP_DRIVE_READ_TIMEOUT_MS = 10_000 export type WslDriveUncConversionStartupDeps = { /** Where the journal lives. */ @@ -40,8 +47,13 @@ export type WslDriveUncConversionStartupDeps = { profileId: string stores: readonly WslDriveUncConversionStore[] now?: () => Date + /** Where a drive letter maps right now; a mapped-drive plan runs only while it still matches. */ + readMappedDriveShare?: (letter: string) => Promise } +/** The restart follows the confirm within seconds; a plan this old was left by another run. */ +const MAPPED_DRIVE_PLAN_MAX_AGE_MS = 60 * 60 * 1000 + export type WslDriveUncConversionOutcome = | { migrationId: string @@ -51,6 +63,8 @@ export type WslDriveUncConversionOutcome = distro?: string /** Set for a mapped-drive respelling, whose projects the WSL move takes next. */ mappedDrive?: boolean + /** This run rewrote the profile; a later run only finishes outside stores. */ + respelledThisRun?: boolean } /** The profile could not be rewritten; nothing changed, and the panes stay asleep. */ | { migrationId: string; outcome: 'rolled-back'; detail: string } @@ -74,8 +88,10 @@ async function runOne( ): Promise { const { migrationId } = initial let record = initial - if (record.phase === 'prepared') { + const advancing = record.phase === 'prepared' + if (advancing) { try { + await assertMappedDriveStillMatches(deps, record) record = rewriteProfile(deps, record) } catch (error) { removeWslDriveUncConversion(deps.userDataPath, migrationId) @@ -111,7 +127,36 @@ async function runOne( repoIds: record.repoIds, folderWorkspaceIds: record.folderWorkspaceIds, distro: record.distro, - ...(record.mappedDrive ? { mappedDrive: true } : {}) + ...(record.mappedDrive ? { mappedDrive: true } : {}), + ...(advancing ? { respelledThisRun: true } : {}) + } +} + +/** + * A mapped-drive plan names the drive's share as it was at the confirm. One left over (an older + * build ran in between, say) or a drive remapped since rolls back instead of rewriting into the + * wrong distro or folder. + */ +async function assertMappedDriveStillMatches( + deps: WslDriveUncConversionStartupDeps, + record: WslDriveUncConversion +): Promise { + const drive = record.mappedDrive + if (!drive) { + return + } + const age = (deps.now?.() ?? new Date()).getTime() - Date.parse(record.createdAt) + if (!(age >= 0 && age <= MAPPED_DRIVE_PLAN_MAX_AGE_MS)) { + throw new Error('wsl_mapped_drive_plan_expired') + } + const read = deps.readMappedDriveShare + ? await deps.readMappedDriveShare(drive.letter) + : 'unverifiable' + if (read === 'unverifiable') { + throw new Error('wsl_mapped_drive_unverifiable') + } + if (!wslMappedDriveMatches(read.share, record.distro, drive.share)) { + throw new Error('wsl_mapped_drive_remapped') } } @@ -198,7 +243,10 @@ export function wslMappedDriveMovesDueOf( outcomes: readonly WslDriveUncConversionOutcome[] ): WslMappedDriveMoveDue[] { return outcomes.flatMap((outcome) => - outcome.outcome === 'converted' && outcome.mappedDrive && outcome.distro + outcome.outcome === 'converted' && + outcome.mappedDrive && + outcome.respelledThisRun && + outcome.distro ? [ { distro: outcome.distro, @@ -229,6 +277,9 @@ export async function runPendingWslDriveUncConversions(paths: { } lastOutcomes = await runWslDriveUncConversionsAtStartup({ ...paths, + // Longer than an add's wait: the distro may still be starting with the app. + readMappedDriveShare: (letter) => + readWslMappedDriveShareNow(letter, undefined, STARTUP_DRIVE_READ_TIMEOUT_MS), stores: wslDriveUncConversionStores({ daemonHistoryDir: getHistoryRoot(), shellHistoryRoots: [getHistoryRoot(), ...listWslHistoryRoots()], diff --git a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.test.ts b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.test.ts index 6c84ecff1b9..ea423abf5c3 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.test.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.test.ts @@ -68,3 +68,32 @@ describe('rewriteWslDriveUncValue', () => { expect(rewriteWslDriveUncValue(untouched, rewriter)).toBe(untouched) }) }) + +describe('createWslDriveUncRewriter for a mapped drive', () => { + const mapped = createWslDriveUncRewriter({ + distro: 'Ubuntu', + mappedDrive: { letter: 'W', share: String.raw`\\wsl.localhost\Ubuntu` }, + repoIds: new Set(['r1']), + folderWorkspaceIds: new Set(), + roots: [String.raw`W:\home\me\App`] + }) + + it.each([ + [ + 'a saved path', + String.raw`W:\home\me\App\src`, + String.raw`\\wsl.localhost\Ubuntu\home\me\App\src` + ], + // Case is folded in the key; the root's own spelling restores it. + ['a comparison key of the root', 'w:/home/me/app', '//wsl/ubuntu/home/me/App'], + ['a comparison key inside it', 'w:/home/me/app/src', '//wsl/ubuntu/home/me/App/src'], + ['a comparison key of another folder', 'w:/home/me/other', 'w:/home/me/other'], + ['a path of another folder', String.raw`W:\home\me\other`, String.raw`W:\home\me\other`] + ])('re-keys %s', (_label, value, expected) => { + expect(mapped.identity(value)).toBe(expected) + }) + + it('keeps a D1c comparison key in comparison form', () => { + expect(rewriter.identity('//wsl/ubuntu/mnt/c/src/app/lib')).toBe('c:/src/app/lib') + }) +}) diff --git a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts index 73ed4c4db63..8f31241dbe4 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts @@ -49,7 +49,7 @@ export type WslDriveUncRewriter = { const VERBATIM_KEYS: ReadonlySet = new Set(['priorWorktreeIds']) export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDriveUncRewriter { - const respelling = wslDriveUncRespelling(scope) + const respelling = wslDriveUncRespelling(scope, scope.roots) const roots = scope.roots.flatMap((root) => { const converted = respelling.path(root) return converted ? [normalizeRuntimePathForComparison(converted)] : [] @@ -84,7 +84,12 @@ export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDr ) } const barePath = (value: string): string => { - const mapped = respelling.comparisonForm(value) ?? respelling.path(value) + // A comparison key stays one; the respelling checks its root itself. + const comparison = respelling.comparisonForm(value) + if (comparison) { + return comparison + } + const mapped = respelling.path(value) return mapped && inRoot(mapped) ? mapped : value } const identity = (value: string): string => { diff --git a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts index c4e372e4ea6..7b62b9dc4c0 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts @@ -79,12 +79,12 @@ export function rewriteWslDriveUncState( rewriter ) } - if (!scope.mappedDrive) { - next.projects = sameIfUnchanged( - next.projects, - withWindowsGit(next.projects, repoIds, scope.distro) - ) - } + next.projects = sameIfUnchanged( + next.projects, + scope.mappedDrive + ? withPinnedRuntime(next.projects, repoIds) + : withWindowsGit(next.projects, repoIds, scope.distro) + ) next.projectGroups = sameIfUnchanged( next.projectGroups, withConvertedGroupFolders(next, repoIds, folderWorkspaceIds, respelling) @@ -252,6 +252,19 @@ function windowsGitPreference( return { kind: 'wsl', distro, git: 'windows-host' } } +/** + * A project with no saved runtime infers WSL from a share path, so respelling alone would move its + * terminals and Git from the global default into the distro, even if the move is then cancelled. + */ +function withPinnedRuntime(projects: Project[], repoIds: ReadonlySet): Project[] { + return projects.map((project) => + project.localWindowsRuntimePreference === undefined && + project.sourceRepoIds.some((id) => repoIds.has(id)) + ? { ...project, localWindowsRuntimePreference: { kind: 'inherit-global' } } + : project + ) +} + /** A group whose projects all convert was made from their parent folder, which converts too. */ function withConvertedGroupFolders( state: PersistedState, diff --git a/src/main/wsl/filesystem/wsl-mapped-drive-conversion-startup.test.ts b/src/main/wsl/filesystem/wsl-mapped-drive-conversion-startup.test.ts index a5c317528ca..3d46fd45008 100644 --- a/src/main/wsl/filesystem/wsl-mapped-drive-conversion-startup.test.ts +++ b/src/main/wsl/filesystem/wsl-mapped-drive-conversion-startup.test.ts @@ -20,6 +20,7 @@ import { runWslDriveUncConversionsAtStartup, wslMappedDriveMovesDueOf } from './wsl-drive-unc-conversion-startup' +import type { WslMappedDriveRead } from './wsl-mapped-drive-share' const PROFILE = 'profile-1' const SHARE = String.raw`\\wsl.localhost\Ubuntu` @@ -67,8 +68,7 @@ function profileState(): PersistedState { badgeColor: '', sourceRepoIds: ['repo-a'], createdAt: 0, - updatedAt: 0, - localWindowsRuntimePreference: { kind: 'windows-host' } + updatedAt: 0 } ] state.worktreeMeta = { @@ -151,12 +151,14 @@ function journal(overrides: Partial = {}): void { }) } -function run() { +function run(read: WslMappedDriveRead = { share: SHARE }) { return runWslDriveUncConversionsAtStartup({ userDataPath: root, profileUserDataPath: root, profileId: PROFILE, - stores: [] + stores: [], + now: () => new Date('2026-11-16T00:00:05.000Z'), + readMappedDriveShare: async () => read }) } @@ -172,7 +174,8 @@ describe('a mapped-drive conversion at startup', () => { repoIds: ['repo-a'], folderWorkspaceIds: ['notes'], distro: 'Ubuntu', - mappedDrive: true + mappedDrive: true, + respelledThisRun: true } ]) const state = readProfileProjectTransferState(PROFILE, root).state @@ -192,13 +195,39 @@ describe('a mapped-drive conversion at startup', () => { ptyId: `${NEW_ID}@@s1`, worktreeId: NEW_ID }) - // Only D1c switches to Git for Windows; a respelled project keeps what it ran. - expect(state.projects[0].localWindowsRuntimePreference).toEqual({ kind: 'windows-host' }) + // With nothing saved it ran the global default; the share path alone would now infer WSL. + expect(state.projects[0].localWindowsRuntimePreference).toEqual({ kind: 'inherit-global' }) expect(wslMappedDriveMovesDueOf(outcomes)).toEqual([ { distro: 'Ubuntu', repoIds: ['repo-a'], folderWorkspaceIds: ['notes'] } ]) }) + it('reports the move due only on the run that rewrote the profile', async () => { + seedProfile(profileState()) + // The window's stores never recorded themselves, so the journal outlives the first run. + journal() + expect(wslMappedDriveMovesDueOf(await run())).toHaveLength(1) + expect(listWslDriveUncConversions(root)).toHaveLength(1) + expect(wslMappedDriveMovesDueOf(await run())).toEqual([]) + }) + + it.each([ + ['the drive now maps elsewhere', { share: String.raw`\\wsl.localhost\Debian` }, {}], + ['Windows cannot say where it maps', 'unverifiable' as const, {}], + [ + 'the plan is left over from long ago', + { share: SHARE }, + { createdAt: '2026-11-01T00:00:00.000Z' } + ] + ])('rolls back, changing nothing, when %s', async (_why, read, overrides) => { + seedProfile(profileState()) + journal(overrides) + const [outcome] = await run(read) + expect(outcome).toMatchObject({ migrationId: 'conv-1', outcome: 'rolled-back' }) + expect(readProfileProjectTransferState(PROFILE, root).state.repos[0].path).toBe(MAPPED) + expect(listWslDriveUncConversions(root)).toEqual([]) + }) + it('keeps its journal apart from D1c so an older build never runs it as one', () => { journal() expect(existsSync(join(root, 'wsl-mapped-drive-conversions', 'conv-1.json'))).toBe(true) diff --git a/src/main/wsl/filesystem/wsl-mapped-drive-share.test.ts b/src/main/wsl/filesystem/wsl-mapped-drive-share.test.ts index b0948ec8fb8..07cfdccb5b8 100644 --- a/src/main/wsl/filesystem/wsl-mapped-drive-share.test.ts +++ b/src/main/wsl/filesystem/wsl-mapped-drive-share.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { clearWslMappedDriveShareCacheForTests, + readWslMappedDriveShareNow, resolveWslMappedDrivePath, type WslMappedDriveShareDeps } from './wsl-mapped-drive-share' @@ -144,3 +145,42 @@ describe('resolveWslMappedDrivePath', () => { await expect(resolveWslMappedDrivePath('W:\\..\\etc', deps(realpathRoot))).resolves.toBe(null) }) }) + +describe('readWslMappedDriveShareNow', () => { + it('asks Windows again rather than trusting a cached answer from before a remap', async () => { + const realpathRoot = vi + .fn() + .mockResolvedValueOnce('\\\\wsl.localhost\\Ubuntu\\') + .mockResolvedValueOnce('\\\\wsl.localhost\\Debian\\') + await resolveWslMappedDrivePath('W:\\x', deps(realpathRoot)) + await expect(readWslMappedDriveShareNow('w', deps(realpathRoot))).resolves.toEqual({ + share: '\\\\wsl.localhost\\Debian' + }) + expect(realpathRoot).toHaveBeenLastCalledWith('W:\\') + }) + + it('tells a slow drive apart from one that maps nowhere', async () => { + await expect( + readWslMappedDriveShareNow( + 'W', + deps(() => new Promise(() => {})) + ) + ).resolves.toBe('unverifiable') + await expect( + readWslMappedDriveShareNow( + 'W', + deps(async () => { + throw new Error('ENOENT') + }) + ) + ).resolves.toEqual({ share: null }) + await expect( + readWslMappedDriveShareNow( + 'C', + deps(async () => 'C:\\') + ) + ).resolves.toEqual({ + share: null + }) + }) +}) diff --git a/src/main/wsl/filesystem/wsl-mapped-drive-share.ts b/src/main/wsl/filesystem/wsl-mapped-drive-share.ts index 4cece01a14e..ee6e7b6f9e1 100644 --- a/src/main/wsl/filesystem/wsl-mapped-drive-share.ts +++ b/src/main/wsl/filesystem/wsl-mapped-drive-share.ts @@ -4,6 +4,7 @@ */ import { realpath } from 'node:fs' import { win32 } from 'node:path' +import { normalizeRuntimePathForComparison } from '../../../shared/file-access/cross-platform-path' import { parseWslUncPath } from '../../../shared/file-access/wsl-paths' const RESOLVE_TIMEOUT_MS = 2_000 @@ -97,6 +98,52 @@ export async function resolveWslMappedDrivePath( return tail === '' || tail === '.' ? share : `${share}\\${tail}` } +/** What a drive letter maps to right now; `unverifiable` when Windows didn't answer in time. */ +export type WslMappedDriveRead = { share: string | null } | 'unverifiable' + +/** + * Asks Windows again, bypassing the cache, for a decision that rewrites saved state: a drive + * remapped within the cache's minute must not convert a project into another distro or folder. + */ +export async function readWslMappedDriveShareNow( + letter: string, + deps: WslMappedDriveShareDeps = defaultDeps, + timeoutMs: number = deps.timeoutMs +): Promise { + if (deps.platform !== 'win32' || !/^[A-Za-z]$/.test(letter)) { + return { share: null } + } + let timer: ReturnType | undefined + const timeout = new Promise<'unverifiable'>((resolve) => { + timer = setTimeout(() => resolve('unverifiable'), timeoutMs) + }) + const lookup = deps.realpathRoot(`${letter.toUpperCase()}:\\`).then( + (real): WslMappedDriveRead => ({ + share: parseWslUncPath(real) ? real.replace(/[\\/]+$/, '') : null + }), + // No such drive, or not one Windows can resolve: nothing is mapped there. + (): WslMappedDriveRead => ({ share: null }) + ) + return Promise.race([lookup, timeout]).finally(() => clearTimeout(timer)) +} + +/** + * The drive still maps into `distro`, to the share the window showed when it was given one. + * A drive may map a folder inside the distro; the share is that folder's UNC path. + */ +export function wslMappedDriveMatches( + share: string | null, + distro: string, + expectedShare: string | undefined +): share is string { + return ( + share !== null && + parseWslUncPath(share)?.distro.toLowerCase() === distro.toLowerCase() && + (expectedShare === undefined || + normalizeRuntimePathForComparison(share) === normalizeRuntimePathForComparison(expectedShare)) + ) +} + export function clearWslMappedDriveShareCacheForTests(): void { cache.clear() } diff --git a/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx b/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx index cc5869d8081..132a6a49bf6 100644 --- a/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx +++ b/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx @@ -51,7 +51,10 @@ export function RepositoryWindowsRuntimeSection({ }: RepositoryWindowsRuntimeSectionProps): React.JSX.Element | null { const t = useTranslate() // Owner decision: for a WSL project with a host, the runtime toggle becomes "Move project". - const wslMoveTarget = useWslMoveTargetForRepo(repo) + // A mapped-drive project keeps its runtime toggle; its move is on the project menu. Swapping the + // toggle out once the drive lookup answers would make the setting jump. + const resolvedMoveTarget = useWslMoveTargetForRepo(repo) + const wslMoveTarget = resolvedMoveTarget?.mappedDrive ? null : resolvedMoveTarget // D1c ships with WSL hosts; serve-only, a live block or the setting off hide its offers, as main // refuses them. A project already on Git for Windows still shows that state. const d1cAvailable = useWslHostsAcceptNewWork() diff --git a/src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts b/src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts index 5ebe8de1ba1..1da8da50b61 100644 --- a/src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts +++ b/src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts @@ -44,7 +44,7 @@ describe('moveWslHostOfferProject', () => { it('reopens a project the add found saved as W: at its share path before the move', async () => { // Registration matches by real path, so the share spelling resolves to the saved W: row. - resolveWslMappedDrivePath.mockResolvedValue(offer.sharePath) + resolveWslMappedDrivePath.mockResolvedValue('\\\\wsl.localhost\\Ubuntu') moveWslHostOfferProject(offer, { status: 'completed', repo: { id: 'repo-w', path: 'W:\\home\\u\\repo', displayName: 'repo' } @@ -53,11 +53,13 @@ describe('moveWslHostOfferProject', () => { expect(openWslMappedDriveMove).toHaveBeenCalledWith({ distro: 'Ubuntu', letter: 'W', + share: '\\\\wsl.localhost\\Ubuntu', sharePath: offer.sharePath, ref: { kind: 'repo', id: 'repo-w' }, name: 'repo' }) ) + expect(resolveWslMappedDrivePath).toHaveBeenCalledWith('W:\\') expect(openWslMoveDialogFor).not.toHaveBeenCalled() expect(toastError).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/components/sidebar/wsl-host-offer-move.ts b/src/renderer/src/components/sidebar/wsl-host-offer-move.ts index 8f44eb0a1c3..2b4a8f0119d 100644 --- a/src/renderer/src/components/sidebar/wsl-host-offer-move.ts +++ b/src/renderer/src/components/sidebar/wsl-host-offer-move.ts @@ -14,6 +14,7 @@ import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver- import { openWslMoveDialogFor } from '../wsl-move/wsl-move-entry' import { openWslMappedDriveMove } from '../wsl-move/wsl-mapped-drive-move-store' import { resolveWslMappedDrivePath } from './wsl-mapped-drive-path' +import { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-drive-unc-respelling' import { wslMoveDistroOfPath } from '../wsl-move/wsl-move-scope-rows' import type { WslHostOffer } from './wsl-host-offer-actions' @@ -87,11 +88,18 @@ async function moveSavedUnderMappedDrive( offer: WslHostOffer, repo: { id: string; path: string; name: string } ): Promise { - const sharePath = await resolveWslMappedDrivePath(repo.path) - if (sharePath && wslMoveDistroOfPath(sharePath)?.toLowerCase() === offer.distro.toLowerCase()) { + const letter = repo.path[0]?.toUpperCase() ?? '' + const share = /^[A-Z]$/.test(letter) ? await resolveWslMappedDrivePath(`${letter}:\\`) : null + const sharePath = share ? wslMappedDrivePathToShare(repo.path, { letter, share }) : null + if ( + share && + sharePath && + wslMoveDistroOfPath(sharePath)?.toLowerCase() === offer.distro.toLowerCase() + ) { openWslMappedDriveMove({ distro: offer.distro, - letter: repo.path[0].toUpperCase(), + letter, + share, sharePath, ref: { kind: 'repo', id: repo.id }, name: repo.name diff --git a/src/renderer/src/components/wsl-drive-project/wsl-drive-unc-conversion-copy.ts b/src/renderer/src/components/wsl-drive-project/wsl-drive-unc-conversion-copy.ts index 28b5e7647ba..3fa552ca8b1 100644 --- a/src/renderer/src/components/wsl-drive-project/wsl-drive-unc-conversion-copy.ts +++ b/src/renderer/src/components/wsl-drive-project/wsl-drive-unc-conversion-copy.ts @@ -45,6 +45,13 @@ function mappedDriveBlockerMessage( blocker: WslDriveUncConversionBlocker, letter: string ): string | null { + if (blocker.kind === 'drive-unverifiable') { + return translate( + 'wslDriveUnc.mappedDrive.unverifiable', + 'Orca couldn’t check where drive {{letter}}: points just now, so nothing changed. Try again in a moment.', + { letter } + ) + } if (blocker.kind === 'drive-not-mapped') { return translate( 'wslDriveUnc.mappedDrive.notMapped', @@ -76,6 +83,11 @@ function mappedDriveBlockerMessage( function blockerMessage(blocker: WslDriveUncConversionBlocker, drivePath: string): string { switch (blocker.kind) { + case 'drive-unverifiable': + return translate( + 'wslDriveUnc.blocker.driveUnverifiable', + 'Orca couldn’t check where that drive points just now, so nothing changed. Try again in a moment.' + ) case 'drive-not-mapped': return translate( 'wslDriveUnc.blocker.driveNotMapped', diff --git a/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx b/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx index cc0271db917..be5e84148b7 100644 --- a/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx +++ b/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx @@ -13,7 +13,8 @@ import { LoadingSpinner } from '@/components/LoadingSpinner' import { closeWslMappedDriveMove, confirmWslMappedDriveMove, - useWslMappedDriveMoveStore + useWslMappedDriveMoveStore, + wslMappedDriveMoveBusy } from './wsl-mapped-drive-move-store' /** The step before moving a mapped-drive project: reopen it at its share path, which restarts Orca. */ @@ -25,7 +26,15 @@ export function WslMappedDriveMoveDialog(): React.JSX.Element | null { return null } const { distro, letter, sharePath, name } = request - const converting = step.kind === 'converting' + const converting = wslMappedDriveMoveBusy(step) + const confirmLabel = + step.kind === 'converting' + ? t('wslMove.mappedDrive.pausing', 'Pausing terminals…') + : step.kind === 'restarting' + ? t('wslMove.mappedDrive.restartingLabel', 'Restarting…') + : step.kind === 'problem' + ? t('wslMove.mappedDrive.retry', 'Try again') + : t('wslMove.mappedDrive.confirm', 'Restart and continue') return ( !open && closeWslMappedDriveMove()}> {step.kind === 'problem' ? ( -
+
{step.messages.map((message) => (

{message}

))} @@ -66,15 +75,15 @@ export function WslMappedDriveMoveDialog(): React.JSX.Element | null { > {t('wslMove.mappedDrive.cancel', 'Cancel')} + {/* Fixed width: the label changes with each stage, and the footer must not shift. */} diff --git a/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx b/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx index dc69f4c7808..80a58627e25 100644 --- a/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx +++ b/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx @@ -4,7 +4,7 @@ import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { DropdownMenuItem } from '@/components/ui/dropdown-menu' import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' +import { resolveFolderWorkspaceHost } from '../../../../shared/folder-workspaces/folder-workspace-execution-host' import type { Repo } from '../../../../shared/repository/repo-types' import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types' import { useWslMoveTargetForPath, useWslMoveTargetForRepo } from './wsl-move-entry' @@ -45,14 +45,17 @@ export function WslMoveFolderWorkspaceMenuItem({ }: { folderWorkspaceId: string }): React.JSX.Element | null { - const folder = useAppStore((s) => - selectFolderWorkspaces(s).find( - (entry) => - entry.id === folderWorkspaceId && - (entry.executionHostId ?? LOCAL_EXECUTION_HOST_ID) === LOCAL_EXECUTION_HOST_ID && - !entry.connectionId - ) - ) + const folder = useAppStore((s) => { + const entry = selectFolderWorkspaces(s).find((row) => row.id === folderWorkspaceId) + // Main's rule: this row alone, as another host may hold a folder workspace with the same id. + return entry && + resolveFolderWorkspaceHost( + { repos: s.repos, projectGroups: s.projectGroups, folderWorkspaces: [entry] }, + entry.id + ).kind === 'local' + ? entry + : undefined + }) const target = useWslMoveTargetForPath(folder?.folderPath, !!folder) return folder ? ( diff --git a/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.test.ts b/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.test.ts index 6f231374ec7..9a44a782b98 100644 --- a/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.test.ts +++ b/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.test.ts @@ -13,6 +13,7 @@ import { useWslMappedDriveMoveStore } from './wsl-mapped-drive-move-store' +const SHARE = String.raw`\\wsl.localhost\Ubuntu` const SHARE_PATH = String.raw`\\wsl.localhost\Ubuntu\home\u\repo` const host = { id: 'env-1', @@ -38,19 +39,15 @@ afterEach(() => { describe('wslMoveTargetOfPath', () => { it('names the mapped drive for a drive path whose share has a host', () => { - expect(wslMoveTargetOfPath(String.raw`w:\home\u\repo`, SHARE_PATH, [host])).toEqual({ + expect(wslMoveTargetOfPath(String.raw`w:\home\u\repo`, SHARE, [host])).toEqual({ distro: 'Ubuntu', - mappedDrive: { letter: 'W', sharePath: SHARE_PATH } + mappedDrive: { letter: 'W', share: SHARE, sharePath: SHARE_PATH } }) }) it('offers nothing without a host, or for a share into a Windows drive', () => { - expect(wslMoveTargetOfPath(String.raw`W:\home\u\repo`, SHARE_PATH, [])).toBeNull() - expect( - wslMoveTargetOfPath(String.raw`W:\mnt\c\src`, String.raw`\\wsl.localhost\Ubuntu\mnt\c\src`, [ - host - ]) - ).toBeNull() + expect(wslMoveTargetOfPath(String.raw`W:\home\u\repo`, SHARE, [])).toBeNull() + expect(wslMoveTargetOfPath(String.raw`W:\mnt\c\src`, SHARE, [host])).toBeNull() }) it('keeps a UNC project on the plain move', () => { @@ -59,7 +56,10 @@ describe('wslMoveTargetOfPath', () => { }) describe('the mapped-drive move', () => { - const target = { distro: 'Ubuntu', mappedDrive: { letter: 'W', sharePath: SHARE_PATH } } + const target = { + distro: 'Ubuntu', + mappedDrive: { letter: 'W', share: SHARE, sharePath: SHARE_PATH } + } it('asks main to reopen the project at its share path', async () => { convert.mockResolvedValue({ outcome: 'restarting', migrationId: 'conv-1' }) @@ -70,9 +70,11 @@ describe('the mapped-drive move', () => { distro: 'Ubuntu', repoIds: [], folderWorkspaceIds: ['notes'], - mappedDriveLetter: 'W' + mappedDriveLetter: 'W', + // What the window showed, so main refuses a drive remapped since. + mappedDriveShare: SHARE }) - expect(useWslMappedDriveMoveStore.getState().step).toEqual({ kind: 'converting' }) + expect(useWslMappedDriveMoveStore.getState().step).toEqual({ kind: 'restarting' }) expect(toast).toHaveBeenCalledOnce() }) @@ -86,13 +88,30 @@ describe('the mapped-drive move', () => { }) }) - it('opens the move for the reopened project once the restart is done', async () => { + it('says to try again when the drive could not be checked in time', async () => { + convert.mockResolvedValue({ outcome: 'refused', blockers: [{ kind: 'drive-unverifiable' }] }) + openWslMoveForProject(target, { kind: 'repo', id: 'repo-w' }, 'repo') + await confirmWslMappedDriveMove() + expect(useWslMappedDriveMoveStore.getState().step).toEqual({ + kind: 'problem', + messages: [expect.stringContaining('Try again')] + }) + }) + + it('opens the move with every reopened project checked once the restart is done', async () => { takeMappedDriveMovesDue.mockResolvedValue([ - { distro: 'Ubuntu', repoIds: ['repo-w'], folderWorkspaceIds: [] } + { distro: 'Ubuntu', repoIds: ['repo-w', 'repo-nested'], folderWorkspaceIds: ['notes'] } ]) await openWslMappedDriveMovesDue() expect(openWslMoveDialog).toHaveBeenCalledWith( - expect.objectContaining({ distro: 'Ubuntu', only: { kind: 'repo', id: 'repo-w' } }) + expect.objectContaining({ + distro: 'Ubuntu', + only: [ + { kind: 'repo', id: 'repo-w' }, + { kind: 'repo', id: 'repo-nested' }, + { kind: 'folder', id: 'notes' } + ] + }) ) }) }) diff --git a/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.ts b/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.ts index 4c11154ebb6..40b3ff5cf52 100644 --- a/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.ts +++ b/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.ts @@ -16,15 +16,26 @@ import { openWslMoveDialogFor, type WslMoveTarget } from './wsl-move-entry' export type WslMappedDriveMoveRequest = { distro: string - /** The drive letter the project is saved under. */ + /** The drive letter the project is saved under, and the share it showed. */ letter: string + share: string /** Where the project reopens: its folder on the distro share. */ sharePath: string ref: WslMoveRowRef name: string } -type Step = { kind: 'review' } | { kind: 'converting' } | { kind: 'problem'; messages: string[] } +type Step = + | { kind: 'review' } + /** Main is checking the drive and putting the project's terminals to sleep. */ + | { kind: 'converting' } + /** Main accepted; the app is about to restart. */ + | { kind: 'restarting' } + | { kind: 'problem'; messages: string[] } + +export function wslMappedDriveMoveBusy(step: Step): boolean { + return step.kind === 'converting' || step.kind === 'restarting' +} type State = { request: WslMappedDriveMoveRequest | null; step: Step } @@ -51,7 +62,7 @@ export function openWslMoveForProject( } export function closeWslMappedDriveMove(): void { - if (useWslMappedDriveMoveStore.getState().step.kind !== 'converting') { + if (!wslMappedDriveMoveBusy(useWslMappedDriveMoveStore.getState().step)) { useWslMappedDriveMoveStore.setState({ request: null, step: { kind: 'review' } }) } } @@ -68,7 +79,8 @@ export async function confirmWslMappedDriveMove(): Promise { distro: request.distro, repoIds: request.ref.kind === 'repo' ? [request.ref.id] : [], folderWorkspaceIds: request.ref.kind === 'folder' ? [request.ref.id] : [], - mappedDriveLetter: request.letter + mappedDriveLetter: request.letter, + mappedDriveShare: request.share }) } catch { useWslMappedDriveMoveStore.setState({ @@ -88,7 +100,8 @@ export async function confirmWslMappedDriveMove(): Promise { return } if (result.outcome === 'restarting') { - // The dialog stays on its spinner until the window goes away. + // The dialog stays until the window goes away. + useWslMappedDriveMoveStore.setState({ step: { kind: 'restarting' } }) toast(translate('wslMove.mappedDrive.restarting', 'Restarting Orca to reopen this project…')) return } @@ -117,5 +130,5 @@ export async function openWslMappedDriveMovesDue(): Promise { ...first.repoIds.map((id) => ({ kind: 'repo' as const, id })), ...first.folderWorkspaceIds.map((id) => ({ kind: 'folder' as const, id })) ] - openWslMoveDialogFor(first.distro, refs.length === 1 ? refs[0] : undefined) + openWslMoveDialogFor(first.distro, refs) } diff --git a/src/renderer/src/components/wsl-move/wsl-move-dialog-selection.test.ts b/src/renderer/src/components/wsl-move/wsl-move-dialog-selection.test.ts new file mode 100644 index 00000000000..9daa183a1a2 --- /dev/null +++ b/src/renderer/src/components/wsl-move/wsl-move-dialog-selection.test.ts @@ -0,0 +1,45 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getWslMoveDialog, openWslMoveDialog, setWslMoveDialog } from './wsl-move-dialog-store' + +const preview = vi.fn() + +beforeEach(() => { + preview.mockResolvedValue({ + outcome: 'ready', + repoIds: ['repo-a', 'repo-b', 'repo-c'], + folderWorkspaceIds: ['notes'], + blockers: [] + }) + vi.stubGlobal('window', { api: { wslMove: { preview } } }) +}) + +afterEach(() => { + preview.mockReset() + vi.unstubAllGlobals() + setWslMoveDialog({ stage: 'closed' }) +}) + +describe('openWslMoveDialog', () => { + it('checks exactly the projects it was opened for, not the whole distro', async () => { + await openWslMoveDialog({ + distro: 'Ubuntu', + only: [ + { kind: 'repo', id: 'repo-a' }, + { kind: 'folder', id: 'notes' } + ] + }) + const dialog = getWslMoveDialog() + expect(dialog.stage === 'preview' ? dialog.selected : null).toEqual([ + { kind: 'repo', id: 'repo-a' }, + { kind: 'folder', id: 'notes' } + ]) + }) + + it('still takes a single project', async () => { + await openWslMoveDialog({ distro: 'Ubuntu', only: { kind: 'repo', id: 'repo-b' } }) + const dialog = getWslMoveDialog() + expect(dialog.stage === 'preview' ? dialog.selected : null).toEqual([ + { kind: 'repo', id: 'repo-b' } + ]) + }) +}) diff --git a/src/renderer/src/components/wsl-move/wsl-move-dialog-store.ts b/src/renderer/src/components/wsl-move/wsl-move-dialog-store.ts index 797ab407231..296ed320e3e 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-dialog-store.ts +++ b/src/renderer/src/components/wsl-move/wsl-move-dialog-store.ts @@ -56,8 +56,8 @@ export type WslMoveDialogState = export type WslMoveOpenRequest = { distro: string - /** Opened from one project: only it starts checked. Otherwise every project does. */ - only?: WslMoveRowRef + /** Opened from some projects: only they start checked. Otherwise every project does. */ + only?: WslMoveRowRef | readonly WslMoveRowRef[] /** Fallback list when main refuses the whole-distro preview. */ catalogCandidates?: () => WslMoveCandidates } @@ -174,9 +174,11 @@ export async function openWslMoveDialog(request: WslMoveOpenRequest): Promise ref.kind === only.kind && ref.id === only.id) : all + const only = request.only === undefined ? undefined : [request.only].flat() + // Opened from projects that cannot move: check nothing; "Not moving" says why. + const selected = only + ? all.filter((ref) => only.some((wanted) => ref.kind === wanted.kind && ref.id === wanted.id)) + : all const wholeDistro = selected.length === all.length && distroPreview.outcome === 'ready' setDialog({ stage: 'preview', diff --git a/src/renderer/src/components/wsl-move/wsl-move-entry.ts b/src/renderer/src/components/wsl-move/wsl-move-entry.ts index bc9bb59c9bc..2b4c453f4f7 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-entry.ts +++ b/src/renderer/src/components/wsl-move/wsl-move-entry.ts @@ -10,6 +10,7 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' import { wslHostMovableDistroOfPath } from '../../../../shared/file-access/wsl-paths' +import { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-drive-unc-respelling' import type { Repo } from '../../../../shared/repository/repo-types' import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types' import { @@ -21,7 +22,11 @@ import { openWslMoveDialog } from './wsl-move-dialog-store' import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields' import { findWslHostForDistro, wslMoveCatalogCandidates } from './wsl-move-scope-rows' -export function openWslMoveDialogFor(distro: string, only?: WslMoveRowRef): void { +/** `only`: the projects that start checked; absent, every project of the distro does. */ +export function openWslMoveDialogFor( + distro: string, + only?: WslMoveRowRef | readonly WslMoveRowRef[] +): void { void openWslMoveDialog({ distro, only, @@ -38,32 +43,47 @@ export function openWslMoveDialogFor(distro: string, only?: WslMoveRowRef): void /** Where a local project can move: its distro's host, spelled as the host names the distro. */ export type WslMoveTarget = { distro: string - /** Saved under a drive letter mapped to the distro's share: the move reopens it there first. */ - mappedDrive?: { letter: string; sharePath: string } + /** + * Saved under a drive letter mapped to the distro's share: the move reopens it there first. + * `share` is the drive's own share, `sharePath` the project's folder on it. + */ + mappedDrive?: { letter: string; share: string; sharePath: string } } const DRIVE_PATH = /^[A-Za-z]:[\\/]/ +const SHARE_CACHE_TTL_MS = 60_000 +// Per drive letter, so a menu opened again shows its item at once instead of after the lookup. +const shareCache = new Map() -/** The share path of a drive-letter path once main resolved it; null for any other path. */ +function cachedShare(letter: string): { share: string | null } | null { + const entry = shareCache.get(letter) + return entry && Date.now() - entry.at < SHARE_CACHE_TTL_MS ? entry : null +} + +/** The share a drive letter maps to once main resolved it; null for any other drive. */ function useMappedDriveShare(path: string | null): string | null { - const [resolved, setResolved] = useState<{ path: string; share: string | null } | null>(null) - const wanted = path && DRIVE_PATH.test(path) ? path : null + const letter = path && DRIVE_PATH.test(path) ? path[0].toUpperCase() : null + const [resolved, setResolved] = useState<{ letter: string; share: string | null } | null>(null) useEffect(() => { - if (!wanted) { + if (!letter || cachedShare(letter)) { return } let current = true // Main bounds and caches the lookup per drive letter. - void resolveWslMappedDrivePath(wanted).then((share) => { + void resolveWslMappedDrivePath(`${letter}:\\`).then((share) => { + shareCache.set(letter, { share, at: Date.now() }) if (current) { - setResolved({ path: wanted, share }) + setResolved({ letter, share }) } }) return () => { current = false } - }, [wanted]) - return wanted && resolved?.path === wanted ? resolved.share : null + }, [letter]) + if (!letter) { + return null + } + return cachedShare(letter)?.share ?? (resolved?.letter === letter ? resolved.share : null) } /** The host a local project's folder could move to, or null where no move is offered. */ @@ -79,21 +99,25 @@ export function useWslMoveTargetForPath( return offered ? wslMoveTargetOfPath(offered, share, environments) : null } -/** `share` is the resolved share path of a drive-letter `path`, else null. */ +/** `share` is the share a drive-letter `path`'s drive maps to, else null. */ export function wslMoveTargetOfPath( path: string, share: string | null, environments: Parameters[0] ): WslMoveTarget | null { const uncDistro = wslHostMovableDistroOfPath(path) - const sharePath = uncDistro || !DRIVE_PATH.test(path) ? null : share + const letter = path[0]?.toUpperCase() ?? '' + const sharePath = + uncDistro || !share || !DRIVE_PATH.test(path) + ? null + : wslMappedDrivePathToShare(path, { letter, share }) const distro = uncDistro ?? (sharePath ? wslHostMovableDistroOfPath(sharePath) : null) const host = distro ? findWslHostForDistro(environments, distro) : null if (!host) { return null } - return sharePath - ? { distro: host.distro, mappedDrive: { letter: path[0].toUpperCase(), sharePath } } + return sharePath && share + ? { distro: host.distro, mappedDrive: { letter, share, sharePath } } : { distro: host.distro } } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 97082c6c362..0a9517aa159 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -24841,7 +24841,9 @@ "retry": "Try again", "confirm": "Restart and continue", "failed": "Orca could not reopen this project, so nothing changed.", - "restarting": "Restarting Orca to reopen this project…" + "restarting": "Restarting Orca to reopen this project…", + "pausing": "Pausing terminals…", + "restartingLabel": "Restarting…" } }, "onboarding": { @@ -25269,12 +25271,14 @@ "differingState": "Orca saved different details for this folder under both its WSL path and {{drivePath}}, so nothing changed.", "projectSplit": "This project also holds a repository that isn’t converting, so nothing changed.", "driveNotMapped": "That drive no longer points into this distro, so nothing changed.", - "windowsDriveFolder": "This folder is a Windows drive seen through WSL, so it stays on this computer." + "windowsDriveFolder": "This folder is a Windows drive seen through WSL, so it stays on this computer.", + "driveUnverifiable": "Orca couldn’t check where that drive points just now, so nothing changed. Try again in a moment." }, "mappedDrive": { "notMapped": "Drive {{letter}}: no longer points into this distro, so nothing changed.", "mixed": "Some of this project’s folders aren’t on drive {{letter}}:, so they can’t move with it.", - "notOnDrive": "This project isn’t on drive {{letter}}: on this computer." + "notOnDrive": "This project isn’t on drive {{letter}}: on this computer.", + "unverifiable": "Orca couldn’t check where drive {{letter}}: points just now, so nothing changed. Try again in a moment." } }, "runtime": { diff --git a/src/shared/wsl-move/wsl-drive-unc-conversion-types.ts b/src/shared/wsl-move/wsl-drive-unc-conversion-types.ts index 9bfc4db764a..8cb0abe3f6d 100644 --- a/src/shared/wsl-move/wsl-drive-unc-conversion-types.ts +++ b/src/shared/wsl-move/wsl-drive-unc-conversion-types.ts @@ -14,6 +14,8 @@ export type WslDriveUncConversionRequest = { * UNC path instead, so the WSL move can take them. Absent: the D1c conversion. */ mappedDriveLetter?: string + /** The share the window showed for that drive; a drive remapped since is refused. */ + mappedDriveShare?: string } export type WslDriveUncConversionBlocker = @@ -32,8 +34,10 @@ export type WslDriveUncConversionBlocker = | 'not-windows-drive-mount' | 'windows-drive-folder' } - /** The mapped drive no longer points into the requested distro (`mappedDriveLetter`). */ + /** The mapped drive no longer points where the window showed (`mappedDriveShare`). */ | { kind: 'drive-not-mapped' } + /** Windows didn't say in time where the drive points (a distro still starting, say). */ + | { kind: 'drive-unverifiable' } | { kind: 'windows-git-missing' } /** WSL Git made these worktrees; their links are Linux paths Windows Git can't follow. */ | { kind: 'wsl-authored-worktrees'; repoId: string; paths: string[] } diff --git a/src/shared/wsl-move/wsl-drive-unc-renderer-store-keys.ts b/src/shared/wsl-move/wsl-drive-unc-renderer-store-keys.ts index 8eedec81316..096ed0c1c50 100644 --- a/src/shared/wsl-move/wsl-drive-unc-renderer-store-keys.ts +++ b/src/shared/wsl-move/wsl-drive-unc-renderer-store-keys.ts @@ -25,6 +25,8 @@ export type WslDriveUncRendererKeys = { worktreeId: (worktreeId: string) => string | null /** A path inside a converted folder, in its converted form; null for any other path. */ path: (path: string) => string | null + /** A comparison-form key inside a converted folder, re-keyed in comparison form; else null. */ + comparisonKey: (key: string) => string | null } export function wslDriveUncRendererKeys( @@ -34,14 +36,13 @@ export function wslDriveUncRendererKeys( > ): WslDriveUncRendererKeys { const ids = new Map(conversion.worktreeIds) - const respelling = wslDriveUncRespelling(conversion) + const respelling = wslDriveUncRespelling(conversion, conversion.rootPaths) const roots = conversion.rootPaths.flatMap((root) => { const converted = respelling.path(root) return converted ? [normalizeRuntimePathForComparison(converted)] : [] }) const path = (value: string): string | null => { - // Quick-open keeps its roots in comparison form, which folds both UNC spellings into one. - const converted = respelling.comparisonForm(value) ?? respelling.path(value) + const converted = respelling.path(value) if (!converted) { return null } @@ -51,7 +52,11 @@ export function wslDriveUncRendererKeys( ) return inRoot ? converted : null } - return { worktreeId: (worktreeId) => ids.get(worktreeId) ?? null, path } + return { + worktreeId: (worktreeId) => ids.get(worktreeId) ?? null, + path, + comparisonKey: respelling.comparisonForm + } } function parseArray(value: string): unknown[] | null { @@ -84,10 +89,9 @@ export function convertedQuickOpenHistoryScope( return null } const nextId = keys.worktreeId(worktreeId) - const nextRoot = keys.path(root) - return nextId !== null && nextRoot !== null - ? JSON.stringify([route, nextId, normalizeRuntimePathForComparison(nextRoot)]) - : null + // Quick-open keeps its roots in comparison form, which folds both UNC spellings into one. + const nextRoot = keys.comparisonKey(root) + return nextId !== null && nextRoot !== null ? JSON.stringify([route, nextId, nextRoot]) : null } /** `[worktreeId, environment, sshTarget, filePath]`, as buildFileViewPreferenceKey writes it. */ diff --git a/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts b/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts index 2886d16097e..109a5dd6900 100644 --- a/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts +++ b/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts @@ -48,7 +48,9 @@ describe('wslDriveUncRespelling for a mapped drive', () => { }) it('leaves the D1c respelling as it was', () => { - const d1c = wslDriveUncRespelling({ distro: 'Ubuntu' }) + const d1c = wslDriveUncRespelling({ distro: 'Ubuntu' }, [ + String.raw`\\wsl.localhost\Ubuntu\mnt\c\src` + ]) expect(d1c.path(String.raw`\\wsl.localhost\Ubuntu\mnt\c\src`)).toBe(String.raw`C:\src`) expect(d1c.comparisonForm('//wsl/ubuntu/mnt/c/src')).toBe('c:/src') expect(d1c.path(String.raw`W:\home`)).toBeNull() @@ -80,4 +82,19 @@ describe('wslDriveUncRendererKeys for a mapped drive', () => { ) expect(keys.path(String.raw`W:\home\me\other`)).toBeNull() }) + + it("keeps the root's case for a mixed-case folder, whose key is folded", () => { + const oldId = String.raw`r::W:\home\me\App` + const newId = String.raw`r::\\wsl.localhost\Ubuntu\home\me\App` + const keys = wslDriveUncRendererKeys({ + distro: 'Ubuntu', + mappedDrive: DRIVE, + worktreeIds: [[oldId, newId]], + rootPaths: [String.raw`W:\home\me\App`] + }) + const route = { executionHostId: 'local' } + expect( + convertedQuickOpenHistoryScope(JSON.stringify([route, oldId, 'w:/home/me/app']), keys) + ).toBe(JSON.stringify([route, newId, '//wsl/ubuntu/home/me/App'])) + }) }) diff --git a/src/shared/wsl-move/wsl-drive-unc-respelling.ts b/src/shared/wsl-move/wsl-drive-unc-respelling.ts index efa4f1f3c81..48a9aa1bf30 100644 --- a/src/shared/wsl-move/wsl-drive-unc-respelling.ts +++ b/src/shared/wsl-move/wsl-drive-unc-respelling.ts @@ -4,6 +4,7 @@ * to a distro share to that share's UNC path (`W:\home\x` -> `\\wsl.localhost\\home\x`), which * the WSL move can then take. */ +import { normalizeRuntimePathForComparison } from '../file-access/cross-platform-path' import { parseWslUncPath, wslUncDrivePathToWindows } from '../file-access/wsl-paths' /** A drive letter mapped to a distro share, as the resolver read it when the conversion began. */ @@ -14,27 +15,56 @@ export type WslDriveUncRespelling = { path: (value: string) => string | null /** A `file:` URL's converted spelling and the converted path it names; null otherwise. */ fileUrl: (value: string) => { url: string; path: string } | null - /** A `normalizeRuntimePathForComparison` key's converted spelling, in that form; null otherwise. */ + /** + * A `normalizeRuntimePathForComparison` key at or inside a converted root, re-keyed in that form; + * null otherwise. Folded case can't be unfolded, so the root's own spelling supplies it. + */ comparisonForm: (value: string) => string | null } -export function wslDriveUncRespelling(conversion: { - distro: string - mappedDrive?: WslMappedDrive | null -}): WslDriveUncRespelling { - return conversion.mappedDrive - ? mappedDriveRespelling(conversion.mappedDrive) - : uncDriveRespelling(conversion.distro) +type PathMap = Omit & { + /** A string only `normalizeRuntimePathForComparison` produces in this conversion's source form. */ + isComparisonKey: (value: string) => boolean } -function uncDriveRespelling(distro: string): WslDriveUncRespelling { +export function wslDriveUncRespelling( + conversion: { distro: string; mappedDrive?: WslMappedDrive | null }, + /** The converting folders as saved; comparison keys are re-keyed only at or inside one. */ + roots: readonly string[] = [] +): WslDriveUncRespelling { + const map = conversion.mappedDrive + ? mappedDriveRespelling(conversion.mappedDrive) + : uncDriveRespelling(conversion.distro) + const rootKeys = roots.flatMap((root) => { + const converted = map.path(root) + return converted ? [{ from: normalizeRuntimePathForComparison(root), to: converted }] : [] + }) + return { + path: map.path, + fileUrl: map.fileUrl, + comparisonForm: (value) => { + if (!map.isComparisonKey(value)) { + return null + } + for (const { from, to } of rootKeys) { + const prefix = from.endsWith('/') ? from : `${from}/` + if (value === from || value.startsWith(prefix)) { + const rest = value === from ? '' : value.slice(prefix.length) + const joined = rest ? `${to.replace(/[\\/]+$/, '')}\\${rest.replace(/\//g, '\\')}` : to + return normalizeRuntimePathForComparison(joined) + } + } + return null + } + } +} + +function uncDriveRespelling(distro: string): PathMap { const fileUrl = new RegExp( `^file://(?:wsl\\.localhost|wsl\\$)/${escapeRegExp(distro)}(/mnt/[a-z](?:/[^?#]*)?)([?#].*)?$`, 'i' ) - const comparisonForm = new RegExp( - `^//wsl/${escapeRegExp(distro.toLowerCase())}/mnt/([a-z])(/[\\s\\S]*)?$` - ) + const comparisonKey = new RegExp(`^//wsl/${escapeRegExp(distro.toLowerCase())}/mnt/[a-z](?:/|$)`) return { path: (value) => wslUncDrivePathToWindows(value, distro), fileUrl: (value) => { @@ -50,10 +80,7 @@ function uncDriveRespelling(distro: string): WslDriveUncRespelling { const tail = match[1].slice('/mnt/c'.length) return { url: `file:///${drive.slice(0, 2)}${tail || '/'}${match[2] ?? ''}`, path: drive } }, - comparisonForm: (value) => { - const match = comparisonForm.exec(value) - return match ? `${match[1]}:${match[2] ?? '/'}` : null - } + isComparisonKey: (value) => comparisonKey.test(value) } } @@ -84,7 +111,8 @@ export function wslMappedDrivePathToShare(value: string, drive: WslMappedDrive): return segments.length > 0 ? `${share}\\${segments.join('\\')}` : share } -function mappedDriveRespelling(drive: WslMappedDrive): WslDriveUncRespelling { +function mappedDriveRespelling(drive: WslMappedDrive): PathMap { + const letter = drive.letter.toLowerCase() const shareUrl = parseWslUncPath(drive.share) ? shareFileUrl(drive.share) : null return { path: (value) => wslMappedDrivePathToShare(value, drive), @@ -99,8 +127,9 @@ function mappedDriveRespelling(drive: WslMappedDrive): WslDriveUncRespelling { // The share's own segments encoded; the tail keeps the URL's encoding. return path ? { url: `${shareUrl}${match[2] ?? '/'}${match[3] ?? ''}`, path } : null }, - // A drive key in comparison form (`w:/x`) is also a real spelling, which `path` takes. - comparisonForm: () => null + // Folded: lowercase, forward slashes only. Saved paths keep their `W:\` spelling. + isComparisonKey: (value) => + value.startsWith(`${letter}:/`) && value === value.toLowerCase() && !value.includes('\\') } }