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 2c9a7dd8f7a..ef3ad65375a 100644 --- a/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts +++ b/src/main/ipc/wsl/wsl-drive-unc-conversion-handlers.ts @@ -1,5 +1,6 @@ /** - * IPC for converting UNC Windows-drive projects to their drive paths (D1c), and what the last + * IPC for converting UNC Windows-drive projects to their drive paths (D1c) or mapped-drive projects + * to their distro share, and what the last * startup did with a journaled conversion. Refused off Windows and while the internal WSL hosts * gate is closed, before anything is read. */ @@ -7,7 +8,8 @@ import { randomUUID } from 'node:crypto' import { app, ipcMain, type IpcMainInvokeEvent } from 'electron' import type { WslDriveUncConversionRequest, - WslDriveUncConversionResult + WslDriveUncConversionResult, + WslMappedDriveMoveDue } from '../../../shared/wsl-move/wsl-drive-unc-conversion-types' import { relaunchApp } from '../../startup/quit/app-relaunch' import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' @@ -21,8 +23,10 @@ import { quitProcess } from '../../startup/quit/process-quit-request' import { startWslDriveUncConversion } from '../../wsl/filesystem/wsl-drive-unc-conversion-run' import { lastWslDriveUncConversionOutcomes, + takeWslMappedDriveMovesDue, type WslDriveUncConversionOutcome } from '../../wsl/filesystem/wsl-drive-unc-conversion-startup' +import { resolveWslMappedDrivePath } 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' @@ -39,6 +43,7 @@ import { readWslDistroDriveMounts } from '../../wsl/filesystem/wsl-drive-unc-mou export const WSL_DRIVE_UNC_CONVERSION_CHANNELS = [ 'wslDriveUnc:convert', 'wslDriveUnc:lastOutcomes', + 'wslDriveUnc:takeMappedDriveMovesDue', 'wslDriveUnc:listPendingRendererRewrites', 'wslDriveUnc:recordStoreRewritten' ] as const @@ -65,6 +70,7 @@ export function registerWslDriveUncConversionHandlers( userDataPath, profileId: activeProfileId, readDriveMounts: readWslDistroDriveMounts, + readMappedDriveShare: (letter) => resolveWslMappedDrivePath(`${letter}:\\`), readProfileState: async () => { await store.flushPendingOrThrowAsync() return readProfileProjectTransferState(activeProfileId, getProfileUserDataPath()).state @@ -96,6 +102,13 @@ export function registerWslDriveUncConversionHandlers( ipcMain.handle('wslDriveUnc:lastOutcomes', (): WslDriveUncConversionOutcome[] => wslHostsGateOpen() ? lastWslDriveUncConversionOutcomes() : [] ) + ipcMain.handle( + 'wslDriveUnc:takeMappedDriveMovesDue', + (event: IpcMainInvokeEvent): WslMappedDriveMoveDue[] => + wslHostsGateOpen() && getTrustedUIRendererWebContents()?.id === event.sender.id + ? takeWslMappedDriveMovesDue() + : [] + ) ipcMain.handle( 'wslDriveUnc:listPendingRendererRewrites', (): WslDriveUncPendingRendererRewrite[] => @@ -135,15 +148,20 @@ function parseRequest(value: unknown): WslDriveUncConversionRequest { const distro = 'distro' in record ? record.distro : undefined const repoIds = 'repoIds' in record ? record.repoIds : undefined const folderWorkspaceIds = 'folderWorkspaceIds' in record ? record.folderWorkspaceIds : [] + const mappedDriveLetter = 'mappedDriveLetter' in record ? record.mappedDriveLetter : undefined if ( typeof distro !== 'string' || !distro || !isIdList(repoIds) || - !isIdList(folderWorkspaceIds) + !isIdList(folderWorkspaceIds) || + (mappedDriveLetter !== undefined && + (typeof mappedDriveLetter !== 'string' || !/^[A-Za-z]$/.test(mappedDriveLetter))) ) { throw new Error('wsl_drive_unc_invalid_args') } - return { distro, repoIds, folderWorkspaceIds } + return mappedDriveLetter === undefined + ? { distro, repoIds, folderWorkspaceIds } + : { distro, repoIds, folderWorkspaceIds, mappedDriveLetter } } function isIdList(value: unknown): value is string[] { diff --git a/src/main/persistence/moving-wsl-projects/quiescence/wsl-move-fence.ts b/src/main/persistence/moving-wsl-projects/quiescence/wsl-move-fence.ts index fcb77333e37..e0314403fc1 100644 --- a/src/main/persistence/moving-wsl-projects/quiescence/wsl-move-fence.ts +++ b/src/main/persistence/moving-wsl-projects/quiescence/wsl-move-fence.ts @@ -7,6 +7,7 @@ import { } from '../../../../shared/wsl-move/wsl-move-cutover' import { scanWslMoveCutovers } from '../cutover-recovery/wsl-move-cutover-journal' import { comparableWslPath } from '../manifest-scope/wsl-move-comparable-path' +import { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-drive-unc-respelling' import { wslMoveScopeRootPaths } from '../manifest-scope/wsl-move-scope-roots' import { listWslDriveUncConversions, @@ -72,9 +73,13 @@ export function withWslDriveUncConversions( } const fencedRoots = [ ...fence.fencedRoots, - ...pending.map(({ distro, rootPaths }) => ({ + ...pending.map(({ distro, rootPaths, mappedDrive }) => ({ distro, - roots: rootPaths.flatMap((root) => comparableWslPath(root, distro) ?? []) + roots: rootPaths.flatMap((root) => { + // A mapped drive's folder is fenced by its share path, the spelling a spawn there resolves to. + const unc = mappedDrive ? wslMappedDrivePathToShare(root, mappedDrive) : root + return (unc && comparableWslPath(unc, distro)) ?? [] + }) })) ] return { ...fence, fenced, fencedRoots } diff --git a/src/main/wsl/filesystem/wsl-drive-unc-conversion-journal.ts b/src/main/wsl/filesystem/wsl-drive-unc-conversion-journal.ts index e38353b3c33..713bf481b50 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-journal.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-journal.ts @@ -2,12 +2,14 @@ * The journal of a UNC Windows-drive project conversion (D1c): `wsl-drive-unc-conversions/.json` * beside the profile. Written once the scope's panes are asleep, and read at the next startup, * before the profile loads, which runs the conversion. Its own directory, so an older build never - * reads it as a move. + * reads it as a move. A mapped-drive respelling (`mappedDrive`) has a directory of its own too, so + * an older build never runs it as a D1c conversion. * * - `prepared`: nothing outside the journal changed yet; a failed profile rewrite drops the record. * - `profile-rewritten`: the profile names the drive paths; the other stores only go forward. */ import { isRecord } from '../../../shared/orcad-migration/orcad-migration-manifest-fields' +import type { WslMappedDrive } from '../../../shared/wsl-move/wsl-drive-unc-respelling' import { createMigrationJournalDirectory } from '../../persistence/migrating-orcad-catalog/cutover-journals/migration-journal-directory' export const WSL_DRIVE_UNC_CONVERSION_PHASES = ['prepared', 'profile-rewritten'] as const @@ -19,9 +21,14 @@ export type WslDriveUncConversion = { /** The profile the conversion rewrites; null in a journal written before it was recorded. */ profileId: string | null distro: string + /** Set for a mapped drive respelled to its share path; absent for D1c. */ + mappedDrive?: WslMappedDrive repoIds: string[] folderWorkspaceIds: string[] - /** The converting projects' folders, as UNC paths, for a spawn that names no workspace. */ + /** + * The converting projects' folders as saved (UNC, or on the mapped drive), for a spawn that + * names no workspace. + */ rootPaths: string[] phase: WslDriveUncConversionPhase /** Old → new worktree ids, from the profile rewrite; empty before it. */ @@ -49,20 +56,32 @@ export function onWslDriveUncConversionJournalChange( return () => changeListeners.delete(listener) } -const journals = createMigrationJournalDirectory({ - directoryName: 'wsl-drive-unc-conversions', +const journalOptions = { maxFileBytes: 4 * 1024 * 1024, - parse: parseWslDriveUncConversion, - unreadable: (detail) => new WslDriveUncConversionJournalUnreadableError(detail), - onChange: (userDataPath) => { + unreadable: (detail: string) => new WslDriveUncConversionJournalUnreadableError(detail), + onChange: (userDataPath: string) => { for (const listener of changeListeners) { listener(userDataPath) } } +} + +const journals = createMigrationJournalDirectory({ + ...journalOptions, + directoryName: 'wsl-drive-unc-conversions', + parse: (value) => withoutMappedDrive(parseWslDriveUncConversion(value)) +}) + +const mappedDriveJournals = createMigrationJournalDirectory({ + ...journalOptions, + directoryName: 'wsl-mapped-drive-conversions', + parse: (value) => withMappedDrive(parseWslDriveUncConversion(value)) }) export function listWslDriveUncConversions(userDataPath: string): WslDriveUncConversion[] { - return journals.list(userDataPath).map((record) => structuredClone(record)) + return [...journals.list(userDataPath), ...mappedDriveJournals.list(userDataPath)].map((record) => + structuredClone(record) + ) } /** A profile's conversions; one journaled before profiles were recorded counts for every profile. */ @@ -79,11 +98,26 @@ export function writeWslDriveUncConversion( userDataPath: string, record: WslDriveUncConversion ): void { - journals.write(userDataPath, record) + ;(record.mappedDrive ? mappedDriveJournals : journals).write(userDataPath, record) } export function removeWslDriveUncConversion(userDataPath: string, migrationId: string): void { journals.remove(userDataPath, migrationId) + mappedDriveJournals.remove(userDataPath, migrationId) +} + +function withoutMappedDrive(record: WslDriveUncConversion): WslDriveUncConversion { + if (record.mappedDrive) { + throw new Error('wsl_drive_unc_conversion_mapped_drive_misplaced') + } + return record +} + +function withMappedDrive(record: WslDriveUncConversion): WslDriveUncConversion { + if (!record.mappedDrive) { + throw new Error('wsl_drive_unc_conversion_mapped_drive_missing') + } + return record } function parseWslDriveUncConversion(value: unknown): WslDriveUncConversion { @@ -111,6 +145,9 @@ function parseWslDriveUncConversion(value: unknown): WslDriveUncConversion { migrationId: value.migrationId, profileId: isText(value.profileId) ? value.profileId : null, distro: value.distro, + ...(isMappedDrive(value.mappedDrive) + ? { mappedDrive: { letter: value.mappedDrive.letter, share: value.mappedDrive.share } } + : {}), repoIds: [...value.repoIds], folderWorkspaceIds: [...value.folderWorkspaceIds], rootPaths: [...value.rootPaths], @@ -122,6 +159,15 @@ function parseWslDriveUncConversion(value: unknown): WslDriveUncConversion { } } +function isMappedDrive(value: unknown): value is WslMappedDrive { + return ( + isRecord(value) && + typeof value.letter === 'string' && + /^[A-Za-z]$/.test(value.letter) && + isText(value.share) + ) +} + function isText(value: unknown): value is string { return typeof value === 'string' && value.length > 0 } diff --git a/src/main/wsl/filesystem/wsl-drive-unc-conversion-renderer.ts b/src/main/wsl/filesystem/wsl-drive-unc-conversion-renderer.ts index 154635026dd..4092a36790d 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-renderer.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-renderer.ts @@ -35,6 +35,7 @@ export function listPendingWslDriveUncRendererRewrites( .map((record) => ({ migrationId: record.migrationId, distro: record.distro, + ...(record.mappedDrive ? { mappedDrive: record.mappedDrive } : {}), worktreeIds: record.worktreeIds, rootPaths: record.rootPaths, storeIds: RENDERER_STORE_IDS.filter((id) => !record.rewrittenStores.includes(id)) 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 56f6220ce44..7120c640f2e 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,6 +49,7 @@ function deps(overrides: Partial = {}): WslDriveUn userDataPath: root, profileId: 'profile-1', readDriveMounts: async () => [{ mountPoint: '/mnt/c', windowsRoot: 'C:\\' }], + readMappedDriveShare: async () => null, readProfileState: async () => state(), pause: vi.fn(async () => ({ panes: [] })), runWindowsGit: vi.fn(async (args: string[]) => @@ -159,3 +160,72 @@ describe('startWslDriveUncConversion', () => { ).toEqual(['profile-1', 'profile-2']) }) }) + +describe('startWslDriveUncConversion for a mapped drive', () => { + const SHARE = String.raw`\\wsl.localhost\Ubuntu` + const MAPPED = String.raw`W:\home\me\App` + + function mappedState(): PersistedState { + const value = state() + value.repos = [{ id: 'repo-a', path: MAPPED, displayName: 'App', badgeColor: '', addedAt: 0 }] + value.folderWorkspaces = [] + return value + } + + const MAPPED_REQUEST = { distro: 'Ubuntu', repoIds: ['repo-a'], mappedDriveLetter: 'w' } + + 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) + }) + expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ + outcome: 'restarting', + migrationId: 'conv-1' + }) + expect(run.readMappedDriveShare).toHaveBeenCalledWith('w') + expect(run.runWindowsGit).not.toHaveBeenCalled() + const [journal] = listWslDriveUncConversions(root) + expect(journal).toMatchObject({ + mappedDrive: { letter: 'W', share: SHARE }, + repoIds: ['repo-a'], + rootPaths: [MAPPED], + worktreeIds: [[`repo-a::${MAPPED}`, String.raw`repo-a::\\wsl.localhost\Ubuntu\home\me\App`]] + }) + expect(run.restart).toHaveBeenCalledOnce() + }) + + 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` + }) + expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ + outcome: 'refused', + blockers: [{ kind: 'drive-not-mapped' }] + }) + expect(run.pause).not.toHaveBeenCalled() + expect(listWslDriveUncConversions(root)).toEqual([]) + }) + + it('refuses a project already saved under its share path', async () => { + const run = deps({ + readProfileState: async () => { + const value = mappedState() + value.repos.push({ + id: 'repo-b', + path: String.raw`\\wsl.localhost\Ubuntu\home\me\App`, + displayName: 'App', + badgeColor: '', + addedAt: 0 + }) + return value + }, + readMappedDriveShare: async () => SHARE + }) + expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({ + outcome: 'refused', + blockers: [{ kind: 'not-convertible', id: 'repo-a', reason: 'duplicate-windows-project' }] + }) + }) +}) 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 b4407a2e6ed..b51884f3840 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-run.ts @@ -1,5 +1,6 @@ /** - * Starts converting UNC Windows-drive projects to their drive paths (D1c): check them, put their + * Starts converting UNC Windows-drive projects to their drive paths (D1c), or respelling mapped-drive + * projects to their distro share (so the WSL move can take them): check them, put their * terminals to sleep through the mover's pause (gate, then Sleep keeping each shell's folder), * journal the conversion and restart. The next startup rewrites everything before the window * opens (wsl-drive-unc-conversion-startup.ts); the woken panes reattach to their renamed sessions. @@ -27,9 +28,16 @@ import { WslDriveUncKeyCollisionError } from './wsl-drive-unc-identity-rewrite' import { collectWslDriveUncScope, withNestedWslDriveUncProjects, - wslDriveUncDuplicatesSplitBy + wslDriveUncDuplicatesSplitBy, + type WslDriveUncScope, + type WslDriveUncTarget } from './wsl-drive-unc-project-scope' -import { wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths' +import { collectWslMappedDriveScope } from './wsl-mapped-drive-project-scope' +import { parseWslUncPath, wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths' +import { + wslDriveUncRespelling, + type WslMappedDrive +} from '../../../shared/wsl-move/wsl-drive-unc-respelling' import { rewriteWslDriveUncState, wslDriveUncRewriteRoots } from './wsl-drive-unc-state-rewrite' import type { WindowsDriveMount } from './wsl-guest-drive-mountinfo' @@ -42,6 +50,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 /** 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> @@ -60,8 +70,24 @@ 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 + if (mappedDrive === null) { + return refused([{ kind: 'drive-not-mapped' }]) + } const state = await deps.readProfileState() - const checked = checkScope(state, request, (await deps.readDriveMounts(request.distro)) ?? []) + const checked = mappedDrive + ? checkScope(state, request, collectWslMappedDriveScope(state, mappedDrive), mappedDrive) + : checkScope( + state, + request, + collectWslDriveUncScope( + state, + request.distro, + (await deps.readDriveMounts(request.distro)) ?? [] + ) + ) if ('blockers' in checked) { return refused(checked.blockers) } @@ -70,6 +96,7 @@ export async function startWslDriveUncConversion( try { ;({ worktreeIds } = rewriteWslDriveUncState(state, { distro: request.distro, + mappedDrive, repoIds, folderWorkspaceIds })) @@ -77,7 +104,8 @@ export async function startWslDriveUncConversion( return refused([stateConflict(error)]) } const repos = state.repos.filter((repo) => repoIds.includes(repo.id)) - const gitBlockers = await windowsGitBlockers(deps, repos, request.distro) + // A respelled project keeps the Git it ran; only D1c switches to Git for Windows. + const gitBlockers = mappedDrive ? [] : await windowsGitBlockers(deps, repos, request.distro) if (gitBlockers.length > 0) { return refused(gitBlockers) } @@ -101,6 +129,7 @@ export async function startWslDriveUncConversion( migrationId, profileId: deps.profileId, distro: request.distro, + ...(mappedDrive ? { mappedDrive } : {}), repoIds, folderWorkspaceIds, rootPaths: [ @@ -120,14 +149,34 @@ export async function startWslDriveUncConversion( return { outcome: 'restarting', migrationId } } +/** The drive's share, read now; null when it no longer maps into `distro`. */ +async function readMappedDrive( + deps: Pick, + letter: string, + distro: string +): Promise { + 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 } + : null +} + function checkScope( state: PersistedState, request: WslDriveUncConversionRequest, - mounts: readonly WindowsDriveMount[] + scope: WslDriveUncScope, + mappedDrive?: WslMappedDrive ): | { repoIds: string[]; folderWorkspaceIds: string[] } | { blockers: WslDriveUncConversionBlocker[] } { - const scope = collectWslDriveUncScope(state, request.distro, mounts) + const toTarget: WslDriveUncTarget = wslDriveUncRespelling({ + distro: request.distro, + mappedDrive + }).path const blockers: WslDriveUncConversionBlocker[] = [] const pick = (ids: readonly string[], allowed: readonly string[]): string[] => ids.filter((id) => { @@ -147,15 +196,15 @@ function checkScope( return { blockers } } const rewriteRoots = (project: { repoIds: string[]; folderWorkspaceIds: string[] }): string[] => - wslDriveUncRewriteRoots(state, { distro: request.distro, ...project }) + wslDriveUncRewriteRoots(state, { distro: request.distro, mappedDrive, ...project }) // Bare paths are re-keyed by folder, so a nested project's rows would move without its ids. const converting = withNestedWslDriveUncProjects( scope, - request.distro, + toTarget, { repoIds, folderWorkspaceIds }, rewriteRoots ) - const split = wslDriveUncDuplicatesSplitBy(state, scope, request.distro, converting, () => + const split = wslDriveUncDuplicatesSplitBy(state, scope, toTarget, converting, () => rewriteRoots(converting) ) return split.length > 0 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 e786470ee85..bc75a456c39 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-conversion-startup.ts @@ -30,6 +30,7 @@ import { orchestrationDbFile } from '../../runtime/orchestration/db/orchestratio import { journalDomainDatabasePath } from '../../native-chat/agent-session-journal/database/journal-domain-database' 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' export type WslDriveUncConversionStartupDeps = { /** Where the journal lives. */ @@ -42,7 +43,15 @@ export type WslDriveUncConversionStartupDeps = { } export type WslDriveUncConversionOutcome = - | { migrationId: string; outcome: 'converted'; repoIds: string[]; folderWorkspaceIds: string[] } + | { + migrationId: string + outcome: 'converted' + repoIds: string[] + folderWorkspaceIds: string[] + distro?: string + /** Set for a mapped-drive respelling, whose projects the WSL move takes next. */ + mappedDrive?: boolean + } /** The profile could not be rewritten; nothing changed, and the panes stay asleep. */ | { migrationId: string; outcome: 'rolled-back'; detail: string } /** The profile is converted; `store` failed and retries at the next startup. */ @@ -100,7 +109,9 @@ async function runOne( migrationId, outcome: 'converted', repoIds: record.repoIds, - folderWorkspaceIds: record.folderWorkspaceIds + folderWorkspaceIds: record.folderWorkspaceIds, + distro: record.distro, + ...(record.mappedDrive ? { mappedDrive: true } : {}) } } @@ -172,8 +183,35 @@ export function lastWslDriveUncConversionOutcomes(): WslDriveUncConversionOutcom return [...lastOutcomes] } +let movesTaken = false + +/** Once per run: a window reload must not open the move again. */ +export function takeWslMappedDriveMovesDue(): WslMappedDriveMoveDue[] { + if (movesTaken) { + return [] + } + movesTaken = true + return wslMappedDriveMovesDueOf(lastOutcomes) +} + +export function wslMappedDriveMovesDueOf( + outcomes: readonly WslDriveUncConversionOutcome[] +): WslMappedDriveMoveDue[] { + return outcomes.flatMap((outcome) => + outcome.outcome === 'converted' && outcome.mappedDrive && outcome.distro + ? [ + { + distro: outcome.distro, + repoIds: outcome.repoIds, + folderWorkspaceIds: outcome.folderWorkspaceIds + } + ] + : [] + ) +} + /** - * Startup, before the profile store opens: with nothing journaled it only lists one directory. + * Startup, before the profile store opens: with nothing journaled it only lists its directories. * Never throws; a conversion it can't finish stays journaled for the next startup. Only Windows * starts a conversion, but the journal alone says one is due, so this runs on any platform. */ 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 9a9e0b93c46..73ed4c4db63 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-identity-rewrite.ts @@ -1,8 +1,9 @@ /** * The re-key of a UNC Windows-drive project converting to its drive path (D1c): every identity * string that names one of its folders through the distro (`\\wsl.localhost\\mnt\c\x`) becomes - * the same folder's drive path (`C:\x`). Worktree ids, owner keys, PTY session ids and editor file - * ids are rebuilt by the export's composite rewriters; user text is never touched. + * the same folder's drive path (`C:\x`); for a mapped-drive conversion, `W:\x` becomes the share's + * UNC path. Worktree ids, owner keys, PTY session ids and editor file ids are rebuilt by the + * export's composite rewriters; user text is never touched. */ import { isDeepStrictEqual } from 'node:util' import { normalizeRuntimePathForComparison } from '../../../shared/file-access/cross-platform-path' @@ -24,13 +25,18 @@ import { rewriteOrcadMigrationPathValue, type OrcadMigrationPathRewriter } from '../../persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite' -import { wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths' +import { + wslDriveUncRespelling, + type WslMappedDrive +} from '../../../shared/wsl-move/wsl-drive-unc-respelling' export type WslDriveUncRewriteScope = { distro: string + /** Set when the conversion takes a mapped drive's paths to its share instead. */ + mappedDrive?: WslMappedDrive | null repoIds: ReadonlySet folderWorkspaceIds: ReadonlySet - /** UNC folders of the converting projects; a bare path is rewritten only at or under one. */ + /** The converting projects' folders as saved; a bare path is rewritten only at or under one. */ roots: readonly string[] } @@ -43,54 +49,27 @@ export type WslDriveUncRewriter = { const VERBATIM_KEYS: ReadonlySet = new Set(['priorWorktreeIds']) export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDriveUncRewriter { - const fileUrl = new RegExp( - `^file://(?:wsl\\.localhost|wsl\\$)/${escapeRegExp(scope.distro)}(/mnt/[a-z](?:/[^?#]*)?)([?#].*)?$`, - 'i' - ) - const comparisonForm = new RegExp( - `^//wsl/${escapeRegExp(scope.distro.toLowerCase())}/mnt/([a-z])(/[\\s\\S]*)?$` - ) + const respelling = wslDriveUncRespelling(scope) const roots = scope.roots.flatMap((root) => { - const drive = wslUncDrivePathToWindows(root, scope.distro) - return drive ? [normalizeRuntimePathForComparison(drive)] : [] + const converted = respelling.path(root) + return converted ? [normalizeRuntimePathForComparison(converted)] : [] }) - const inRoot = (drivePath: string): boolean => { - const comparable = normalizeRuntimePathForComparison(drivePath) + const inRoot = (convertedPath: string): boolean => { + const comparable = normalizeRuntimePathForComparison(convertedPath) return roots.some( (root) => comparable === root || comparable.startsWith(root.endsWith('/') ? root : `${root}/`) ) } - const fileUrlDrivePath = ( - value: string - ): { drive: string; tail: string; extra: string } | null => { - const match = fileUrl.exec(value) - if (!match) { - return null - } - const linux = safeDecode(match[1]) - const drive = linux - ? wslUncDrivePathToWindows(`//wsl.localhost/${scope.distro}${linux}`, scope.distro) - : null - if (!drive) { - return null - } - // `/mnt/c/x` → `C:/x`, keeping the URL's own encoding of the tail. - const tail = match[1].slice('/mnt/c'.length) - return { drive, tail, extra: match[2] ?? '' } - } - // Any drive path of the distro: an id's owner was checked first. + // Any converted path: an id's owner was checked first. const drive: OrcadMigrationPathRewriter = { path: (value, form) => { if (form === 'relative') { return value } if (form === 'url') { - const parsed = fileUrlDrivePath(value) - return parsed - ? `file:///${parsed.drive.slice(0, 2)}${parsed.tail || '/'}${parsed.extra}` - : value + return respelling.fileUrl(value)?.url ?? value } - return wslUncDrivePathToWindows(value, scope.distro) ?? value + return respelling.path(value) ?? value } } const ownerInScope = (owner: string): boolean => { @@ -105,12 +84,7 @@ export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDr ) } const barePath = (value: string): string => { - const comparison = comparisonForm.exec(value) - if (comparison) { - const mapped = `${comparison[1]}:${comparison[2] ?? '/'}` - return inRoot(mapped) ? mapped : value - } - const mapped = wslUncDrivePathToWindows(value, scope.distro) + const mapped = respelling.comparisonForm(value) ?? respelling.path(value) return mapped && inRoot(mapped) ? mapped : value } const identity = (value: string): string => { @@ -137,8 +111,8 @@ export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDr return ownerInScope(value) ? rewriteOrcadMigrationPathValue(value, 'owner-key', drive) : value } if (/^file:/i.test(value)) { - const parsed = fileUrlDrivePath(value) - return parsed && inRoot(parsed.drive) ? drive.path(value, 'url') : value + const parsed = respelling.fileUrl(value) + return parsed && inRoot(parsed.path) ? parsed.url : value } return barePath(value) } @@ -231,15 +205,3 @@ function isEmptyValue(value: unknown): boolean { } return typeof value === 'object' && Object.keys(value).length === 0 } - -function safeDecode(value: string): string | null { - try { - return decodeURIComponent(value) - } catch { - return null - } -} - -function escapeRegExp(value: string): string { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -} diff --git a/src/main/wsl/filesystem/wsl-drive-unc-project-scope.ts b/src/main/wsl/filesystem/wsl-drive-unc-project-scope.ts index 66950b11191..913ea16412c 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-project-scope.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-project-scope.ts @@ -30,6 +30,8 @@ export type WslDriveUncRefusal = | 'not-windows-drive-mount' /** A folder of it nests with one of a refused project, whose paths would then be split. */ | 'overlaps-refused-project' + /** A mapped drive's folder that is a Windows drive seen through the distro (`W:\mnt\c`). */ + | 'windows-drive-folder' export type WslDriveUncScope = { repoIds: string[] @@ -50,6 +52,7 @@ export function collectWslDriveUncScope( mounts: readonly WindowsDriveMount[] ): WslDriveUncScope { const scope: WslDriveUncScope = { repoIds: [], folderWorkspaceIds: [], refused: [] } + const uncDrive: WslDriveUncTarget = (path) => wslUncDrivePathToWindows(path, distro) const onDriveMount = (path: string): boolean => { const target = wslUncDrivePathToWindows(path, distro) return target !== null && wslUncPathIsWindowsDriveFolder(path, distro, target, mounts) @@ -86,7 +89,7 @@ export function collectWslDriveUncScope( scope.repoIds.push(repo.id) } } - refuseOverlaps(scope, state.repos, distro) + refuseWslDriveUncOverlaps(scope, state.repos, uncDrive) const hostState = { repos: [...state.repos], projectGroups: [...state.projectGroups] } // This row alone: another host may hold a folder workspace with the same id. const isLocal = (workspace: FolderWorkspace): boolean => @@ -122,14 +125,18 @@ export function collectWslDriveUncScope( } /** A bare path is re-keyed by the folder it lies in, so nested projects must convert together. */ -function refuseOverlaps(scope: WslDriveUncScope, repos: readonly Repo[], distro: string): void { +export function refuseWslDriveUncOverlaps( + scope: WslDriveUncScope, + repos: readonly Repo[], + toTarget: WslDriveUncTarget +): void { // A same-folder duplicate is the project it duplicates; nested ones: wslDriveUncDuplicatesSplitBy. const refusedIds = new Set( scope.refused .filter((entry) => entry.reason !== 'duplicate-windows-project') .map((entry) => entry.id) ) - const comparable = (repo: Repo): string[] => driveRoots(wslMoveRepoPaths(repo), distro) + const comparable = (repo: Repo): string[] => targetRoots(wslMoveRepoPaths(repo), toTarget) const refusedRoots = repos.filter((repo) => refusedIds.has(repo.id)).flatMap(comparable) const overlapping = new Set( repos @@ -148,7 +155,7 @@ function refuseOverlaps(scope: WslDriveUncScope, repos: readonly Repo[], distro: /** The picked projects and every convertible one nesting with them, which must convert together. */ export function withNestedWslDriveUncProjects( scope: WslDriveUncScope, - distro: string, + toTarget: WslDriveUncTarget, picked: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] }, /** The folders a conversion of just this project rewrites, its saved worktrees included. */ rewriteRoots: (project: { repoIds: string[]; folderWorkspaceIds: string[] }) => string[] @@ -159,12 +166,12 @@ export function withNestedWslDriveUncProjects( ...scope.repoIds.map((id) => ({ ids: repoIds, id, - roots: driveRoots(rewriteRoots({ repoIds: [id], folderWorkspaceIds: [] }), distro) + roots: targetRoots(rewriteRoots({ repoIds: [id], folderWorkspaceIds: [] }), toTarget) })), ...scope.folderWorkspaceIds.map((id) => ({ ids: folderWorkspaceIds, id, - roots: driveRoots(rewriteRoots({ repoIds: [], folderWorkspaceIds: [id] }), distro) + roots: targetRoots(rewriteRoots({ repoIds: [], folderWorkspaceIds: [id] }), toTarget) })) ] for (let added = true; added;) { @@ -192,7 +199,7 @@ export function withNestedWslDriveUncProjects( export function wslDriveUncDuplicatesSplitBy( state: WslDriveUncScopeState, scope: WslDriveUncScope, - distro: string, + toTarget: WslDriveUncTarget, converting: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] }, rewriteRoots: () => readonly string[] ): string[] { @@ -201,20 +208,20 @@ export function wslDriveUncDuplicatesSplitBy( return [] } const convertingFolders = new Set( - driveRoots( + targetRoots( [ ...state.repos.filter(({ id }) => converting.repoIds.includes(id)).map(({ path }) => path), ...state.folderWorkspaces .filter(({ id }) => converting.folderWorkspaceIds.includes(id)) .map(({ folderPath }) => folderPath) ], - distro + toTarget ) ) - const roots = driveRoots(rewriteRoots(), distro) + const roots = targetRoots(rewriteRoots(), toTarget) const splits = (folder: string, paths: readonly string[]): boolean => - !driveRoots([folder], distro).some((path) => convertingFolders.has(path)) && - driveRoots(paths, distro).some((path) => roots.some((root) => isInside(path, root))) + !targetRoots([folder], toTarget).some((path) => convertingFolders.has(path)) && + targetRoots(paths, toTarget).some((path) => roots.some((root) => isInside(path, root))) return duplicates.flatMap(({ kind, id }) => { if (kind === 'repo') { const repo = state.repos.find((entry) => entry.id === id) @@ -225,10 +232,13 @@ export function wslDriveUncDuplicatesSplitBy( }) } -function driveRoots(paths: readonly string[], distro: string): string[] { +/** A saved path's converted spelling (WslDriveUncRespelling.path); null when it does not convert. */ +export type WslDriveUncTarget = (path: string) => string | null + +function targetRoots(paths: readonly string[], toTarget: WslDriveUncTarget): string[] { return paths.flatMap((path) => { - const drive = wslUncDrivePathToWindows(path, distro) - return drive ? [normalizeRuntimePathForComparison(drive)] : [] + const target = toTarget(path) + return target ? [normalizeRuntimePathForComparison(target)] : [] }) } 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 48739fc5d2d..c4e372e4ea6 100644 --- a/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts +++ b/src/main/wsl/filesystem/wsl-drive-unc-state-rewrite.ts @@ -1,7 +1,8 @@ /** - * The profile state of UNC Windows-drive projects converted to their drive paths (D1c): each field - * that can name one is re-keyed by wsl-drive-unc-identity-rewrite.ts, and the projects switch to - * Git for Windows with their terminals still in the distro. Pure; the caller writes the result. + * The profile state of UNC Windows-drive projects converted to their drive paths (D1c), or of + * mapped-drive projects respelled to their share: each field that can name one is re-keyed by + * wsl-drive-unc-identity-rewrite.ts. D1c projects also switch to Git for Windows with their + * terminals still in the distro. Pure; the caller writes the result. */ import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host' @@ -23,7 +24,11 @@ import { withCrossStoreChildKey } from '../../../shared/worktree/lineage/cross-s import { WSL_DRIVE_UNC_STATE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-drive-unc-state-dispositions' import { wslMoveRepoPaths } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-scope' import { withoutDiscoveryShadows } from './wsl-drive-unc-discovery-shadows' -import { wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths' +import { + wslDriveUncRespelling, + type WslDriveUncRespelling, + type WslMappedDrive +} from '../../../shared/wsl-move/wsl-drive-unc-respelling' import { createWslDriveUncRewriter, mergeWslDriveUncKeyedEntries, @@ -35,6 +40,8 @@ export type WslDriveUncStateScope = { distro: string repoIds: readonly string[] folderWorkspaceIds: readonly string[] + /** Set for a mapped drive respelled to its share; its runtime choices stay as they were. */ + mappedDrive?: WslMappedDrive | null } export type WslDriveUncStateRewrite = { @@ -54,10 +61,12 @@ export function rewriteWslDriveUncState( const state = withoutDiscoveryShadows(saved, worktreeIds) const rewriter = createWslDriveUncRewriter({ distro: scope.distro, + mappedDrive: scope.mappedDrive, repoIds, folderWorkspaceIds, roots }) + const respelling = wslDriveUncRespelling(scope) const next: PersistedState = { ...state } for (const [field, disposition] of Object.entries(WSL_DRIVE_UNC_STATE_DISPOSITIONS)) { if (disposition === 'rewrite' && isStateField(field) && state[field] !== undefined) { @@ -70,13 +79,15 @@ export function rewriteWslDriveUncState( rewriter ) } - next.projects = sameIfUnchanged( - next.projects, - withWindowsGit(next.projects, repoIds, scope.distro) - ) + if (!scope.mappedDrive) { + next.projects = sameIfUnchanged( + next.projects, + withWindowsGit(next.projects, repoIds, scope.distro) + ) + } next.projectGroups = sameIfUnchanged( next.projectGroups, - withConvertedGroupFolders(next, repoIds, folderWorkspaceIds, scope.distro) + withConvertedGroupFolders(next, repoIds, folderWorkspaceIds, respelling) ) next.worktreeMeta = withPriorIds(next.worktreeMeta, worktreeIds, (id) => [id]) if (next.worktreeMetaByIdentity) { @@ -148,6 +159,7 @@ function collectRewriteRoots( ] const ids = createWslDriveUncRewriter({ distro: scope.distro, + mappedDrive: scope.mappedDrive, repoIds, folderWorkspaceIds, roots @@ -245,7 +257,7 @@ function withConvertedGroupFolders( state: PersistedState, repoIds: ReadonlySet, folderWorkspaceIds: ReadonlySet, - distro: string + respelling: WslDriveUncRespelling ): PersistedState['projectGroups'] { return state.projectGroups.map((group) => { const members = [ @@ -256,7 +268,7 @@ function withConvertedGroupFolders( .filter((folder) => folder.projectGroupId === group.id) .map((folder) => folderWorkspaceIds.has(folder.id)) ] - const parentPath = group.parentPath && wslUncDrivePathToWindows(group.parentPath, distro) + const parentPath = group.parentPath && respelling.path(group.parentPath) return parentPath && members.length > 0 && members.every(Boolean) ? { ...group, parentPath } : group 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 new file mode 100644 index 00000000000..a5c317528ca --- /dev/null +++ b/src/main/wsl/filesystem/wsl-mapped-drive-conversion-startup.test.ts @@ -0,0 +1,237 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs' +// Runs on Node's SQLite: the startup reopens the profile read-only, which Bun's macOS build refuses. +import '../../sqlite/sync-database' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { getDefaultPersistedState } from '../../../shared/orca-profiles/constants' +import type { PersistedState } from '../../../shared/orca-profiles/persisted-state-types' +import { readProfileProjectTransferState } from '../../orca-profiles/project-transfer/profile-project-domain-state' +import { getOrcaProfileStateDatabaseFile } from '../../orca-profiles/profile-storage-paths' +import { openProfileStateDatabase } from '../../persistence/profile-state/database/profile-state-database' +import { importProfileStateJson } from '../../persistence/profile-state/documents/profile-state-documents' +import { resolveWslMoveFence } from '../../persistence/moving-wsl-projects/quiescence/wsl-move-fence' +import { + listWslDriveUncConversions, + writeWslDriveUncConversion, + type WslDriveUncConversion +} from './wsl-drive-unc-conversion-journal' +import { + runWslDriveUncConversionsAtStartup, + wslMappedDriveMovesDueOf +} from './wsl-drive-unc-conversion-startup' + +const PROFILE = 'profile-1' +const SHARE = String.raw`\\wsl.localhost\Ubuntu` +const MAPPED = String.raw`W:\home\me\App` +const UNC = String.raw`\\wsl.localhost\Ubuntu\home\me\App` +const OLD_ID = `repo-a::${MAPPED}` +const NEW_ID = `repo-a::${UNC}` + +let root: string + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-mapped-drive-startup-')) +}) + +afterEach(() => { + rmSync(root, { recursive: true, force: true }) +}) + +function profileState(): PersistedState { + const state = getDefaultPersistedState('/home/me') + state.repos = [{ id: 'repo-a', path: MAPPED, displayName: 'App', badgeColor: '', addedAt: 0 }] + state.projectGroups = [ + { + id: 'group-w', + name: 'me', + parentPath: String.raw`W:\home\me`, + parentGroupId: null, + createdFrom: 'folder-scan', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 0, + updatedAt: 0 + } + ] + state.folderWorkspaces = [ + folder('notes', String.raw`W:\home\me\notes`), + // Another drive's folder is not the mapped drive's, even with the same tail. + folder('other', String.raw`X:\home\me\notes`) + ] + state.projects = [ + { + id: 'repo-a', + displayName: 'App', + badgeColor: '', + sourceRepoIds: ['repo-a'], + createdAt: 0, + updatedAt: 0, + localWindowsRuntimePreference: { kind: 'windows-host' } + } + ] + state.worktreeMeta = { + [OLD_ID]: { + displayName: 'App', + comment: 'keep me', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0 + } + } + state.workspaceSession.activeWorktreeId = OLD_ID + state.workspaceSession.tabsByWorktree = { + [OLD_ID]: [ + { + id: 'tab-1', + ptyId: `${OLD_ID}@@s1`, + worktreeId: OLD_ID, + title: 'shell', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0 + } + ] + } + return state +} + +function folder(id: string, folderPath: string): PersistedState['folderWorkspaces'][number] { + return { + id, + projectGroupId: id === 'notes' ? 'group-w' : '', + name: id, + folderPath, + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 0, + updatedAt: 0 + } +} + +function seedProfile(state: PersistedState): void { + const file = getOrcaProfileStateDatabaseFile(PROFILE, root) + mkdirSync(join(file, '..'), { recursive: true }) + const opened = openProfileStateDatabase(file, PROFILE) + try { + importProfileStateJson(opened.db, JSON.stringify(state)) + } finally { + opened.db.close() + } +} + +function journal(overrides: Partial = {}): void { + writeWslDriveUncConversion(root, { + version: 1, + migrationId: 'conv-1', + profileId: PROFILE, + distro: 'Ubuntu', + mappedDrive: { letter: 'W', share: SHARE }, + repoIds: ['repo-a'], + folderWorkspaceIds: ['notes'], + rootPaths: [MAPPED, String.raw`W:\home\me\notes`], + phase: 'prepared', + worktreeIds: [[OLD_ID, NEW_ID]], + rewrittenStores: [], + createdAt: '2026-11-16T00:00:00.000Z', + updatedAt: '2026-11-16T00:00:00.000Z', + ...overrides + }) +} + +function run() { + return runWslDriveUncConversionsAtStartup({ + userDataPath: root, + profileUserDataPath: root, + profileId: PROFILE, + stores: [] + }) +} + +describe('a mapped-drive conversion at startup', () => { + it('respells the projects to their share path and keeps their runtime choice', async () => { + seedProfile(profileState()) + journal() + const outcomes = await run() + expect(outcomes).toEqual([ + { + migrationId: 'conv-1', + outcome: 'converted', + repoIds: ['repo-a'], + folderWorkspaceIds: ['notes'], + distro: 'Ubuntu', + mappedDrive: true + } + ]) + const state = readProfileProjectTransferState(PROFILE, root).state + expect(state.repos[0].path).toBe(UNC) + expect(state.folderWorkspaces.map((folder) => folder.folderPath)).toEqual([ + String.raw`\\wsl.localhost\Ubuntu\home\me\notes`, + String.raw`X:\home\me\notes` + ]) + expect(state.worktreeMeta[NEW_ID]).toMatchObject({ + comment: 'keep me', + priorWorktreeIds: [OLD_ID] + }) + expect(state.workspaceSession.activeWorktreeId).toBe(NEW_ID) + // Every member converts, so the group's parent folder is respelled with them. + expect(state.projectGroups[0].parentPath).toBe(String.raw`\\wsl.localhost\Ubuntu\home\me`) + expect(state.workspaceSession.tabsByWorktree[NEW_ID]?.[0]).toMatchObject({ + 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' }) + expect(wslMappedDriveMovesDueOf(outcomes)).toEqual([ + { distro: 'Ubuntu', repoIds: ['repo-a'], folderWorkspaceIds: ['notes'] } + ]) + }) + + 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) + expect(existsSync(join(root, 'wsl-drive-unc-conversions'))).toBe(false) + expect(listWslDriveUncConversions(root)).toEqual([ + expect.objectContaining({ mappedDrive: { letter: 'W', share: SHARE } }) + ]) + }) + + it('fences the pending projects by their share path', () => { + journal() + const fence = resolveWslMoveFence(root) + expect([...fence.fenced.repoIds]).toEqual(['repo-a']) + expect([...fence.fenced.folderWorkspaceIds]).toEqual(['notes']) + expect(fence.fencedRoots).toEqual([ + { + distro: 'Ubuntu', + roots: ['//wsl.localhost/ubuntu/home/me/App', '//wsl.localhost/ubuntu/home/me/notes'] + } + ]) + }) + + it('reports no move due for a D1c conversion', () => { + expect( + wslMappedDriveMovesDueOf([ + { + migrationId: 'conv-2', + outcome: 'converted', + repoIds: ['repo-b'], + folderWorkspaceIds: [], + distro: 'Ubuntu' + } + ]) + ).toEqual([]) + }) +}) diff --git a/src/main/wsl/filesystem/wsl-mapped-drive-project-scope.test.ts b/src/main/wsl/filesystem/wsl-mapped-drive-project-scope.test.ts new file mode 100644 index 00000000000..6da0c76d876 --- /dev/null +++ b/src/main/wsl/filesystem/wsl-mapped-drive-project-scope.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest' +import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' +import type { Repo } from '../../../shared/repository/repo-types' +import { collectWslMappedDriveScope } from './wsl-mapped-drive-project-scope' + +const DRIVE = { letter: 'W', share: String.raw`\\wsl.localhost\Ubuntu` } + +function repo(id: string, path: string, extra: Partial = {}): Repo { + return { id, path, displayName: id, badgeColor: '', addedAt: 0, ...extra } +} + +function folder(id: string, folderPath: string, extra: Partial = {}) { + return { + id, + projectGroupId: '', + name: id, + folderPath, + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 0, + updatedAt: 0, + ...extra + } +} + +describe('collectWslMappedDriveScope', () => { + it('takes local repos and folders on the drive, and nothing elsewhere', () => { + const scope = collectWslMappedDriveScope( + { + repos: [ + repo('on-drive', String.raw`W:\home\me\app`), + repo('on-c', String.raw`C:\src\app`), + repo('already-unc', String.raw`\\wsl.localhost\Ubuntu\home\me\other`) + ], + folderWorkspaces: [folder('notes', String.raw`W:\home\me\notes`)], + projectGroups: [] + }, + DRIVE + ) + expect(scope).toEqual({ repoIds: ['on-drive'], folderWorkspaceIds: ['notes'], refused: [] }) + }) + + it('accepts a worktree folder already saved under the share path', () => { + const scope = collectWslMappedDriveScope( + { + repos: [ + repo('app', String.raw`W:\home\me\app`, { + worktreeBasePath: String.raw`\\wsl.localhost\Ubuntu\home\me\trees` + }) + ], + folderWorkspaces: [], + projectGroups: [] + }, + DRIVE + ) + expect(scope.repoIds).toEqual(['app']) + }) + + it('refuses split, remote, Windows-drive and already-saved projects', () => { + const scope = collectWslMappedDriveScope( + { + repos: [ + repo('split', String.raw`W:\home\me\app`, { worktreeBasePath: String.raw`D:\trees` }), + repo('remote', String.raw`W:\home\me\remote`, { connectionId: 'ssh-1' }), + repo('drvfs', String.raw`W:\mnt\c\src`), + repo('twin', String.raw`W:\home\me\twin`), + repo('twin-unc', String.raw`\\wsl.localhost\Ubuntu\home\me\twin`) + ], + folderWorkspaces: [], + projectGroups: [] + }, + DRIVE + ) + expect(scope.repoIds).toEqual([]) + expect(scope.refused).toEqual([ + { kind: 'repo', id: 'split', reason: 'mixed-locations' }, + { kind: 'repo', id: 'remote', reason: 'not-local' }, + { kind: 'repo', id: 'drvfs', reason: 'windows-drive-folder' }, + { kind: 'repo', id: 'twin', reason: 'duplicate-windows-project' } + ]) + }) + + it('refuses a repo nested in one it refused, whose paths would otherwise split', () => { + const scope = collectWslMappedDriveScope( + { + repos: [ + repo('outer', String.raw`W:\home\me\mono`, { worktreeBasePath: String.raw`D:\trees` }), + repo('inner', String.raw`W:\home\me\mono\packages\a`) + ], + folderWorkspaces: [], + projectGroups: [] + }, + DRIVE + ) + expect(scope.refused).toContainEqual({ + kind: 'repo', + id: 'inner', + reason: 'overlaps-refused-project' + }) + }) +}) diff --git a/src/main/wsl/filesystem/wsl-mapped-drive-project-scope.ts b/src/main/wsl/filesystem/wsl-mapped-drive-project-scope.ts new file mode 100644 index 00000000000..23bb6fc2af6 --- /dev/null +++ b/src/main/wsl/filesystem/wsl-mapped-drive-project-scope.ts @@ -0,0 +1,110 @@ +/** + * Projects saved under a drive letter mapped to a distro share (`W:\home\x` with `W:` -> + * `\\wsl.localhost\Ubuntu`). The WSL move only takes a project by its share path, so the + * conversion respells each in place first. This is the scope; nothing here writes. + */ +import { + getRepoExecutionHostId, + LOCAL_EXECUTION_HOST_ID +} from '../../../shared/execution-host/execution-host' +import { normalizeRuntimePathForComparison } from '../../../shared/file-access/cross-platform-path' +import { resolveFolderWorkspaceHost } from '../../../shared/folder-workspaces/folder-workspace-execution-host' +import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../shared/project/groups/project-group-types' +import type { Repo } from '../../../shared/repository/repo-types' +import { + parseWslUncPath, + wslHostMovableDistroOfPath, + wslUncPathToLinux +} from '../../../shared/file-access/wsl-paths' +import { + wslMappedDrivePathToShare, + type WslMappedDrive +} from '../../../shared/wsl-move/wsl-drive-unc-respelling' +import { wslMoveRepoPaths } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-scope' +import { + refuseWslDriveUncOverlaps, + type WslDriveUncRefusal, + type WslDriveUncScope +} from './wsl-drive-unc-project-scope' + +type WslMappedDriveScopeState = { + repos: readonly Repo[] + folderWorkspaces: readonly FolderWorkspace[] + projectGroups: readonly ProjectGroup[] +} + +export function collectWslMappedDriveScope( + state: WslMappedDriveScopeState, + drive: WslMappedDrive +): WslDriveUncScope { + const scope: WslDriveUncScope = { repoIds: [], folderWorkspaceIds: [], refused: [] } + const toShare = (path: string): string | null => wslMappedDrivePathToShare(path, drive) + const distro = parseWslUncPath(drive.share)?.distro ?? '' + const refusalOf = (paths: readonly string[]): WslDriveUncRefusal | null => { + // A folder already saved under the share path (a worktree, say) needs no respelling. + const shares = paths.map((path) => + wslUncPathToLinux(path, distro) === null ? toShare(path) : path + ) + if (shares.some((share) => share === null)) { + return 'mixed-locations' + } + // A Windows drive seen through the distro (`W:\mnt\c`) is not the distro's, so it can't move. + return shares.every((share) => share !== null && wslHostMovableDistroOfPath(share)) + ? null + : 'windows-drive-folder' + } + // Share paths already taken: the same folder saved under its share path is that project. + const claimedRepoPaths = new Set( + state.repos + .filter((repo) => getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID) + .map((repo) => normalizeRuntimePathForComparison(repo.path)) + ) + for (const repo of state.repos) { + const target = toShare(repo.path) + if (!target) { + continue + } + const key = normalizeRuntimePathForComparison(target) + const reason = + getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID + ? 'not-local' + : (refusalOf(wslMoveRepoPaths(repo)) ?? + (claimedRepoPaths.has(key) ? 'duplicate-windows-project' : null)) + if (reason) { + scope.refused.push({ kind: 'repo', id: repo.id, reason }) + } else { + claimedRepoPaths.add(key) + scope.repoIds.push(repo.id) + } + } + refuseWslDriveUncOverlaps(scope, state.repos, toShare) + const hostState = { repos: [...state.repos], projectGroups: [...state.projectGroups] } + // This row alone: another host may hold a folder workspace with the same id. + const isLocal = (workspace: FolderWorkspace): boolean => + resolveFolderWorkspaceHost({ ...hostState, folderWorkspaces: [workspace] }, workspace.id) + .kind === 'local' + const claimedFolderPaths = new Set( + state.folderWorkspaces + .filter(isLocal) + .map((workspace) => normalizeRuntimePathForComparison(workspace.folderPath)) + ) + for (const workspace of state.folderWorkspaces) { + const target = toShare(workspace.folderPath) + if (!target) { + continue + } + const key = normalizeRuntimePathForComparison(target) + const reason = !isLocal(workspace) + ? 'not-local' + : (refusalOf([workspace.folderPath]) ?? + (claimedFolderPaths.has(key) ? 'duplicate-windows-project' : null)) + if (reason) { + scope.refused.push({ kind: 'folder-workspace', id: workspace.id, reason }) + } else { + claimedFolderPaths.add(key) + scope.folderWorkspaceIds.push(workspace.id) + } + } + return scope +} diff --git a/src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts b/src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts index 7accdab7d44..d155bda28ef 100644 --- a/src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts +++ b/src/preload/api/wsl/wsl-drive-unc-conversion-bridge.ts @@ -1,15 +1,18 @@ import { ipcRenderer } from 'electron' import type { WslDriveUncConversionRequest, - WslDriveUncConversionResult + WslDriveUncConversionResult, + WslMappedDriveMoveDue } from '../../../shared/wsl-move/wsl-drive-unc-conversion-types' import type { WslDriveUncPendingRendererRewrite } from '../../../shared/wsl-move/wsl-drive-unc-renderer-store-keys' import type { WslMoveRecordStoreRewrittenResult } from '../../../shared/wsl-move/wsl-move-renderer-rewrite-types' -/** Converting a UNC Windows-drive project to its drive path; main gates every call. */ +/** Converting a UNC Windows-drive project to its drive path, or a mapped-drive one to its share; main gates every call. */ export type WslDriveUncConversionApi = { /** Checks, pauses the project's terminals and restarts the app to convert. */ convert: (request: WslDriveUncConversionRequest) => Promise + /** Mapped-drive projects this startup respelled, once per run, for the window to move. */ + takeMappedDriveMovesDue: () => Promise listPendingRendererRewrites: () => Promise recordStoreRewritten: (request: { migrationId: string @@ -19,6 +22,7 @@ export type WslDriveUncConversionApi = { export const wslDriveUncConversionApi: WslDriveUncConversionApi = { convert: (request) => ipcRenderer.invoke('wslDriveUnc:convert', request), + takeMappedDriveMovesDue: () => ipcRenderer.invoke('wslDriveUnc:takeMappedDriveMovesDue'), listPendingRendererRewrites: () => ipcRenderer.invoke('wslDriveUnc:listPendingRendererRewrites'), recordStoreRewritten: (request) => ipcRenderer.invoke('wslDriveUnc:recordStoreRewritten', request) } diff --git a/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx b/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx index 0126e440475..cc5869d8081 100644 --- a/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx +++ b/src/renderer/src/components/settings/repository/runtime/RepositoryWindowsRuntimeSection.tsx @@ -51,7 +51,7 @@ 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 wslMoveDistro = useWslMoveTargetForRepo(repo) + const wslMoveTarget = useWslMoveTargetForRepo(repo) // 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() @@ -79,8 +79,8 @@ export function RepositoryWindowsRuntimeSection({ className="space-y-3" forceVisible={forceVisible || matchesSettingsSearch(searchQuery, searchEntries)} > - {wslMoveDistro && repo ? ( - + {wslMoveTarget && repo ? ( + ) : ( + {folderWorkspaceId ? ( + + ) : null} )} 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 c8f4f3c4edb..5ebe8de1ba1 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 @@ -2,8 +2,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest' const toastError = vi.hoisted(() => vi.fn()) const openWslMoveDialogFor = vi.hoisted(() => vi.fn()) +const openWslMappedDriveMove = vi.hoisted(() => vi.fn()) +const resolveWslMappedDrivePath = vi.hoisted(() => + vi.fn(async (_path: string): Promise => null) +) vi.mock('sonner', () => ({ toast: { error: toastError } })) vi.mock('../wsl-move/wsl-move-entry', () => ({ openWslMoveDialogFor })) +vi.mock('../wsl-move/wsl-mapped-drive-move-store', () => ({ openWslMappedDriveMove })) +vi.mock('./wsl-mapped-drive-path', () => ({ resolveWslMappedDrivePath })) import { useAppStore } from '@/store' import { moveWslHostOfferProject } from './wsl-host-offer-move' @@ -20,6 +26,9 @@ const offer = { afterEach(() => { toastError.mockReset() openWslMoveDialogFor.mockReset() + openWslMappedDriveMove.mockReset() + resolveWslMappedDrivePath.mockReset() + resolveWslMappedDrivePath.mockResolvedValue(null) useAppStore.setState(initialState, true) }) @@ -33,14 +42,35 @@ describe('moveWslHostOfferProject', () => { expect(toastError).not.toHaveBeenCalled() }) - it('explains instead of opening a move when the add found the folder saved as W:', () => { + 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) + moveWslHostOfferProject(offer, { + status: 'completed', + repo: { id: 'repo-w', path: 'W:\\home\\u\\repo', displayName: 'repo' } + }) + await vi.waitFor(() => + expect(openWslMappedDriveMove).toHaveBeenCalledWith({ + distro: 'Ubuntu', + letter: 'W', + sharePath: offer.sharePath, + ref: { kind: 'repo', id: 'repo-w' }, + name: 'repo' + }) + ) + expect(openWslMoveDialogFor).not.toHaveBeenCalled() + expect(toastError).not.toHaveBeenCalled() + }) + + it('explains when the saved spelling no longer maps into the offered distro', async () => { moveWslHostOfferProject(offer, { status: 'completed', repo: { id: 'repo-w', path: 'W:\\home\\u\\repo' } }) - expect(openWslMoveDialogFor).not.toHaveBeenCalled() - expect(toastError).toHaveBeenCalledWith(expect.stringContaining('W:\\home\\u\\repo')) + await vi.waitFor(() => + expect(toastError).toHaveBeenCalledWith(expect.stringContaining('W:\\home\\u\\repo')) + ) + expect(openWslMappedDriveMove).not.toHaveBeenCalled() }) it('falls back to the share spelling when the add names no repo', () => { 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 6307c10417e..8f44eb0a1c3 100644 --- a/src/renderer/src/components/sidebar/wsl-host-offer-move.ts +++ b/src/renderer/src/components/sidebar/wsl-host-offer-move.ts @@ -12,6 +12,8 @@ import { } from '../../../../shared/execution-host/execution-host' import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types' 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 { wslMoveDistroOfPath } from '../wsl-move/wsl-move-scope-rows' import type { WslHostOffer } from './wsl-host-offer-actions' @@ -55,7 +57,7 @@ export function wslHostOfferProjectRef(path: string): WslMoveRowRef | null { } /** The repo a local add answered with (new or already saved); null for any other outcome. */ -function addedRepoOf(added: unknown): { id: string; path: string } | null { +function addedRepoOf(added: unknown): { id: string; path: string; name: string } | null { if (typeof added !== 'object' || added === null || !('repo' in added)) { return null } @@ -66,7 +68,14 @@ function addedRepoOf(added: unknown): { id: string; path: string } | null { typeof repo.id === 'string' && 'path' in repo && typeof repo.path === 'string' - ? { id: repo.id, path: repo.path } + ? { + id: repo.id, + path: repo.path, + name: + 'displayName' in repo && typeof repo.displayName === 'string' + ? repo.displayName + : repo.path + } : null } @@ -74,17 +83,35 @@ function addedRepoOf(added: unknown): { id: string; path: string } | null { * Opens the move with only the offered project checked; the user's Move is what moves it. * `added` is the add's answer, which names an already-saved project the path resolved to. */ +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()) { + openWslMappedDriveMove({ + distro: offer.distro, + letter: repo.path[0].toUpperCase(), + sharePath, + ref: { kind: 'repo', id: repo.id }, + name: repo.name + }) + return + } + toast.error( + translate( + 'sidebar.wslHostOffer.savedUnderAnotherPath', + "This folder is already a project here as {{path}}, which can't move to the {{distro}} host yet. Remove that project, then add the folder again to move it.", + { path: repo.path, distro: offer.distro } + ) + ) +} + export function moveWslHostOfferProject(offer: WslHostOffer, added?: unknown): void { const repo = addedRepoOf(added) - // The same folder was already saved under another spelling (`W:\…`), which the move can't take. + // The same folder was already saved under another spelling (`W:\…`): reopen it at its share first. if (repo && wslMoveDistroOfPath(repo.path)?.toLowerCase() !== offer.distro.toLowerCase()) { - toast.error( - translate( - 'sidebar.wslHostOffer.savedUnderAnotherPath', - "This folder is already a project here as {{path}}, which can't move to the {{distro}} host yet. Remove that project, then add the folder again to move it.", - { path: repo.path, distro: offer.distro } - ) - ) + void moveSavedUnderMappedDrive(offer, repo) return } const only = repo 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 0d911ae03e2..28b5e7647ba 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 @@ -1,4 +1,7 @@ -/** Plain-language copy for why a UNC Windows-drive project can't be converted right now. */ +/** + * Plain-language copy for why a UNC Windows-drive project can't be converted right now, or why a + * mapped-drive project (`mappedDriveLetter`) can't be reopened at its share path. + */ import { translate } from '@/i18n/i18n' import type { WslDriveUncConversionBlocker, @@ -8,11 +11,18 @@ import { wslDriveProjectBlockerMessage } from './wsl-drive-project-copy' export function wslDriveUncConversionMessages( result: Exclude, - drivePath: string + /** Where the project would reopen: its drive path, or its share path for a mapped drive. */ + drivePath: string, + mappedDriveLetter?: string ): string[] { switch (result.outcome) { case 'refused': - return result.blockers.map((blocker) => blockerMessage(blocker, drivePath)) + return result.blockers.map((blocker) => + mappedDriveLetter + ? (mappedDriveBlockerMessage(blocker, mappedDriveLetter) ?? + blockerMessage(blocker, drivePath)) + : blockerMessage(blocker, drivePath) + ) case 'terminals-blocked': return [ translate( @@ -30,8 +40,47 @@ export function wslDriveUncConversionMessages( } } +/** The mapped-drive wording where D1c's would name the wrong place; null to use D1c's. */ +function mappedDriveBlockerMessage( + blocker: WslDriveUncConversionBlocker, + letter: string +): string | null { + if (blocker.kind === 'drive-not-mapped') { + return translate( + 'wslDriveUnc.mappedDrive.notMapped', + 'Drive {{letter}}: no longer points into this distro, so nothing changed.', + { letter } + ) + } + if (blocker.kind !== 'not-convertible') { + return null + } + switch (blocker.reason) { + case 'mixed-locations': + return translate( + 'wslDriveUnc.mappedDrive.mixed', + 'Some of this project’s folders aren’t on drive {{letter}}:, so they can’t move with it.', + { letter } + ) + case 'not-local': + case 'not-in-scope': + return translate( + 'wslDriveUnc.mappedDrive.notOnDrive', + 'This project isn’t on drive {{letter}}: on this computer.', + { letter } + ) + default: + return null + } +} + function blockerMessage(blocker: WslDriveUncConversionBlocker, drivePath: string): string { switch (blocker.kind) { + case 'drive-not-mapped': + return translate( + 'wslDriveUnc.blocker.driveNotMapped', + 'That drive no longer points into this distro, so nothing changed.' + ) case 'conversion-pending': return translate( 'wslDriveUnc.blocker.pending', @@ -82,6 +131,11 @@ function blockerMessage(blocker: WslDriveUncConversionBlocker, drivePath: string 'wslDriveUnc.blocker.overlap', 'This project shares folders with a project Orca can’t convert, so they would split.' ) + case 'windows-drive-folder': + return translate( + 'wslDriveUnc.blocker.windowsDriveFolder', + 'This folder is a Windows drive seen through WSL, so it stays on this computer.' + ) case 'not-local': case 'not-in-scope': return translate( diff --git a/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx b/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx new file mode 100644 index 00000000000..cc0271db917 --- /dev/null +++ b/src/renderer/src/components/wsl-move/WslMappedDriveMoveDialog.tsx @@ -0,0 +1,83 @@ +import React from 'react' +import { useTranslate } from '@/i18n/use-translate' +import { Button } from '@/components/ui/button' +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle +} from '@/components/ui/dialog' +import { LoadingSpinner } from '@/components/LoadingSpinner' +import { + closeWslMappedDriveMove, + confirmWslMappedDriveMove, + useWslMappedDriveMoveStore +} from './wsl-mapped-drive-move-store' + +/** The step before moving a mapped-drive project: reopen it at its share path, which restarts Orca. */ +export function WslMappedDriveMoveDialog(): React.JSX.Element | null { + const t = useTranslate() + const request = useWslMappedDriveMoveStore((s) => s.request) + const step = useWslMappedDriveMoveStore((s) => s.step) + if (!request) { + return null + } + const { distro, letter, sharePath, name } = request + const converting = step.kind === 'converting' + return ( + !open && closeWslMappedDriveMove()}> + converting && event.preventDefault()} + onInteractOutside={(event) => converting && event.preventDefault()} + > + + + {t('wslMove.mappedDrive.title', 'Move {{name}} to the {{distro}} host', { + name, + distro + })} + + + {t( + 'wslMove.mappedDrive.description', + 'Orca opens this project through drive {{letter}}:. To move it, Orca first reopens it at {{sharePath}} and restarts. Tabs, terminals with their history, chats and settings come along. After the restart, the move opens so you can review it.', + { letter, sharePath } + )} + + + {step.kind === 'problem' ? ( +
+ {step.messages.map((message) => ( +

{message}

+ ))} +
+ ) : null} + + + + +
+
+ ) +} diff --git a/src/renderer/src/components/wsl-move/WslMoveDialog.tsx b/src/renderer/src/components/wsl-move/WslMoveDialog.tsx index 7589953eb87..ba9d6e5b157 100644 --- a/src/renderer/src/components/wsl-move/WslMoveDialog.tsx +++ b/src/renderer/src/components/wsl-move/WslMoveDialog.tsx @@ -33,7 +33,9 @@ import { import { adoptWslMoveProgress } from './wsl-move-run-adoption' import { closeWslMoveDialog, reloadAfterWslMove } from './wsl-move-dialog-close' import { RecoverableRenderErrorBoundary } from '../error-boundaries/RecoverableRenderErrorBoundary' -import { useWslHostsEnabled } from '../sidebar/use-wsl-hosts-enabled' +import { useWslHostsAcceptNewWork, useWslHostsEnabled } from '../sidebar/use-wsl-hosts-enabled' +import { WslMappedDriveMoveDialog } from './WslMappedDriveMoveDialog' +import { openWslMappedDriveMovesDue } from './wsl-mapped-drive-move-store' import { useConfirmationDialog } from '../confirmation-dialog-context' import { useWslMoveQuitGuard } from './use-wsl-move-quit-guard' import { WslMovePreviewBody, wslMoveNotMovingLines } from './WslMovePreviewBody' @@ -114,11 +116,29 @@ export function WslMoveDialogHost(): React.JSX.Element | null { : undefined, [enabled] ) - return open ? ( - - - - ) : null + // The restart that reopened mapped-drive projects at their share path continues into their move. + const acceptsNewWork = useWslHostsAcceptNewWork() + useEffect(() => { + if (acceptsNewWork) { + void openWslMappedDriveMovesDue() + } + }, [acceptsNewWork]) + return ( + <> + {open ? ( + + + + ) : null} + + + + + ) } function WslMoveDialog(): React.JSX.Element | null { diff --git a/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx b/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx index 483909614a6..dc69f4c7808 100644 --- a/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx +++ b/src/renderer/src/components/wsl-move/WslMoveProjectMenuItem.tsx @@ -1,21 +1,60 @@ import React from 'react' import { FolderInput } from 'lucide-react' 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 type { Repo } from '../../../../shared/repository/repo-types' -import { openWslMoveDialogFor, useWslMoveTargetForRepo } from './wsl-move-entry' +import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types' +import { useWslMoveTargetForPath, useWslMoveTargetForRepo } from './wsl-move-entry' +import { openWslMoveForProject } from './wsl-mapped-drive-move-store' -/** "Move to host…" for a local WSL project; nothing where no move is offered. */ -export function WslMoveProjectMenuItem({ repo }: { repo: Repo }): React.JSX.Element | null { +function MoveItem({ + target, + project, + name +}: { + target: ReturnType + project: WslMoveRowRef + name: string +}): React.JSX.Element | null { const t = useTranslate() - const distro = useWslMoveTargetForRepo(repo) - if (!distro) { + if (!target) { return null } return ( - openWslMoveDialogFor(distro, { kind: 'repo', id: repo.id })}> + openWslMoveForProject(target, project, name)}> - {t('wslMove.entry.projectMenu', 'Move to {{distro}} host…', { distro })} + {t('wslMove.entry.projectMenu', 'Move to {{distro}} host…', { distro: target.distro })} ) } + +/** "Move to host…" for a local WSL project; nothing where no move is offered. */ +export function WslMoveProjectMenuItem({ repo }: { repo: Repo }): React.JSX.Element | null { + const target = useWslMoveTargetForRepo(repo) + return ( + + ) +} + +/** The same for a local folder workspace, from its row's menu. */ +export function WslMoveFolderWorkspaceMenuItem({ + folderWorkspaceId +}: { + 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 target = useWslMoveTargetForPath(folder?.folderPath, !!folder) + return folder ? ( + + ) : null +} diff --git a/src/renderer/src/components/wsl-move/WslMoveRuntimeRow.tsx b/src/renderer/src/components/wsl-move/WslMoveRuntimeRow.tsx index 6bdf1565644..2b47200dca2 100644 --- a/src/renderer/src/components/wsl-move/WslMoveRuntimeRow.tsx +++ b/src/renderer/src/components/wsl-move/WslMoveRuntimeRow.tsx @@ -2,17 +2,21 @@ import React from 'react' import { useTranslate } from '@/i18n/use-translate' import { Button } from '@/components/ui/button' import { SettingsRow } from '../settings/form-controls/SettingsFormControls' -import { openWslMoveDialogFor } from './wsl-move-entry' +import type { WslMoveTarget } from './wsl-move-entry' +import { openWslMoveForProject } from './wsl-mapped-drive-move-store' /** The project runtime setting of a WSL project whose distro has a host: a move, not a toggle. */ export function WslMoveRuntimeRow({ - distro, - repoId + target, + repoId, + name }: { - distro: string + target: WslMoveTarget repoId: string + name: string }): React.JSX.Element { const t = useTranslate() + const { distro } = target return ( openWslMoveDialogFor(distro, { kind: 'repo', id: repoId })} + onClick={() => openWslMoveForProject(target, { kind: 'repo', id: repoId }, name)} > {t('wslMove.runtime.move', 'Move project')} 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 new file mode 100644 index 00000000000..6f231374ec7 --- /dev/null +++ b/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.test.ts @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const toast = vi.hoisted(() => vi.fn()) +const openWslMoveDialog = vi.hoisted(() => vi.fn(async () => {})) +vi.mock('sonner', () => ({ toast })) +vi.mock('./wsl-move-dialog-store', () => ({ openWslMoveDialog })) + +import { wslMoveTargetOfPath } from './wsl-move-entry' +import { + confirmWslMappedDriveMove, + openWslMappedDriveMovesDue, + openWslMoveForProject, + useWslMappedDriveMoveStore +} from './wsl-mapped-drive-move-store' + +const SHARE_PATH = String.raw`\\wsl.localhost\Ubuntu\home\u\repo` +const host = { + id: 'env-1', + name: 'Ubuntu host', + orcadDeployment: { kind: 'wsl' as const, distro: 'Ubuntu', localPort: 4100, remotePort: 4200 } +} + +const convert = vi.fn() +const takeMappedDriveMovesDue = vi.fn() + +beforeEach(() => { + vi.stubGlobal('window', { api: { wslDriveUnc: { convert, takeMappedDriveMovesDue } } }) +}) + +afterEach(() => { + convert.mockReset() + takeMappedDriveMovesDue.mockReset() + openWslMoveDialog.mockClear() + toast.mockReset() + vi.unstubAllGlobals() + useWslMappedDriveMoveStore.setState({ request: null, step: { kind: 'review' } }) +}) + +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({ + distro: 'Ubuntu', + mappedDrive: { letter: 'W', 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() + }) + + it('keeps a UNC project on the plain move', () => { + expect(wslMoveTargetOfPath(SHARE_PATH, null, [host])).toEqual({ distro: 'Ubuntu' }) + }) +}) + +describe('the mapped-drive move', () => { + const target = { distro: 'Ubuntu', mappedDrive: { letter: 'W', sharePath: SHARE_PATH } } + + it('asks main to reopen the project at its share path', async () => { + convert.mockResolvedValue({ outcome: 'restarting', migrationId: 'conv-1' }) + openWslMoveForProject(target, { kind: 'folder', id: 'notes' }, 'notes') + expect(openWslMoveDialog).not.toHaveBeenCalled() + await confirmWslMappedDriveMove() + expect(convert).toHaveBeenCalledWith({ + distro: 'Ubuntu', + repoIds: [], + folderWorkspaceIds: ['notes'], + mappedDriveLetter: 'W' + }) + expect(useWslMappedDriveMoveStore.getState().step).toEqual({ kind: 'converting' }) + expect(toast).toHaveBeenCalledOnce() + }) + + it('shows why main refused, worded for the mapped drive', async () => { + convert.mockResolvedValue({ outcome: 'refused', blockers: [{ kind: 'drive-not-mapped' }] }) + openWslMoveForProject(target, { kind: 'repo', id: 'repo-w' }, 'repo') + await confirmWslMappedDriveMove() + expect(useWslMappedDriveMoveStore.getState().step).toEqual({ + kind: 'problem', + messages: [expect.stringContaining('W:')] + }) + }) + + it('opens the move for the reopened project once the restart is done', async () => { + takeMappedDriveMovesDue.mockResolvedValue([ + { distro: 'Ubuntu', repoIds: ['repo-w'], folderWorkspaceIds: [] } + ]) + await openWslMappedDriveMovesDue() + expect(openWslMoveDialog).toHaveBeenCalledWith( + expect.objectContaining({ distro: 'Ubuntu', only: { kind: 'repo', id: 'repo-w' } }) + ) + }) +}) 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 new file mode 100644 index 00000000000..4c11154ebb6 --- /dev/null +++ b/src/renderer/src/components/wsl-move/wsl-mapped-drive-move-store.ts @@ -0,0 +1,121 @@ +/** + * Moving a project saved under a drive letter mapped to a distro share (`W:\home\x`). The WSL move + * takes a project only by its share path, so Orca first reopens it there, which restarts the app; + * the move then opens with that project (openWslMappedDriveMovesDue). + */ +import { create } from 'zustand' +import { toast } from 'sonner' +import { translate } from '@/i18n/i18n' +import type { + WslDriveUncConversionResult, + WslMappedDriveMoveDue +} from '../../../../shared/wsl-move/wsl-drive-unc-conversion-types' +import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types' +import { wslDriveUncConversionMessages } from '../wsl-drive-project/wsl-drive-unc-conversion-copy' +import { openWslMoveDialogFor, type WslMoveTarget } from './wsl-move-entry' + +export type WslMappedDriveMoveRequest = { + distro: string + /** The drive letter the project is saved under. */ + letter: 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 State = { request: WslMappedDriveMoveRequest | null; step: Step } + +export const useWslMappedDriveMoveStore = create()(() => ({ + request: null, + step: { kind: 'review' } +})) + +export function openWslMappedDriveMove(request: WslMappedDriveMoveRequest): void { + useWslMappedDriveMoveStore.setState({ request, step: { kind: 'review' } }) +} + +/** One project's move: the dialog, or for a mapped drive the reopen that comes first. */ +export function openWslMoveForProject( + target: WslMoveTarget, + ref: WslMoveRowRef, + name: string +): void { + if (target.mappedDrive) { + openWslMappedDriveMove({ distro: target.distro, ...target.mappedDrive, ref, name }) + return + } + openWslMoveDialogFor(target.distro, ref) +} + +export function closeWslMappedDriveMove(): void { + if (useWslMappedDriveMoveStore.getState().step.kind !== 'converting') { + useWslMappedDriveMoveStore.setState({ request: null, step: { kind: 'review' } }) + } +} + +export async function confirmWslMappedDriveMove(): Promise { + const { request } = useWslMappedDriveMoveStore.getState() + if (!request) { + return + } + useWslMappedDriveMoveStore.setState({ step: { kind: 'converting' } }) + let result: WslDriveUncConversionResult + try { + result = await window.api.wslDriveUnc.convert({ + distro: request.distro, + repoIds: request.ref.kind === 'repo' ? [request.ref.id] : [], + folderWorkspaceIds: request.ref.kind === 'folder' ? [request.ref.id] : [], + mappedDriveLetter: request.letter + }) + } catch { + useWslMappedDriveMoveStore.setState({ + step: { + kind: 'problem', + messages: [ + translate( + 'wslMove.mappedDrive.failed', + 'Orca could not reopen this project, so nothing changed.' + ) + ] + } + }) + return + } + if (useWslMappedDriveMoveStore.getState().request !== request) { + return + } + if (result.outcome === 'restarting') { + // The dialog stays on its spinner until the window goes away. + toast(translate('wslMove.mappedDrive.restarting', 'Restarting Orca to reopen this project…')) + return + } + useWslMappedDriveMoveStore.setState({ + step: { + kind: 'problem', + messages: wslDriveUncConversionMessages(result, request.sharePath, request.letter) + } + }) +} + +/** After the restart that reopened them: the move, with only those projects checked. */ +export async function openWslMappedDriveMovesDue(): Promise { + let due: WslMappedDriveMoveDue[] + try { + due = await window.api.wslDriveUnc.takeMappedDriveMovesDue() + } catch { + return + } + // One dialog at a time; a second distro's projects are listed on its host row. + const first = due[0] + if (!first) { + return + } + const refs: WslMoveRowRef[] = [ + ...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) +} 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 50869606bff..bc9bb59c9bc 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-entry.ts +++ b/src/renderer/src/components/wsl-move/wsl-move-entry.ts @@ -3,16 +3,23 @@ * offered only where WSL hosts are: the internal gate open (the preload omits the API otherwise) * and the Experimental switch on. Main refuses every call with the gate closed regardless. */ +import { useEffect, useState } from 'react' import { useAppStore } from '@/store' +import { + getRepoExecutionHostId, + LOCAL_EXECUTION_HOST_ID +} from '../../../../shared/execution-host/execution-host' +import { wslHostMovableDistroOfPath } from '../../../../shared/file-access/wsl-paths' import type { Repo } from '../../../../shared/repository/repo-types' import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types' import { useWslHostsAcceptNewWork, useWslHostServerFilesMissing } from '../sidebar/use-wsl-hosts-enabled' +import { resolveWslMappedDrivePath } from '../sidebar/wsl-mapped-drive-path' import { openWslMoveDialog } from './wsl-move-dialog-store' import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields' -import { wslMoveCatalogCandidates, wslMoveTargetForRepo } from './wsl-move-scope-rows' +import { findWslHostForDistro, wslMoveCatalogCandidates } from './wsl-move-scope-rows' export function openWslMoveDialogFor(distro: string, only?: WslMoveRowRef): void { void openWslMoveDialog({ @@ -28,12 +35,74 @@ export function openWslMoveDialogFor(distro: string, only?: WslMoveRowRef): void }) } -/** The distro host a local WSL repo can move to, or null where no move is offered. */ -export function useWslMoveTargetForRepo( - repo: Pick | null | undefined -): string | null { +/** 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 } +} + +const DRIVE_PATH = /^[A-Za-z]:[\\/]/ + +/** The share path of a drive-letter path once main resolved it; null for any other path. */ +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 + useEffect(() => { + if (!wanted) { + return + } + let current = true + // Main bounds and caches the lookup per drive letter. + void resolveWslMappedDrivePath(wanted).then((share) => { + if (current) { + setResolved({ path: wanted, share }) + } + }) + return () => { + current = false + } + }, [wanted]) + return wanted && resolved?.path === wanted ? resolved.share : null +} + +/** The host a local project's folder could move to, or null where no move is offered. */ +export function useWslMoveTargetForPath( + path: string | null | undefined, + isLocal: boolean +): WslMoveTarget | null { const enabled = useWslHostsAcceptNewWork() const serverFilesMissing = useWslHostServerFilesMissing() const environments = useAppStore((s) => s.runtimeEnvironments) - return enabled && !serverFilesMissing && repo ? wslMoveTargetForRepo(repo, environments) : null + const offered = enabled && !serverFilesMissing && isLocal && path ? path : null + const share = useMappedDriveShare(offered) + return offered ? wslMoveTargetOfPath(offered, share, environments) : null +} + +/** `share` is the resolved share path of a drive-letter `path`, 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 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 } } + : { distro: host.distro } +} + +/** The distro host a local WSL repo can move to, or null where no move is offered. */ +export function useWslMoveTargetForRepo( + repo: Pick | null | undefined +): WslMoveTarget | null { + return useWslMoveTargetForPath( + repo?.path, + !!repo && getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID + ) } diff --git a/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts b/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts index 435fd75ed4e..43188a46f0a 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts +++ b/src/renderer/src/components/wsl-move/wsl-move-scope-rows.ts @@ -67,18 +67,6 @@ export function findWslHostForDistro( return null } -/** The host a local WSL repo could move to, spelled as the host names its distro. */ -export function wslMoveTargetForRepo( - repo: Pick, - environments: readonly PublicKnownRuntimeEnvironment[] -): string | null { - if (getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID) { - return null - } - const distro = wslMoveDistroOfPath(repo.path) - return distro ? (findWslHostForDistro(environments, distro)?.distro ?? null) : null -} - function localRepo(catalog: WslMoveCatalog, id: string): Repo | undefined { return catalog.repos.find( (repo) => repo.id === id && getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 155bd2a0b51..97082c6c362 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -24833,6 +24833,15 @@ "attemptsExhausted": "it didn't complete after several tries" }, "finishPending": "An earlier move to the {{distro}} host is done there. Orca finishes it here when it restarts, or now with Check again." + }, + "mappedDrive": { + "title": "Move {{name}} to the {{distro}} host", + "description": "Orca opens this project through drive {{letter}}:. To move it, Orca first reopens it at {{sharePath}} and restarts. Tabs, terminals with their history, chats and settings come along. After the restart, the move opens so you can review it.", + "cancel": "Cancel", + "retry": "Try again", + "confirm": "Restart and continue", + "failed": "Orca could not reopen this project, so nothing changed.", + "restarting": "Restarting Orca to reopen this project…" } }, "onboarding": { @@ -25258,7 +25267,14 @@ "notDriveMount": "In this distro, that folder isn’t {{drivePath}}: it isn’t mounted from that Windows drive.", "notConvertible": "This project isn’t on a Windows drive on this computer.", "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." + "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." + }, + "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." } }, "runtime": { diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index c8a0df8e601..bfae81f77c6 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -170,6 +170,7 @@ function createWebPreloadApi(): Omit, 'settings' | 'plugins' // Desktop-only: a web client never converts this computer's projects. wslDriveUnc: { convert: () => Promise.resolve({ outcome: 'refused', blockers: [] }), + takeMappedDriveMovesDue: () => Promise.resolve([]), listPendingRendererRewrites: () => Promise.resolve([]), recordStoreRewritten: () => Promise.resolve({ recorded: false, reason: 'gated-off' }) }, 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 fa305df53a5..9bfc4db764a 100644 --- a/src/shared/wsl-move/wsl-drive-unc-conversion-types.ts +++ b/src/shared/wsl-move/wsl-drive-unc-conversion-types.ts @@ -1,4 +1,7 @@ -/** Converting a UNC Windows-drive project to its drive path (D1c); desktop-only IPC. */ +/** + * Converting a UNC Windows-drive project to its drive path (D1c), or a mapped-drive project to its + * share path; desktop-only IPC. + */ import type { WslMoveBlocker } from './wsl-move-driver-types' export type WslDriveUncConversionRequest = { @@ -6,6 +9,11 @@ export type WslDriveUncConversionRequest = { /** The repos to convert; each must be a local UNC project on one of the distro's drives. */ repoIds: string[] folderWorkspaceIds?: string[] + /** + * Respell projects saved under this drive letter, mapped to a share of `distro`, to the share's + * UNC path instead, so the WSL move can take them. Absent: the D1c conversion. + */ + mappedDriveLetter?: string } export type WslDriveUncConversionBlocker = @@ -22,7 +30,10 @@ export type WslDriveUncConversionBlocker = | 'duplicate-windows-project' | 'overlaps-refused-project' | 'not-windows-drive-mount' + | 'windows-drive-folder' } + /** The mapped drive no longer points into the requested distro (`mappedDriveLetter`). */ + | { kind: 'drive-not-mapped' } | { 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[] } @@ -36,6 +47,13 @@ export type WslDriveUncConversionBlocker = key?: string } +/** Mapped-drive projects this startup respelled to their share; the window opens their move. */ +export type WslMappedDriveMoveDue = { + distro: string + repoIds: string[] + folderWorkspaceIds: string[] +} + export type WslDriveUncConversionResult = /** Journaled with the panes asleep; the app restarts and converts before the window opens. */ | { outcome: 'restarting'; migrationId: 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 41c30c8b3b8..8eedec81316 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 @@ -6,14 +6,16 @@ import { normalizeRuntimePathForComparison } from '../file-access/cross-platform-path' import { LOCAL_EXECUTION_HOST_ID } from '../execution-host/execution-host' import type { PythonEnvironment } from '../editor/notebooks/notebook-kernel-types' -import { wslUncDrivePathToWindows } from '../file-access/wsl-paths' +import { wslDriveUncRespelling, type WslMappedDrive } from './wsl-drive-unc-respelling' /** A converted conversion's renderer half, as main lists it. */ export type WslDriveUncPendingRendererRewrite = { migrationId: string distro: string + /** Set for a mapped drive respelled to its share path. */ + mappedDrive?: WslMappedDrive worktreeIds: [string, string][] - /** The converted projects' folders, as UNC paths. */ + /** The converted projects' folders, as saved before the conversion. */ rootPaths: string[] /** Renderer stores still to record. */ storeIds: string[] @@ -21,35 +23,33 @@ export type WslDriveUncPendingRendererRewrite = { export type WslDriveUncRendererKeys = { worktreeId: (worktreeId: string) => string | null - /** A path inside a converted folder, in its drive form; null for any other path. */ + /** A path inside a converted folder, in its converted form; null for any other path. */ path: (path: string) => string | null } export function wslDriveUncRendererKeys( - conversion: Pick + conversion: Pick< + WslDriveUncPendingRendererRewrite, + 'distro' | 'mappedDrive' | 'worktreeIds' | 'rootPaths' + > ): WslDriveUncRendererKeys { const ids = new Map(conversion.worktreeIds) - const { distro } = conversion + const respelling = wslDriveUncRespelling(conversion) const roots = conversion.rootPaths.flatMap((root) => { - const drive = wslUncDrivePathToWindows(root, distro) - return drive ? [normalizeRuntimePathForComparison(drive)] : [] + const converted = respelling.path(root) + return converted ? [normalizeRuntimePathForComparison(converted)] : [] }) - const comparisonForm = /^\/\/wsl\/([^/]+)(\/[\s\S]*)?$/ const path = (value: string): string | null => { - // Quick-open keeps its roots in comparison form, which folds both UNC spellings into this. - const folded = comparisonForm.exec(value) - const drive = - folded && folded[1] === distro.toLowerCase() - ? wslUncDrivePathToWindows(`//wsl.localhost/${distro}${folded[2] ?? '/'}`, distro) - : wslUncDrivePathToWindows(value, distro) - if (!drive) { + // Quick-open keeps its roots in comparison form, which folds both UNC spellings into one. + const converted = respelling.comparisonForm(value) ?? respelling.path(value) + if (!converted) { return null } - const comparable = normalizeRuntimePathForComparison(drive) + const comparable = normalizeRuntimePathForComparison(converted) const inRoot = roots.some( (root) => comparable === root || comparable.startsWith(root.endsWith('/') ? root : `${root}/`) ) - return inRoot ? drive : null + return inRoot ? converted : null } return { worktreeId: (worktreeId) => ids.get(worktreeId) ?? null, path } } diff --git a/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts b/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts new file mode 100644 index 00000000000..2886d16097e --- /dev/null +++ b/src/shared/wsl-move/wsl-drive-unc-respelling.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from 'vitest' +import { wslDriveUncRespelling, wslMappedDrivePathToShare } from './wsl-drive-unc-respelling' +import { + convertedQuickOpenHistoryScope, + wslDriveUncRendererKeys +} from './wsl-drive-unc-renderer-store-keys' + +const DRIVE = { letter: 'W', share: String.raw`\\wsl.localhost\Ubuntu` } + +describe('wslMappedDrivePathToShare', () => { + it('respells either separator and drive case, keeping the Linux tail as written', () => { + expect(wslMappedDrivePathToShare(String.raw`W:\home\Me\App`, DRIVE)).toBe( + String.raw`\\wsl.localhost\Ubuntu\home\Me\App` + ) + expect(wslMappedDrivePathToShare('w:/home/me/app/', DRIVE)).toBe( + String.raw`\\wsl.localhost\Ubuntu\home\me\app` + ) + expect(wslMappedDrivePathToShare('W:\\', DRIVE)).toBe(DRIVE.share) + }) + + it('takes nothing off the mapped drive, drive-relative, or past its root', () => { + expect(wslMappedDrivePathToShare(String.raw`C:\home\me`, DRIVE)).toBeNull() + expect(wslMappedDrivePathToShare('W:home', DRIVE)).toBeNull() + expect(wslMappedDrivePathToShare(String.raw`\\wsl.localhost\Ubuntu\home`, DRIVE)).toBeNull() + expect(wslMappedDrivePathToShare(String.raw`W:\..\etc`, DRIVE)).toBeNull() + expect(wslMappedDrivePathToShare(String.raw`W:\home\me\..\you\.\x`, DRIVE)).toBe( + String.raw`\\wsl.localhost\Ubuntu\home\you\x` + ) + }) + + it('respells a drive mapped to a folder inside the distro', () => { + const home = { letter: 'H', share: String.raw`\\wsl$\Ubuntu\home\me` } + expect(wslMappedDrivePathToShare(String.raw`H:\App`, home)).toBe( + String.raw`\\wsl$\Ubuntu\home\me\App` + ) + }) +}) + +describe('wslDriveUncRespelling for a mapped drive', () => { + const respelling = wslDriveUncRespelling({ distro: 'Ubuntu', mappedDrive: DRIVE }) + + it('respells a file URL on the drive, keeping its own encoding and suffix', () => { + expect(respelling.fileUrl('file:///W:/home/me/My%20App/a.ts#L3')).toEqual({ + url: 'file://wsl.localhost/Ubuntu/home/me/My%20App/a.ts#L3', + path: String.raw`\\wsl.localhost\Ubuntu\home\me\My App\a.ts` + }) + expect(respelling.fileUrl('file:///C:/home/me/a.ts')).toBeNull() + }) + + it('leaves the D1c respelling as it was', () => { + const d1c = wslDriveUncRespelling({ distro: 'Ubuntu' }) + 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() + }) +}) + +describe('wslDriveUncRendererKeys for a mapped drive', () => { + it('re-keys a quick-open history inside a converted folder only', () => { + const keys = wslDriveUncRendererKeys({ + distro: 'Ubuntu', + mappedDrive: DRIVE, + worktreeIds: [ + [String.raw`r::W:\home\me\app`, String.raw`r::\\wsl.localhost\Ubuntu\home\me\app`] + ], + rootPaths: [String.raw`W:\home\me\app`] + }) + const route = { executionHostId: 'local' } + expect( + convertedQuickOpenHistoryScope( + JSON.stringify([route, String.raw`r::W:\home\me\app`, 'w:/home/me/app']), + keys + ) + ).toBe( + JSON.stringify([ + route, + String.raw`r::\\wsl.localhost\Ubuntu\home\me\app`, + '//wsl/ubuntu/home/me/app' + ]) + ) + expect(keys.path(String.raw`W:\home\me\other`)).toBeNull() + }) +}) diff --git a/src/shared/wsl-move/wsl-drive-unc-respelling.ts b/src/shared/wsl-move/wsl-drive-unc-respelling.ts new file mode 100644 index 00000000000..efa4f1f3c81 --- /dev/null +++ b/src/shared/wsl-move/wsl-drive-unc-respelling.ts @@ -0,0 +1,123 @@ +/** + * The path map of an in-place project conversion: a UNC Windows-drive project to its drive path + * (`\\wsl.localhost\\mnt\c\x` -> `C:\x`, D1c), or a project saved under a drive letter mapped + * 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 { parseWslUncPath, wslUncDrivePathToWindows } from '../file-access/wsl-paths' + +/** A drive letter mapped to a distro share, as the resolver read it when the conversion began. */ +export type WslMappedDrive = { letter: string; share: string } + +export type WslDriveUncRespelling = { + /** An absolute path's converted spelling; null for a path this conversion does not take. */ + 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. */ + comparisonForm: (value: string) => string | null +} + +export function wslDriveUncRespelling(conversion: { + distro: string + mappedDrive?: WslMappedDrive | null +}): WslDriveUncRespelling { + return conversion.mappedDrive + ? mappedDriveRespelling(conversion.mappedDrive) + : uncDriveRespelling(conversion.distro) +} + +function uncDriveRespelling(distro: string): WslDriveUncRespelling { + 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]*)?$` + ) + return { + path: (value) => wslUncDrivePathToWindows(value, distro), + fileUrl: (value) => { + const match = fileUrl.exec(value) + const linux = match ? safeDecode(match[1]) : null + const drive = linux + ? wslUncDrivePathToWindows(`//wsl.localhost/${distro}${linux}`, distro) + : null + if (!match || !drive) { + return null + } + // `/mnt/c/x` -> `C:/x`, keeping the URL's own encoding of the tail. + 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 + } + } +} + +const DRIVE_ABSOLUTE = /^([A-Za-z]):[\\/]([\s\S]*)$/ +const DRIVE_FILE_URL = /^file:\/\/\/([A-Za-z]):(\/[^?#]*)?([?#].*)?$/i + +/** `W:\home\x` -> `\\wsl.localhost\Ubuntu\home\x`; the tail keeps its case, which Linux needs. */ +export function wslMappedDrivePathToShare(value: string, drive: WslMappedDrive): string | null { + const match = DRIVE_ABSOLUTE.exec(value) + if (!match || match[1].toUpperCase() !== drive.letter.toUpperCase()) { + return null + } + const segments: string[] = [] + for (const segment of match[2].split(/[\\/]+/)) { + if (segment === '' || segment === '.') { + continue + } + if (segment === '..') { + // Past the drive root names no folder of the share. + if (segments.pop() === undefined) { + return null + } + continue + } + segments.push(segment) + } + const share = drive.share.replace(/[\\/]+$/, '') + return segments.length > 0 ? `${share}\\${segments.join('\\')}` : share +} + +function mappedDriveRespelling(drive: WslMappedDrive): WslDriveUncRespelling { + const shareUrl = parseWslUncPath(drive.share) ? shareFileUrl(drive.share) : null + return { + path: (value) => wslMappedDrivePathToShare(value, drive), + fileUrl: (value) => { + const match = DRIVE_FILE_URL.exec(value) + if (!shareUrl || !match || match[1].toUpperCase() !== drive.letter.toUpperCase()) { + return null + } + const decoded = safeDecode(match[2] ?? '/') + const path = + decoded === null ? null : wslMappedDrivePathToShare(`${drive.letter}:${decoded}`, drive) + // 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 + } +} + +/** `\\wsl.localhost\Ubuntu\home` -> `file://wsl.localhost/Ubuntu/home`. */ +function shareFileUrl(share: string): string { + const [server, ...segments] = share.split(/[\\/]+/).filter(Boolean) + return `file://${server}${segments.map((segment) => `/${encodeURIComponent(segment)}`).join('')}` +} + +function safeDecode(value: string): string | null { + try { + return decodeURIComponent(value) + } catch { + return null + } +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +}