feat(wsl-hosts): move projects saved under a mapped WSL drive letter

A project saved as W:\... (W: mapped to \\wsl.localhost\<distro>) had no way onto
its distro's host: the mover only takes projects by their \\wsl.localhost path.
"Move to <distro> host…" now appears for such projects (repo menu, repo runtime
setting, and a new folder-workspace menu item). It reuses the in-place project
conversion (journal, pause, restart, startup rewrite) with a new path map that
respells W:\... to the share path, then opens the existing move dialog after the
restart. The add-time offer for a folder already saved under a drive letter now
takes the same route instead of telling the user to remove and re-add it.

Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
Neil
2026-11-16 22:48:03 -08:00
parent e0174fc7c2
commit d7061e9022
33 changed files with 1636 additions and 189 deletions
@@ -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[] {
@@ -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 }
@@ -2,12 +2,14 @@
* The journal of a UNC Windows-drive project conversion (D1c): `wsl-drive-unc-conversions/<id>.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
}
@@ -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))
@@ -49,6 +49,7 @@ function deps(overrides: Partial<WslDriveUncConversionRunDeps> = {}): 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' }]
})
})
})
@@ -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<readonly WindowsDriveMount[] | null>
/** The distro share a drive letter maps to (`\\wsl.localhost\<d>`); null for any other drive. */
readMappedDriveShare: (letter: string) => Promise<string | null>
/** The saved profile, flushed first: the dry run must see what the restart will rewrite. */
readProfileState: () => Promise<PersistedState>
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<WslDriveUncConversionRunDeps, 'readMappedDriveShare'>,
letter: string,
distro: string
): Promise<WslMappedDrive | null> {
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
@@ -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.
*/
@@ -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\<d>\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<string>
folderWorkspaceIds: ReadonlySet<string>
/** 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<string> = 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, '\\$&')
}
@@ -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)] : []
})
}
@@ -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<string>,
folderWorkspaceIds: ReadonlySet<string>,
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
@@ -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<WslDriveUncConversion> = {}): 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([])
})
})
@@ -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> = {}): Repo {
return { id, path, displayName: id, badgeColor: '', addedAt: 0, ...extra }
}
function folder(id: string, folderPath: string, extra: Partial<FolderWorkspace> = {}) {
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'
})
})
})
@@ -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
}
@@ -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<WslDriveUncConversionResult>
/** Mapped-drive projects this startup respelled, once per run, for the window to move. */
takeMappedDriveMovesDue: () => Promise<WslMappedDriveMoveDue[]>
listPendingRendererRewrites: () => Promise<WslDriveUncPendingRendererRewrite[]>
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)
}
@@ -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 ? (
<WslMoveRuntimeRow distro={wslMoveDistro} repoId={repo.id} />
{wslMoveTarget && repo ? (
<WslMoveRuntimeRow target={wslMoveTarget} repoId={repo.id} name={repoDisplayName} />
) : (
<ProjectWindowsRuntimeSetting
project={project}
@@ -20,6 +20,7 @@ import { WorktreeWslHostStartMenuItem } from '../../workspace-card/host/Worktree
import { WorktreeContextMenuOverlays } from './WorktreeContextMenuOverlays'
import { WorktreeNotificationMuteMenuItem } from './WorktreeNotificationMuteMenuItem'
import { WslMovedWorkspaceUseHereMenuItem } from '@/components/wsl-move/WslMovedUseHereMenuItem'
import { WslMoveFolderWorkspaceMenuItem } from '@/components/wsl-move/WslMoveProjectMenuItem'
import { WorktreeContextMenuDeleteItems } from './WorktreeContextMenuDeleteItems'
import {
WorktreeCopySubMenu,
@@ -44,6 +45,7 @@ export default function WorktreeContextMenuView({ model }: { model: WorktreeCont
deletingSubtree,
developerMenuRevealed,
effectiveSelectedWorktrees,
folderWorkspaceId,
handleAssignWorkspaceStatus,
handleCloseAutoFocus,
handleCloseTerminals,
@@ -210,6 +212,9 @@ export default function WorktreeContextMenuView({ model }: { model: WorktreeCont
<WorktreeCopySubMenu model={model} />
<WorktreeLineageSubMenu model={model} />
<WorktreeProjectGroupSubMenu model={model} />
{folderWorkspaceId ? (
<WslMoveFolderWorkspaceMenuItem folderWorkspaceId={folderWorkspaceId} />
) : null}
<WslMovedWorkspaceUseHereMenuItem worktree={worktree} />
</>
)}
@@ -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<string | null> => 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', () => {
@@ -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<void> {
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
@@ -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<WslDriveUncConversionResult, { outcome: 'restarting' }>,
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(
@@ -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 (
<Dialog open onOpenChange={(open) => !open && closeWslMappedDriveMove()}>
<DialogContent
className="sm:max-w-lg"
showCloseButton={!converting}
data-testid="wsl-mapped-drive-move-dialog"
onEscapeKeyDown={(event) => converting && event.preventDefault()}
onInteractOutside={(event) => converting && event.preventDefault()}
>
<DialogHeader>
<DialogTitle>
{t('wslMove.mappedDrive.title', 'Move {{name}} to the {{distro}} host', {
name,
distro
})}
</DialogTitle>
<DialogDescription>
{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 }
)}
</DialogDescription>
</DialogHeader>
{step.kind === 'problem' ? (
<div role="alert" className="space-y-1 text-sm text-muted-foreground">
{step.messages.map((message) => (
<p key={message}>{message}</p>
))}
</div>
) : null}
<DialogFooter>
<Button
type="button"
variant="ghost"
disabled={converting}
onClick={closeWslMappedDriveMove}
>
{t('wslMove.mappedDrive.cancel', 'Cancel')}
</Button>
<Button
type="button"
disabled={converting}
onClick={() => void confirmWslMappedDriveMove()}
>
{converting ? <LoadingSpinner className="size-4" /> : null}
{step.kind === 'problem'
? t('wslMove.mappedDrive.retry', 'Try again')
: t('wslMove.mappedDrive.confirm', 'Restart and continue')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -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 ? (
<RecoverableRenderErrorBoundary boundaryId="modal.wsl-move" surface="modal" compact>
<WslMoveDialog />
</RecoverableRenderErrorBoundary>
) : 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 ? (
<RecoverableRenderErrorBoundary boundaryId="modal.wsl-move" surface="modal" compact>
<WslMoveDialog />
</RecoverableRenderErrorBoundary>
) : null}
<RecoverableRenderErrorBoundary
boundaryId="modal.wsl-mapped-drive-move"
surface="modal"
compact
>
<WslMappedDriveMoveDialog />
</RecoverableRenderErrorBoundary>
</>
)
}
function WslMoveDialog(): React.JSX.Element | null {
@@ -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 <distro> 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<typeof useWslMoveTargetForRepo>
project: WslMoveRowRef
name: string
}): React.JSX.Element | null {
const t = useTranslate()
const distro = useWslMoveTargetForRepo(repo)
if (!distro) {
if (!target) {
return null
}
return (
<DropdownMenuItem onSelect={() => openWslMoveDialogFor(distro, { kind: 'repo', id: repo.id })}>
<DropdownMenuItem onSelect={() => openWslMoveForProject(target, project, name)}>
<FolderInput className="size-3.5" />
{t('wslMove.entry.projectMenu', 'Move to {{distro}} host…', { distro })}
{t('wslMove.entry.projectMenu', 'Move to {{distro}} host…', { distro: target.distro })}
</DropdownMenuItem>
)
}
/** "Move to <distro> 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 (
<MoveItem target={target} project={{ kind: 'repo', id: repo.id }} name={repo.displayName} />
)
}
/** 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 ? (
<MoveItem target={target} project={{ kind: 'folder', id: folder.id }} name={folder.name} />
) : null
}
@@ -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 (
<SettingsRow
label={t('wslMove.runtime.label', 'Project runtime')}
@@ -26,7 +30,7 @@ export function WslMoveRuntimeRow({
type="button"
variant="outline"
size="sm"
onClick={() => openWslMoveDialogFor(distro, { kind: 'repo', id: repoId })}
onClick={() => openWslMoveForProject(target, { kind: 'repo', id: repoId }, name)}
>
{t('wslMove.runtime.move', 'Move project')}
</Button>
@@ -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' } })
)
})
})
@@ -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<State>()(() => ({
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<void> {
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<void> {
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)
}
@@ -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<Repo, 'path' | 'connectionId' | 'executionHostId'> | 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<typeof findWslHostForDistro>[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<Repo, 'path' | 'connectionId' | 'executionHostId'> | null | undefined
): WslMoveTarget | null {
return useWslMoveTargetForPath(
repo?.path,
!!repo && getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID
)
}
@@ -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<Repo, 'path' | 'connectionId' | 'executionHostId'>,
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
+17 -1
View File
@@ -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": {
+1
View File
@@ -170,6 +170,7 @@ function createWebPreloadApi(): Omit<Partial<PreloadApi>, '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' })
},
@@ -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 }
@@ -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<WslDriveUncPendingRendererRewrite, 'distro' | 'worktreeIds' | 'rootPaths'>
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 }
}
@@ -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()
})
})
@@ -0,0 +1,123 @@
/**
* The path map of an in-place project conversion: a UNC Windows-drive project to its drive path
* (`\\wsl.localhost\<d>\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\<d>\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, '\\$&')
}