mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
refactor(wsl-hosts): move mapped-drive projects directly, without a local respelling
Drops the restart-based conversion that rewrote saved W:\ projects to their \\wsl.localhost path before the move: that local intermediate state changed Git, shells, runtime choice and saved keys before the user approved anything. The mover now takes W:\ projects as they are. Main reads the drive mappings into the distro fresh at preview and again at start (refusing if they changed), records them on the move journal (version 2, so older builds fail closed), and every scope, export, fence, exit-proof, recovery and post-commit rewrite maps W:\ paths through that recorded mapping. Local rows are untouched unless the move commits; cancelling leaves them exactly as they were. Repos whose linked worktrees Git for Windows created are listed as not moving. A drive that doesn't answer only keeps its own projects out, unless the preview had shown it. The D1c conversion files are back to their main content. Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
/**
|
||||
* IPC for converting UNC Windows-drive projects to their drive paths (D1c) or mapped-drive projects
|
||||
* to their distro share, and what the last
|
||||
* IPC for converting UNC Windows-drive projects to their drive paths (D1c), 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.
|
||||
*/
|
||||
@@ -8,8 +7,7 @@ import { randomUUID } from 'node:crypto'
|
||||
import { app, ipcMain, type IpcMainInvokeEvent } from 'electron'
|
||||
import type {
|
||||
WslDriveUncConversionRequest,
|
||||
WslDriveUncConversionResult,
|
||||
WslMappedDriveRestartReport
|
||||
WslDriveUncConversionResult
|
||||
} 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'
|
||||
@@ -23,10 +21,8 @@ import { quitProcess } from '../../startup/quit/process-quit-request'
|
||||
import { startWslDriveUncConversion } from '../../wsl/filesystem/wsl-drive-unc-conversion-run'
|
||||
import {
|
||||
lastWslDriveUncConversionOutcomes,
|
||||
takeWslMappedDriveRestartReport,
|
||||
type WslDriveUncConversionOutcome
|
||||
} from '../../wsl/filesystem/wsl-drive-unc-conversion-startup'
|
||||
import { readWslMappedDriveShareNow } from '../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { wslHostsGateOpen, wslHostsOptedIn } from '../../wsl/host-lifecycle/wsl-host-gate'
|
||||
import { createWslMoveDriverDeps } from './wsl-move-driver-wiring'
|
||||
import { getTrustedUIRendererWebContents } from '../ui'
|
||||
@@ -43,7 +39,6 @@ import { readWslDistroDriveMounts } from '../../wsl/filesystem/wsl-drive-unc-mou
|
||||
export const WSL_DRIVE_UNC_CONVERSION_CHANNELS = [
|
||||
'wslDriveUnc:convert',
|
||||
'wslDriveUnc:lastOutcomes',
|
||||
'wslDriveUnc:takeMappedDriveRestartReport',
|
||||
'wslDriveUnc:listPendingRendererRewrites',
|
||||
'wslDriveUnc:recordStoreRewritten'
|
||||
] as const
|
||||
@@ -70,7 +65,6 @@ export function registerWslDriveUncConversionHandlers(
|
||||
userDataPath,
|
||||
profileId: activeProfileId,
|
||||
readDriveMounts: readWslDistroDriveMounts,
|
||||
readMappedDriveShare: (letter) => readWslMappedDriveShareNow(letter),
|
||||
readProfileState: async () => {
|
||||
await store.flushPendingOrThrowAsync()
|
||||
return readProfileProjectTransferState(activeProfileId, getProfileUserDataPath()).state
|
||||
@@ -102,15 +96,6 @@ export function registerWslDriveUncConversionHandlers(
|
||||
ipcMain.handle('wslDriveUnc:lastOutcomes', (): WslDriveUncConversionOutcome[] =>
|
||||
wslHostsGateOpen() ? lastWslDriveUncConversionOutcomes() : []
|
||||
)
|
||||
ipcMain.handle(
|
||||
'wslDriveUnc:takeMappedDriveRestartReport',
|
||||
(event: IpcMainInvokeEvent): WslMappedDriveRestartReport =>
|
||||
wslHostsGateOpen() && getTrustedUIRendererWebContents()?.id === event.sender.id
|
||||
? takeWslMappedDriveRestartReport(
|
||||
(worktreeId) => void runtime.wakePausedWorkspace(worktreeId)
|
||||
)
|
||||
: { moves: [], rolledBack: [] }
|
||||
)
|
||||
ipcMain.handle(
|
||||
'wslDriveUnc:listPendingRendererRewrites',
|
||||
(): WslDriveUncPendingRendererRewrite[] =>
|
||||
@@ -150,28 +135,15 @@ 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
|
||||
const mappedDriveShare = 'mappedDriveShare' in record ? record.mappedDriveShare : undefined
|
||||
if (
|
||||
typeof distro !== 'string' ||
|
||||
!distro ||
|
||||
!isIdList(repoIds) ||
|
||||
!isIdList(folderWorkspaceIds) ||
|
||||
(mappedDriveLetter !== undefined &&
|
||||
(typeof mappedDriveLetter !== 'string' || !/^[A-Za-z]$/.test(mappedDriveLetter))) ||
|
||||
(mappedDriveShare !== undefined && (typeof mappedDriveShare !== 'string' || !mappedDriveShare))
|
||||
!isIdList(folderWorkspaceIds)
|
||||
) {
|
||||
throw new Error('wsl_drive_unc_invalid_args')
|
||||
}
|
||||
return mappedDriveLetter === undefined
|
||||
? { distro, repoIds, folderWorkspaceIds }
|
||||
: {
|
||||
distro,
|
||||
repoIds,
|
||||
folderWorkspaceIds,
|
||||
mappedDriveLetter,
|
||||
...(mappedDriveShare === undefined ? {} : { mappedDriveShare })
|
||||
}
|
||||
return { distro, repoIds, folderWorkspaceIds }
|
||||
}
|
||||
|
||||
function isIdList(value: unknown): value is string[] {
|
||||
|
||||
@@ -62,6 +62,7 @@ import { inspectPtyProviderProcessForRenderer } from '../../providers/pty/proces
|
||||
import type { OrcaRuntimeService } from '../../runtime/orca-runtime'
|
||||
import { getTrustedUIRendererWebContents, getTrustedUIRendererWindow } from '../ui'
|
||||
import { registerWslMoveHandlers } from './wsl-move-handlers'
|
||||
import { wslMoveMappedDrivePorts } from './wsl-move-mapped-drive-ports'
|
||||
import { registerWslMoveOrchestrator } from './wsl-move-orchestrator-wiring'
|
||||
import { createWslMoveUndoPorts } from './wsl-move-undo-wiring'
|
||||
import { connectWslMoveHostService, type WslMoveHostConnectMode } from './wsl-move-host-connect'
|
||||
@@ -179,6 +180,7 @@ export function createWslMoveDriverDeps(
|
||||
connectHost: (distro) => connectWslMoveHost(userDataPath, distro, hostConnect),
|
||||
isDistroRegistered: (distro, distroGuid) => isWslDistroRegistered(distro, distroGuid),
|
||||
exportManifest: (request) => exportWslMoveManifest(store, request),
|
||||
...wslMoveMappedDrivePorts(),
|
||||
gateInputs: (scope) => collectWslMoveGateInputs(facts, scope),
|
||||
listPanes: (scope) => listWslMovePanes(facts, scope),
|
||||
...(process.platform === 'win32' ? { shellCwds: readWslMovePaneShellCwds } : {}),
|
||||
@@ -200,8 +202,13 @@ export function createWslMoveDriverDeps(
|
||||
},
|
||||
livePtyIds: (workspaceIds) =>
|
||||
runtime.listWslMoveLiveTerminals(workspaceIds).map((terminal) => terminal.ptyId),
|
||||
captureRestoreHints: (panes, distro) =>
|
||||
captureWslMoveRestoreHints(new HistoryReader(getDaemonHistoryDir()), panes, distro),
|
||||
captureRestoreHints: (panes, distro, mappedDrives) =>
|
||||
captureWslMoveRestoreHints(
|
||||
new HistoryReader(getDaemonHistoryDir()),
|
||||
panes,
|
||||
distro,
|
||||
mappedDrives
|
||||
),
|
||||
proveExited: async (scope) => {
|
||||
const fallback = await countInProcessFallbackTerminals()
|
||||
return proveWslMoveTerminalsExited(
|
||||
@@ -218,7 +225,7 @@ export function createWslMoveDriverDeps(
|
||||
}
|
||||
},
|
||||
snapshots: store,
|
||||
sleptScrollback: (panes, distro, migrationId, workspaceIds, reported) =>
|
||||
sleptScrollback: (panes, distro, migrationId, workspaceIds, reported, mappedDrives) =>
|
||||
readWslMoveSleptScrollbackFromHistory(
|
||||
new HistoryReader(getDaemonHistoryDir()),
|
||||
withSleptSessionPanes(
|
||||
@@ -227,7 +234,9 @@ export function createWslMoveDriverDeps(
|
||||
),
|
||||
distro,
|
||||
wslMoveSleptSpoolRoot(userDataPath, migrationId),
|
||||
(tabId) => wslMoveTabTitle(store.getWorkspaceSession(), tabId)
|
||||
(tabId) => wslMoveTabTitle(store.getWorkspaceSession(), tabId),
|
||||
() => new Date(),
|
||||
mappedDrives
|
||||
),
|
||||
shellHistory: (distro, worktrees) => buildWslMoveShellHistoryBlobs({ distro, worktrees }),
|
||||
// The pass reloads the window it held at commit (wsl-move-window-write-hold.ts).
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/** The move's view of drive letters mapped into a distro: Windows only, read fresh each time. */
|
||||
import type { Store } from '../../persistence/loading-store/store'
|
||||
import type { WslMoveDriverDeps } from '../../persistence/moving-wsl-projects/execution/wsl-move-driver-ports'
|
||||
import { readWslMoveMappedDrives } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-mapped-drives'
|
||||
import { windowsGitWorktreePaths } from '../../persistence/moving-wsl-projects/manifest-scope/wsl-move-windows-git-worktrees'
|
||||
import type { WslMappedDrive } from '../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { readWslMappedDriveShareNow } from '../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
|
||||
export function wslMoveMappedDrivePorts(): Pick<
|
||||
WslMoveDriverDeps,
|
||||
'readMappedDriveShare' | 'windowsGitWorktrees'
|
||||
> {
|
||||
return process.platform === 'win32'
|
||||
? {
|
||||
readMappedDriveShare: (letter) => readWslMappedDriveShareNow(letter),
|
||||
windowsGitWorktrees: windowsGitWorktreePaths
|
||||
}
|
||||
: {}
|
||||
}
|
||||
|
||||
/** For the orchestrator's prune check; absent off Windows, where no drive is mapped. */
|
||||
export function readWslMoveDistroMappedDrives(
|
||||
store: Pick<Store, 'getRepos' | 'getFolderWorkspaces'>,
|
||||
distro: string
|
||||
): (() => Promise<readonly WslMappedDrive[] | 'unverifiable'>) | undefined {
|
||||
if (process.platform !== 'win32') {
|
||||
return undefined
|
||||
}
|
||||
return async () => {
|
||||
const read = await readWslMoveMappedDrives(
|
||||
{ repos: store.getRepos(), folderWorkspaces: store.getFolderWorkspaces() },
|
||||
distro,
|
||||
(letter) => readWslMappedDriveShareNow(letter)
|
||||
)
|
||||
// Pruning is the cautious side: an unanswered drive may still hold this distro's projects.
|
||||
return read.unverifiableLetters.length === 0 ? read.mappedDrives : 'unverifiable'
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import type { Store } from '../../persistence/loading-store/store'
|
||||
import { listWslMoveCutoverChain } from '../../persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal'
|
||||
import { moveProjectsToWslHost } from '../../persistence/moving-wsl-projects/wsl-move-driver'
|
||||
import { previewWslMove } from '../../persistence/moving-wsl-projects/execution/wsl-move-driver-preview'
|
||||
import { readWslMoveDistroMappedDrives } from './wsl-move-mapped-drive-ports'
|
||||
import { wslMovedDistroVerdict } from '../../persistence/moving-wsl-projects/quiescence/wsl-move-moved-distro-check'
|
||||
import { WslMoveOrchestrator } from '../../persistence/moving-wsl-projects/wsl-move-orchestrator'
|
||||
import type {
|
||||
@@ -137,7 +138,13 @@ function createOrchestrator(
|
||||
process.env[WSL_MOVE_ORCHESTRATOR_AUTO_ENV] !== '0' && wslHostsOptedIn(store.getSettings()),
|
||||
autoMovesBridgeProjects: wslMoveAutoMovesBridgeProjects,
|
||||
prepareHost: (distro, stillWanted) => prepareHost(userDataPath, distro, stillWanted),
|
||||
isDistroInUse: async (distro) => await isDistroInUse(store, userDataPath, distro),
|
||||
isDistroInUse: async (distro) =>
|
||||
await isDistroInUse(
|
||||
store,
|
||||
userDataPath,
|
||||
distro,
|
||||
readWslMoveDistroMappedDrives(store, distro)
|
||||
),
|
||||
hostRemovalPending: async (distro) => await wslHostRemovalPending(userDataPath, distro),
|
||||
hasHost: async (distro) =>
|
||||
(await getWslHostService()?.recordForEnvironment(defaultWslOrcadEnvironmentId(distro))) !=
|
||||
@@ -149,14 +156,14 @@ function createOrchestrator(
|
||||
{ distro, sleptPanes: await requestSleptPanes() },
|
||||
{ settleInterrupted: userAsked ? 'finish-now' : 'finish-at-restart' }
|
||||
),
|
||||
start: async (distro, stillWanted) => {
|
||||
start: async (distro, stillWanted, mappedDrives) => {
|
||||
const sleptPanes = await requestSleptPanes()
|
||||
// The user may have released or snoozed the distro while the window answered.
|
||||
if (!stillWanted()) {
|
||||
return { outcome: 'refused', code: 'wsl_move_cancelled' }
|
||||
}
|
||||
return runTrackedWslMove(driverDeps(), (deps) =>
|
||||
moveProjectsToWslHost(deps, { distro, sleptPanes })
|
||||
moveProjectsToWslHost(deps, { distro, sleptPanes, mappedDrives: [...mappedDrives] })
|
||||
)
|
||||
},
|
||||
finishedMove: (distro) => finishedWslMove(userDataPath, distro),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../shared/orcad-migration/orcad-migration-manifest-validation'
|
||||
import type { OrcadMigrationDormantStatePayload } from '../../../../shared/orcad-migration/orcad-migration-manifest'
|
||||
import {
|
||||
wslMoveCutoverVersionFor,
|
||||
wslMoveJournalKey,
|
||||
type WslMoveCutover,
|
||||
type WslMoveCutoverPhase
|
||||
@@ -58,7 +59,7 @@ export function wslMoveCutoverFixture(
|
||||
}
|
||||
const manifest = { ...unsigned, manifestSha256: computeOrcadMigrationManifestSha256(unsigned) }
|
||||
return {
|
||||
version: 1,
|
||||
version: wslMoveCutoverVersionFor(extra.mappedDrives),
|
||||
migrationId,
|
||||
phase,
|
||||
startedAt: '2026-10-13T00:00:00.000Z',
|
||||
|
||||
@@ -106,9 +106,9 @@ export function createWslMoveKillRig(): WslMoveRig {
|
||||
world.deps.quiesce = {
|
||||
sleepWorkspaces: async (ids) => (at('sleep'), quiesce.sleepWorkspaces(ids)),
|
||||
livePtyIds: quiesce.livePtyIds,
|
||||
captureRestoreHints: async (panes, distro) => (
|
||||
captureRestoreHints: async (panes, distro, mappedDrives) => (
|
||||
at('restore-hints'),
|
||||
quiesce.captureRestoreHints(panes, distro)
|
||||
quiesce.captureRestoreHints(panes, distro, mappedDrives)
|
||||
),
|
||||
proveExited: async (scope) => (at('prove-exited'), quiesce.proveExited(scope))
|
||||
}
|
||||
|
||||
+3
-1
@@ -136,7 +136,9 @@ function assertWslMoveUpdate(
|
||||
): void {
|
||||
if (
|
||||
next.manifestSha256 !== existing.manifestSha256 ||
|
||||
next.supersedesMigrationId !== existing.supersedesMigrationId
|
||||
next.supersedesMigrationId !== existing.supersedesMigrationId ||
|
||||
// Recovery maps the moved paths with these, so they never change after `prepared`.
|
||||
JSON.stringify(next.mappedDrives) !== JSON.stringify(existing.mappedDrives)
|
||||
) {
|
||||
throw new Error('wsl_move_binding_changed')
|
||||
}
|
||||
|
||||
+9
-4
@@ -11,6 +11,7 @@ import {
|
||||
WSL_MOVE_CUTOVER_PHASES,
|
||||
type WslMoveCutover
|
||||
} from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { createUncToLinuxPathRewriter } from '../manifest-scope/wsl-move-path-rewriter'
|
||||
import type { WslMoveRetainedMark } from './wsl-move-retained-marks'
|
||||
import { isLocalWslMoveRow } from '../quiescence/wsl-move-scope-guard'
|
||||
@@ -32,9 +33,13 @@ function identity(row: IdentityRow, toLinux: (path: string) => string): string {
|
||||
: JSON.stringify([row.id, toLinux(row.path), row.displayName])
|
||||
}
|
||||
|
||||
/** The local row as the move would export it today. */
|
||||
export function wslMoveLocalRowIdentity(row: IdentityRow, distro: string): string {
|
||||
const rewriter = createUncToLinuxPathRewriter(distro)
|
||||
/** The local row as the move would export it today, with the mapped drives the move read. */
|
||||
export function wslMoveLocalRowIdentity(
|
||||
row: IdentityRow,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): string {
|
||||
const rewriter = createUncToLinuxPathRewriter(distro, mappedDrives)
|
||||
return identity(row, (path) => rewriter.path(path, 'absolute'))
|
||||
}
|
||||
|
||||
@@ -114,7 +119,7 @@ export function planWslMoveRetainedMarks(input: {
|
||||
}
|
||||
const changed =
|
||||
wslMoveTakenRowIdentity(owner, ref) !==
|
||||
wslMoveLocalRowIdentity(row, owner.manifest.source.distro)
|
||||
wslMoveLocalRowIdentity(row, owner.manifest.source.distro, owner.mappedDrives)
|
||||
if (changed) {
|
||||
plan.changed.push(ref)
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ export function wslMoveDesktopRewriteContext(
|
||||
): WslMoveDesktopRewriteContext {
|
||||
return {
|
||||
cutover,
|
||||
rewritePath: createUncToLinuxPathRewriter(cutover.manifest.source.distro),
|
||||
rewritePath: createUncToLinuxPathRewriter(cutover.manifest.source.distro, cutover.mappedDrives),
|
||||
destinationHostId: toRuntimeExecutionHostId(cutover.destinationEnvironmentId),
|
||||
recordSeededHostWorkspaceIds: (workspaceIds) =>
|
||||
recordSeededHostWorkspaces(userDataPath, cutover.migrationId, workspaceIds)
|
||||
@@ -229,7 +229,8 @@ export function listPendingWslMoveRendererRewrites(
|
||||
distro: source.distro,
|
||||
scopeRepoIds: [...source.scopeRepoIds],
|
||||
scopeFolderWorkspaceIds: [...source.scopeFolderWorkspaceIds],
|
||||
scopeRootPaths: wslMoveScopeRootPaths(cutover.manifest)
|
||||
scopeRootPaths: wslMoveScopeRootPaths(cutover.manifest),
|
||||
...(cutover.mappedDrives?.length ? { mappedDrives: cutover.mappedDrives } : {})
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* A project saved under a drive letter mapped to the distro's share moves as it is saved: the
|
||||
* preview reads the mapping, the start re-reads it and refuses a change, and the journal keeps it.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../../shared/remote-runtime/wsl-hosts/wsl-host-internal-gate'
|
||||
import type { WslMappedDriveRead } from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { testState } from '../../persistence-test-harness'
|
||||
import {
|
||||
createWslMoveKillRig,
|
||||
removeWslMoveRigDirs,
|
||||
wslMoveRigRetentionStore,
|
||||
type WslMoveRig
|
||||
} from '../../__fixtures__/wsl-mover/wsl-move-kill-rig'
|
||||
import { listWslMoveCutovers } from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
import { planWslMoveRetainedMarks } from '../cutover-recovery/wsl-move-retained-source'
|
||||
import { runWslMoveRetentionPass } from '../cutover-recovery/wsl-move-retention'
|
||||
import { resetWslMoveDesktopRewriteStoresForTests } from '../desktop-state/wsl-move-desktop-rewrite-stores'
|
||||
import { moveProjectsToWslHost } from '../wsl-move-driver'
|
||||
import { previewWslMove } from './wsl-move-driver-preview'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => testState.dir },
|
||||
safeStorage: {
|
||||
isEncryptionAvailable: () => true,
|
||||
encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'),
|
||||
decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length)
|
||||
}
|
||||
}))
|
||||
vi.mock('../../../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../../../telemetry/cohort-classifier', () => ({
|
||||
getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 1 }))
|
||||
}))
|
||||
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
|
||||
let rig: WslMoveRig
|
||||
let shares: Record<string, WslMappedDriveRead>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1')
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
rig = createWslMoveKillRig()
|
||||
rig.world.repos = [{ ...rig.world.repos[0], path: 'W:\\home\\dev\\app' }]
|
||||
shares = { W: { share: W.share } }
|
||||
rig.world.deps.readMappedDriveShare = async (letter) => shares[letter] ?? { share: null }
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
resetWslMoveDesktopRewriteStoresForTests()
|
||||
removeWslMoveRigDirs()
|
||||
})
|
||||
|
||||
describe('moving a project saved under a mapped drive', () => {
|
||||
it('previews it with the mapping and moves it as journaled, keeping the local row', async () => {
|
||||
const preview = await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
expect(preview).toMatchObject({ outcome: 'ready', repoIds: ['repo-1'], mappedDrives: [W] })
|
||||
const result = await moveProjectsToWslHost(rig.world.deps, {
|
||||
distro: 'Ubuntu',
|
||||
mappedDrives: [W]
|
||||
})
|
||||
expect(result).toMatchObject({ outcome: 'moved' })
|
||||
const [record] = listWslMoveCutovers(rig.userDataPath)
|
||||
expect(record).toMatchObject({ version: 2, mappedDrives: [W] })
|
||||
expect(record.manifest.payload.repositories[0].path).toBe('/home/dev/app')
|
||||
// The local row stays exactly as saved; its identity still matches what the move took.
|
||||
await runWslMoveRetentionPass({
|
||||
userDataPath: rig.userDataPath,
|
||||
store: wslMoveRigRetentionStore(rig)
|
||||
})
|
||||
expect(rig.world.repos[0].path).toBe('W:\\home\\dev\\app')
|
||||
const marks = planWslMoveRetainedMarks({
|
||||
chains: [listWslMoveCutovers(rig.userDataPath)],
|
||||
retaining: new Set(),
|
||||
repos: rig.world.repos,
|
||||
folderWorkspaces: [],
|
||||
now: '2026-10-21T00:00:00.000Z'
|
||||
})
|
||||
expect(marks.changed).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a start whose drive maps elsewhere since the preview, before journaling', async () => {
|
||||
await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
shares = { W: { share: '\\\\wsl.localhost\\Ubuntu\\home' } }
|
||||
expect(
|
||||
await moveProjectsToWslHost(rig.world.deps, { distro: 'Ubuntu', mappedDrives: [W] })
|
||||
).toMatchObject({ outcome: 'refused', code: 'wsl_move_scope_changed' })
|
||||
// A start that never saw the mapping refuses as well.
|
||||
shares = { W: { share: W.share } }
|
||||
expect(await moveProjectsToWslHost(rig.world.deps, { distro: 'Ubuntu' })).toMatchObject({
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_scope_changed'
|
||||
})
|
||||
expect(listWslMoveCutovers(rig.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves out only the projects of a drive that does not answer', async () => {
|
||||
// An offline share elsewhere must not block moving the distro's other projects.
|
||||
rig.world.repos = [
|
||||
rig.world.repos[0],
|
||||
{ ...rig.world.repos[0], id: 'repo-s', path: 'S:\\shared\\tool' }
|
||||
]
|
||||
shares = { W: { share: W.share }, S: 'unverifiable' }
|
||||
expect(await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })).toMatchObject({
|
||||
outcome: 'ready',
|
||||
repoIds: ['repo-1'],
|
||||
mappedDrives: [W]
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a start that can no longer read a drive the preview showed', async () => {
|
||||
await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
shares = { W: 'unverifiable' }
|
||||
expect(
|
||||
await moveProjectsToWslHost(rig.world.deps, { distro: 'Ubuntu', mappedDrives: [W] })
|
||||
).toMatchObject({
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_unavailable',
|
||||
detail: 'mapped-drive-unverifiable'
|
||||
})
|
||||
expect(listWslMoveCutovers(rig.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('lists a repo with Windows-authored worktrees as not moving', async () => {
|
||||
rig.world.deps.windowsGitWorktrees = async () => ['W:/home/dev/app-trees/x']
|
||||
expect(await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })).toMatchObject({
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_nothing_new'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
wslMoveJournalKey
|
||||
} from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import { wslHostsAcceptNewWork } from '../../../wsl/host-lifecycle/wsl-host-gate'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { readWslMoveSourceDrives } from './wsl-move-driver-source-drives'
|
||||
import { listWslMoveCutoverChain } from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
|
||||
import { type WslMovePlan, planWslMove } from '../manifest-scope/wsl-move-delta-plan'
|
||||
@@ -185,7 +187,8 @@ export function exportRequestOf(
|
||||
destinationEnvironmentId: host.environmentId,
|
||||
generation: plan.generation,
|
||||
repoIds: plan.repoIds,
|
||||
folderWorkspaceIds: plan.folderWorkspaceIds
|
||||
folderWorkspaceIds: plan.folderWorkspaceIds,
|
||||
...(plan.mappedDrives?.length ? { mappedDrives: plan.mappedDrives } : {})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +198,9 @@ export async function prepareWslMove(
|
||||
migrationId: string,
|
||||
startedAt: Date,
|
||||
/** Settle an earlier move of the distro an interruption left short of commit; false leaves it. */
|
||||
settleInterrupted: WslMoveInterruptedSettle | false = false
|
||||
settleInterrupted: WslMoveInterruptedSettle | false = false,
|
||||
/** At start: the mapped drives the preview showed, which must still hold. Null for a preview. */
|
||||
expectedMappedDrives: readonly WslMappedDrive[] | null = null
|
||||
): Promise<WslMovePrepared | WslMoveRefusal> {
|
||||
// Every new move, dialog or automatic, stops once a block is learned, even mid-run.
|
||||
if (!wslHostsAcceptNewWork()) {
|
||||
@@ -232,12 +237,19 @@ export async function prepareWslMove(
|
||||
request.repoIds || request.folderWorkspaceIds
|
||||
? { repoIds: request.repoIds ?? [], folderWorkspaceIds: request.folderWorkspaceIds ?? [] }
|
||||
: undefined
|
||||
const catalog = deps.readCatalog()
|
||||
const drives = await readWslMoveSourceDrives(deps, catalog, request.distro, expectedMappedDrives)
|
||||
if ('outcome' in drives) {
|
||||
return drives
|
||||
}
|
||||
const planned = planWslMove(
|
||||
deps.userDataPath,
|
||||
deps.readCatalog(),
|
||||
catalog,
|
||||
request.distro,
|
||||
await host.readHolding(),
|
||||
selection
|
||||
selection,
|
||||
drives.mappedDrives,
|
||||
drives.windowsGitWorktreeRepoIds
|
||||
)
|
||||
if (planned.outcome === 'refused') {
|
||||
return refusal(planned.code)
|
||||
|
||||
@@ -27,6 +27,8 @@ import type {
|
||||
WslMoveManifestExportRequest
|
||||
} from '../manifest-scope/wsl-move-manifest-export'
|
||||
import type { WslMoveGateInputs } from '../quiescence/wsl-move-terminal-gate'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { WslMappedDriveRead } from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
|
||||
/** Throws `WslMoveScopeChangedError` when a planned row is gone: plan again. */
|
||||
export type WslMoveManifestExporter = (
|
||||
@@ -74,6 +76,10 @@ export type WslMoveDriverDeps = {
|
||||
*/
|
||||
isDistroRegistered: (distro: string, distroGuid?: string) => Promise<boolean | null>
|
||||
exportManifest: WslMoveManifestExporter
|
||||
/** What a drive letter maps to right now, uncached; absent off Windows (no drive is mapped). */
|
||||
readMappedDriveShare?: (letter: string) => Promise<WslMappedDriveRead>
|
||||
/** Linked worktrees of a mapped-drive repo whose links Git for Windows wrote. */
|
||||
windowsGitWorktrees?: (repoPath: string, distro: string) => Promise<string[]>
|
||||
/** Busy, working, automation and dispatch facts for the scope, from their owning stores. */
|
||||
gateInputs: (scope: WslMoveTerminalScope) => Promise<WslMoveGateInputs>
|
||||
/** The panes the scope's live terminals belong to; read before Sleep ends their sessions. */
|
||||
@@ -104,7 +110,9 @@ export type WslMoveDriverDeps = {
|
||||
/** The scope's workspaces, for panes slept before the move (no live terminal to list). */
|
||||
workspaceIds: readonly string[],
|
||||
/** The window's bindings of slept panes, which main no longer holds; checked before use. */
|
||||
reported: readonly WslMoveRestoreHintPane[]
|
||||
reported: readonly WslMoveRestoreHintPane[],
|
||||
/** The plan's mapped drives, for a checkpoint folder spelled `W:\x`. */
|
||||
mappedDrives: readonly WslMappedDrive[]
|
||||
) => Promise<WslMoveSleptScrollback>
|
||||
shellHistory: (
|
||||
distro: string,
|
||||
|
||||
@@ -62,6 +62,7 @@ async function previewPrepared(
|
||||
heldByHost: plan.heldByHost,
|
||||
refused: plan.refused,
|
||||
blockers: prepared.blockers,
|
||||
mappedDrives: plan.mappedDrives ?? [],
|
||||
...(host.browserLoginsNotCarried
|
||||
? { browserLoginsNotCarried: host.browserLoginsNotCarried }
|
||||
: {})
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* The mapped drives a move plans with: read fresh at preview, and at start again, refusing when
|
||||
* they differ from what the preview showed (the start request carries them back). With them, the
|
||||
* mapped-drive repos whose worktrees Git for Windows created, which the plan refuses.
|
||||
*/
|
||||
import {
|
||||
WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL,
|
||||
type WslMoveRefusal
|
||||
} from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import {
|
||||
sameWslMappedDrives,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { readWslMoveMappedDrives } from '../manifest-scope/wsl-move-mapped-drives'
|
||||
import { findWindowsGitWorktreeRepoIds } from '../manifest-scope/wsl-move-windows-git-worktrees'
|
||||
import type { WslMoveCatalogRows, WslMoveDriverDeps } from './wsl-move-driver-ports'
|
||||
|
||||
export type WslMoveSourceDrives = {
|
||||
mappedDrives: WslMappedDrive[]
|
||||
windowsGitWorktreeRepoIds: ReadonlySet<string>
|
||||
}
|
||||
|
||||
export async function readWslMoveSourceDrives(
|
||||
deps: Pick<WslMoveDriverDeps, 'readMappedDriveShare' | 'windowsGitWorktrees'>,
|
||||
catalog: WslMoveCatalogRows,
|
||||
distro: string,
|
||||
/** At start: the drives the preview showed. Null for a preview. */
|
||||
expected: readonly WslMappedDrive[] | null
|
||||
): Promise<WslMoveSourceDrives | WslMoveRefusal> {
|
||||
const read = deps.readMappedDriveShare
|
||||
? await readWslMoveMappedDrives(catalog, distro, deps.readMappedDriveShare)
|
||||
: { mappedDrives: [], unverifiableLetters: [] }
|
||||
// A drive that doesn't answer (an offline network share, say) only keeps its own projects out;
|
||||
// a start loses a drive the preview showed, so it refuses rather than move without it.
|
||||
const lostLetters = (expected ?? []).filter((drive) =>
|
||||
read.unverifiableLetters.includes(drive.letter.toUpperCase())
|
||||
)
|
||||
if (lostLetters.length > 0) {
|
||||
return {
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_unavailable',
|
||||
detail: WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL
|
||||
}
|
||||
}
|
||||
const { mappedDrives } = read
|
||||
if (expected && !sameWslMappedDrives(expected, mappedDrives)) {
|
||||
return { outcome: 'refused', code: 'wsl_move_scope_changed', detail: 'mapped-drives-changed' }
|
||||
}
|
||||
const windowsGitWorktreeRepoIds =
|
||||
deps.windowsGitWorktrees && mappedDrives.length > 0
|
||||
? await findWindowsGitWorktreeRepoIds(
|
||||
catalog.repos,
|
||||
distro,
|
||||
mappedDrives,
|
||||
deps.windowsGitWorktrees
|
||||
)
|
||||
: new Set<string>()
|
||||
return { mappedDrives, windowsGitWorktreeRepoIds }
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
// Normalize host/path identities for comparison; preserve user text and terminal output byte for byte.
|
||||
import type { WslMoveProjectionScope } from './wsl-move-state-projection'
|
||||
import {
|
||||
toWslDistroUncPath,
|
||||
wslMappedDriveFileUrlToLinux
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
|
||||
export const WSL_MOVE_FREE_TEXT_KEYS: ReadonlySet<string> = new Set([
|
||||
'dirtyDraftContent',
|
||||
@@ -41,9 +45,12 @@ export function parseEditorFileId(value: string): [string, string, string] | nul
|
||||
}
|
||||
|
||||
export function createWslMoveStringNormalizer(
|
||||
scope: Pick<WslMoveProjectionScope, 'distro' | 'hostAliases'>
|
||||
scope: Pick<WslMoveProjectionScope, 'distro' | 'hostAliases' | 'mappedDrives'>
|
||||
): (value: string) => string {
|
||||
const distro = escapeRegExp(scope.distro)
|
||||
const mappedDrives = scope.mappedDrives ?? []
|
||||
// A mapped-drive identity, in the same shape: `W:\x`, `repoId::W:\x`, `worktree:repoId::W:\x`.
|
||||
const driveIdentity = /^((?:worktree:)?(?:[^\s\\/]*::)?)([A-Za-z]:(?:[\\/][^\\/:]*)+)(::.*)?$/
|
||||
// Match distro UNC identities; colons delimit worktree suffixes rather than path segments.
|
||||
const uncIdentity = new RegExp(
|
||||
`^((?:worktree:)?(?:[^\\s\\\\/]*::)?)(?:\\\\\\\\|//)(?:wsl\\.localhost|wsl\\$)[\\\\/]${distro}((?:[\\\\/][^\\\\/:]*)*)(::.*)?$`,
|
||||
@@ -67,6 +74,15 @@ export function createWslMoveStringNormalizer(
|
||||
if (fileUrl.test(value)) {
|
||||
return value.replace(fileUrl, 'file:///')
|
||||
}
|
||||
const driveUrl = wslMappedDriveFileUrlToLinux(value, scope.distro, mappedDrives)
|
||||
if (driveUrl !== null) {
|
||||
return driveUrl
|
||||
}
|
||||
const drive = mappedDrives.length > 0 ? driveIdentity.exec(value) : null
|
||||
const share = drive ? toWslDistroUncPath(drive[2], mappedDrives) : null
|
||||
if (drive && share !== drive[2]) {
|
||||
return normalize(`${drive[1]}${share}${drive[3] ?? ''}`)
|
||||
}
|
||||
const unc = uncIdentity.exec(value)
|
||||
if (!unc) {
|
||||
return value
|
||||
|
||||
+13
-3
@@ -6,10 +6,20 @@ import {
|
||||
foldWslUncPathCaseInsensitiveParts,
|
||||
toWindowsWslUncPath
|
||||
} from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
toWslDistroUncPath,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
|
||||
/** Null for a path that is not in a WSL distro (a Windows drive path, say). */
|
||||
export function comparableWslPath(path: string, distro: string): string | null {
|
||||
const unc = isLinuxSpelled(path) ? toWindowsWslUncPath(path, distro) : path
|
||||
/** Null for a path that is not in a WSL distro (a Windows drive path no mapped drive covers). */
|
||||
export function comparableWslPath(
|
||||
path: string,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): string | null {
|
||||
const unc = isLinuxSpelled(path)
|
||||
? toWindowsWslUncPath(path, distro)
|
||||
: toWslDistroUncPath(path, mappedDrives)
|
||||
return foldWslUncPathCaseInsensitiveParts(unc)?.replace(/\/+$/, '') ?? null
|
||||
}
|
||||
|
||||
|
||||
+6
-2
@@ -6,9 +6,13 @@ import type { WslMoveProjectionScope } from './wsl-move-state-projection'
|
||||
export function findMissingWslMoveAliases(
|
||||
sourceWorktreeIds: readonly string[],
|
||||
destinationMeta: Readonly<Record<string, WorktreeMeta>>,
|
||||
scope: Pick<WslMoveProjectionScope, 'distro'>
|
||||
scope: Pick<WslMoveProjectionScope, 'distro' | 'mappedDrives'>
|
||||
): string[] {
|
||||
const normalize = createWslMoveStringNormalizer({ distro: scope.distro, hostAliases: [] })
|
||||
const normalize = createWslMoveStringNormalizer({
|
||||
distro: scope.distro,
|
||||
hostAliases: [],
|
||||
mappedDrives: scope.mappedDrives
|
||||
})
|
||||
return sourceWorktreeIds.filter((sourceId) => {
|
||||
const destinationId = normalize(sourceId)
|
||||
return (
|
||||
|
||||
@@ -16,11 +16,12 @@ import type { ProjectGroup } from '../../../../shared/project/groups/project-gro
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import {
|
||||
WSL_MOVE_CUTOVER_PHASES,
|
||||
WSL_MOVE_CUTOVER_VERSION,
|
||||
isWslMoveCutoverFinished,
|
||||
wslMoveCutoverVersionFor,
|
||||
wslMoveJournalKey,
|
||||
type WslMoveCutover
|
||||
} from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import {
|
||||
listWslMoveCutoverChain,
|
||||
scanWslMoveCutovers,
|
||||
@@ -73,6 +74,8 @@ export type WslMovePlan = {
|
||||
/** On the host with no move to show for it, e.g. after "Use on this computer again". */
|
||||
heldByHost: WslMoveRowRef[]
|
||||
refused: WslMoveScope['refused']
|
||||
/** The drives mapped into the distro this plan read; journaled with the move. */
|
||||
mappedDrives?: WslMappedDrive[]
|
||||
}
|
||||
|
||||
export type WslMovePlanResult =
|
||||
@@ -96,7 +99,9 @@ export function planWslMove(
|
||||
distro: string,
|
||||
host: WslMoveHostHolding,
|
||||
/** The projects the user ticked; absent means the whole distro. */
|
||||
selection?: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] }
|
||||
selection?: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] },
|
||||
mappedDrives: readonly WslMappedDrive[] = [],
|
||||
windowsGitWorktreeRepoIds: ReadonlySet<string> = new Set()
|
||||
): WslMovePlanResult {
|
||||
const journalKey = wslMoveJournalKey(distro)
|
||||
const chain = listWslMoveCutoverChain(userDataPath, journalKey)
|
||||
@@ -122,7 +127,7 @@ export function planWslMove(
|
||||
.flatMap((cutover) => wslMoveScopeRefs(cutover).map(wslMoveRowKey))
|
||||
)
|
||||
const held = new Set(refsOf(host).map(wslMoveRowKey))
|
||||
const scope = collectWslMoveScope(state, distro)
|
||||
const scope = collectWslMoveScope(state, distro, mappedDrives, windowsGitWorktreeRepoIds)
|
||||
const selected = (ref: WslMoveRowRef): boolean =>
|
||||
!selection ||
|
||||
(ref.kind === 'repo' ? selection.repoIds : selection.folderWorkspaceIds).includes(ref.id)
|
||||
@@ -140,6 +145,21 @@ export function planWslMove(
|
||||
}
|
||||
const candidates = refsOf(scope)
|
||||
const inScope = new Set(candidates.map(wslMoveRowKey))
|
||||
// A taken row is judged under the mapping its move read, not today's.
|
||||
const ownerScopes = new Map<string, ReadonlySet<string>>()
|
||||
const inOwnerScope = (owner: Readonly<WslMoveCutover>, key: string): boolean => {
|
||||
if (!owner.mappedDrives?.length) {
|
||||
return inScope.has(key)
|
||||
}
|
||||
let keys = ownerScopes.get(owner.migrationId)
|
||||
if (!keys) {
|
||||
keys = new Set(
|
||||
refsOf(collectWslMoveScope(state, distro, owner.mappedDrives)).map(wslMoveRowKey)
|
||||
)
|
||||
ownerScopes.set(owner.migrationId, keys)
|
||||
}
|
||||
return keys.has(key)
|
||||
}
|
||||
const fresh: WslMoveRowRef[] = []
|
||||
const changed: WslMoveRowRef[] = []
|
||||
const heldByHost: WslMoveRowRef[] = []
|
||||
@@ -163,8 +183,9 @@ export function planWslMove(
|
||||
removed.push(ref)
|
||||
} else if (
|
||||
// Out of scope now (a path left the distro), or another identity.
|
||||
!inScope.has(key) ||
|
||||
wslMoveTakenRowIdentity(owner, ref) !== wslMoveLocalRowIdentity(row, distro)
|
||||
!inOwnerScope(owner, key) ||
|
||||
wslMoveTakenRowIdentity(owner, ref) !==
|
||||
wslMoveLocalRowIdentity(row, distro, owner.mappedDrives)
|
||||
) {
|
||||
changed.push(ref)
|
||||
}
|
||||
@@ -190,7 +211,8 @@ export function planWslMove(
|
||||
changed,
|
||||
removed,
|
||||
heldByHost,
|
||||
refused: scope.refused
|
||||
refused: scope.refused,
|
||||
mappedDrives: mappedDrives.map((drive) => ({ ...drive }))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,7 +253,7 @@ export function journalWslMove(args: {
|
||||
}
|
||||
const timestamp = (args.now ?? (() => new Date()))().toISOString()
|
||||
const cutover: WslMoveCutover = {
|
||||
version: WSL_MOVE_CUTOVER_VERSION,
|
||||
version: wslMoveCutoverVersionFor(plan.mappedDrives),
|
||||
migrationId: manifest.migrationId,
|
||||
phase: 'prepared',
|
||||
startedAt: timestamp,
|
||||
@@ -242,6 +264,7 @@ export function journalWslMove(args: {
|
||||
manifestSha256: manifest.manifestSha256,
|
||||
provenExitedSessionIds: [],
|
||||
rewrittenStores: [],
|
||||
...(plan.mappedDrives?.length ? { mappedDrives: plan.mappedDrives } : {}),
|
||||
...(plan.supersedesMigrationId ? { supersedesMigrationId: plan.supersedesMigrationId } : {}),
|
||||
...(args.automationsToReenable?.length
|
||||
? { automationsToReenable: [...args.automationsToReenable] }
|
||||
|
||||
@@ -34,7 +34,10 @@ import {
|
||||
} from '../../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite'
|
||||
import type { Store } from '../../loading-store/store'
|
||||
import { compareKeys } from '../../migrating-orcad-catalog/source/catalog/orcad-source-key-order'
|
||||
import { wslUncPathToLinux } from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
wslMoveSourcePathToLinux,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { createUncToLinuxPathRewriter } from './wsl-move-path-rewriter'
|
||||
import { withoutWindowsShellChoices } from '../desktop-state/wsl-move-windows-shell-choices'
|
||||
import { withoutDesktopFocus, withoutPtyBindings } from '../terminal-state/wsl-move-session-rewrite'
|
||||
@@ -54,6 +57,8 @@ export type WslMoveManifestExportRequest = {
|
||||
folderWorkspaceIds: readonly string[]
|
||||
/** Slept panes' daemon history: their only copy of the scrollback. */
|
||||
daemonHistoryLeaf?: (tabId: string, leafId: string) => boolean
|
||||
/** The plan's drives mapped into the distro; their paths export as the share's. */
|
||||
mappedDrives?: readonly WslMappedDrive[]
|
||||
}
|
||||
|
||||
export type WslMoveManifestExport = {
|
||||
@@ -165,7 +170,7 @@ export function exportWslMoveManifest(
|
||||
const dormantState = workspaceSession
|
||||
? { ...inspection.payload, workspaceSession }
|
||||
: inspection.payload
|
||||
const rewriter = createUncToLinuxPathRewriter(request.distro)
|
||||
const rewriter = createUncToLinuxPathRewriter(request.distro, request.mappedDrives)
|
||||
const payload = rewriteOrcadMigrationPayloadPaths(
|
||||
{ ...catalog, ...(hasDormantState(dormantState) ? { dormantState } : {}) },
|
||||
rewriter
|
||||
@@ -216,7 +221,7 @@ export function exportWslMoveManifest(
|
||||
function isLocalRepo(repo: Repo): boolean {
|
||||
return (
|
||||
getRepoExecutionHostId(repo) === LOCAL_EXECUTION_HOST_ID &&
|
||||
wslUncPathToLinux(repo.path, request.distro) !== null
|
||||
wslMoveSourcePathToLinux(repo.path, request.distro, request.mappedDrives) !== null
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
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 { wslMoveCutoverFixture } from '../../__fixtures__/wsl-mover/wsl-move-cutover-fixture'
|
||||
import {
|
||||
wslMoveLocalRowIdentity,
|
||||
wslMoveTakenRowIdentity
|
||||
} from '../cutover-recovery/wsl-move-retained-source'
|
||||
import { createWslMoveStringNormalizer } from './wsl-move-canonical-form'
|
||||
import { createUncToLinuxPathRewriter } from './wsl-move-path-rewriter'
|
||||
import { collectWslMoveScope } from './wsl-move-scope'
|
||||
import { rewriteOrcadMigrationWorktreeId } from '../../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite'
|
||||
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
|
||||
const repo = (id: string, path: string, extra: Partial<Repo> = {}): Repo => ({
|
||||
id,
|
||||
path,
|
||||
displayName: id,
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
...extra
|
||||
})
|
||||
|
||||
const folder = (id: string, folderPath: string): FolderWorkspace => ({
|
||||
id,
|
||||
projectGroupId: 'group',
|
||||
name: id,
|
||||
folderPath,
|
||||
linkedTask: null,
|
||||
comment: '',
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 0,
|
||||
createdAt: 0,
|
||||
updatedAt: 0
|
||||
})
|
||||
|
||||
describe('collectWslMoveScope with mapped drives', () => {
|
||||
const state = {
|
||||
repos: [
|
||||
repo('app', 'W:\\home\\me\\App', { worktreeBasePath: 'trees' }),
|
||||
repo('drvfs', 'W:\\mnt\\c\\src\\site')
|
||||
],
|
||||
folderWorkspaces: [folder('notes', 'W:\\home\\me\\Notes')],
|
||||
projectGroups: []
|
||||
}
|
||||
|
||||
it('takes local W: projects with the mapping and ignores them without it', () => {
|
||||
expect(collectWslMoveScope(state, 'Ubuntu', [W])).toEqual({
|
||||
repoIds: ['app'],
|
||||
folderWorkspaceIds: ['notes'],
|
||||
refused: [{ kind: 'repo', id: 'drvfs', reason: 'windows-drive' }]
|
||||
})
|
||||
expect(collectWslMoveScope(state, 'Ubuntu')).toEqual({
|
||||
repoIds: [],
|
||||
folderWorkspaceIds: [],
|
||||
refused: []
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a mapped-drive repo with worktrees Git for Windows created', () => {
|
||||
expect(collectWslMoveScope(state, 'Ubuntu', [W], new Set(['app'])).refused).toContainEqual({
|
||||
kind: 'repo',
|
||||
id: 'app',
|
||||
reason: 'windows-git-worktrees'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('the move path rewriter with mapped drives', () => {
|
||||
const rewriter = createUncToLinuxPathRewriter('Ubuntu', [W])
|
||||
|
||||
it('rewrites W: worktree ids, paths and file URLs to Linux', () => {
|
||||
expect(rewriteOrcadMigrationWorktreeId('repoId::W:\\home\\me\\App', rewriter)).toBe(
|
||||
'repoId::/home/me/App'
|
||||
)
|
||||
expect(rewriter.path('W:\\home\\me\\App\\src', 'maybe-absolute')).toBe('/home/me/App/src')
|
||||
expect(rewriter.path('file:///W:/home/me/App/x.ts', 'url')).toBe('file:///home/me/App/x.ts')
|
||||
})
|
||||
|
||||
it('leaves a path on an unmapped letter untouched', () => {
|
||||
expect(rewriter.path('X:\\home\\me\\App', 'absolute')).toBe('X:\\home\\me\\App')
|
||||
expect(rewriter.path('file:///X:/home/me', 'url')).toBe('file:///X:/home/me')
|
||||
expect(createUncToLinuxPathRewriter('Ubuntu').path('W:\\home\\me', 'absolute')).toBe(
|
||||
'W:\\home\\me'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the move normalizer with mapped drives', () => {
|
||||
const normalize = createWslMoveStringNormalizer({
|
||||
distro: 'Ubuntu',
|
||||
hostAliases: [],
|
||||
mappedDrives: [W]
|
||||
})
|
||||
|
||||
it('normalizes W: and UNC spellings of the same identity equally', () => {
|
||||
const unc = '\\\\wsl.localhost\\Ubuntu\\home\\me\\App'
|
||||
for (const [drive, share] of [
|
||||
['W:\\home\\me\\App', unc],
|
||||
['repoId::W:\\home\\me\\App', `repoId::${unc}`],
|
||||
['worktree:repoId::W:\\home\\me\\App', `worktree:repoId::${unc}`],
|
||||
['file:///W:/home/me/App/x.ts', 'file://wsl.localhost/Ubuntu/home/me/App/x.ts']
|
||||
]) {
|
||||
expect(normalize(drive)).toBe(normalize(share))
|
||||
expect(normalize(drive)).not.toBe(drive)
|
||||
}
|
||||
expect(normalize('X:\\home\\me\\App')).toBe('X:\\home\\me\\App')
|
||||
})
|
||||
})
|
||||
|
||||
describe('a retained mapped-drive row', () => {
|
||||
it('keeps the identity the move took, read with its mapping', () => {
|
||||
const cutover = wslMoveCutoverFixture('move-1', 'retained', { mappedDrives: [W] }, {})
|
||||
const row = repo('repo-1', 'W:\\home\\dev\\repo-1')
|
||||
const taken = wslMoveTakenRowIdentity(cutover, { kind: 'repo', id: 'repo-1' })
|
||||
expect(wslMoveLocalRowIdentity(row, 'Ubuntu', cutover.mappedDrives)).toBe(taken)
|
||||
expect(wslMoveLocalRowIdentity(row, 'Ubuntu')).not.toBe(taken)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* The drive letters mapped into a distro (`net use W: \\wsl.localhost\Ubuntu`) that local
|
||||
* projects are saved under. Read fresh at preview and again at start, never from a cache: the
|
||||
* move journals this mapping, and every recovery maps the moved paths with it.
|
||||
*/
|
||||
import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import {
|
||||
wslMappedDriveMatches,
|
||||
type WslMappedDriveRead
|
||||
} from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { isLocalWslMoveRow } from '../quiescence/wsl-move-scope-guard'
|
||||
import { wslMoveRepoPaths } from './wsl-move-scope'
|
||||
|
||||
export type WslMoveMappedDrivesRead = {
|
||||
mappedDrives: WslMappedDrive[]
|
||||
/** Windows did not answer for these letters, which local projects use. */
|
||||
unverifiableLetters: string[]
|
||||
}
|
||||
|
||||
const DRIVE_PATH = /^([A-Za-z]):[\\/]/
|
||||
|
||||
/** The distinct drive letters, uppercase, every path the move's scope reads names. */
|
||||
export function wslMoveDriveLettersInUse(rows: {
|
||||
repos: readonly Repo[]
|
||||
folderWorkspaces: readonly FolderWorkspace[]
|
||||
}): string[] {
|
||||
const paths = [
|
||||
...rows.repos.filter(isLocalWslMoveRow).flatMap((repo) => wslMoveRepoPaths(repo)),
|
||||
...rows.folderWorkspaces.filter(isLocalWslMoveRow).map((folder) => folder.folderPath)
|
||||
]
|
||||
const letters = new Set(paths.flatMap((path) => DRIVE_PATH.exec(path)?.[1].toUpperCase() ?? []))
|
||||
return [...letters].sort()
|
||||
}
|
||||
|
||||
export async function readWslMoveMappedDrives(
|
||||
rows: { repos: readonly Repo[]; folderWorkspaces: readonly FolderWorkspace[] },
|
||||
distro: string,
|
||||
readShare: (letter: string) => Promise<WslMappedDriveRead>
|
||||
): Promise<WslMoveMappedDrivesRead> {
|
||||
const letters = wslMoveDriveLettersInUse(rows)
|
||||
const reads = await Promise.all(
|
||||
letters.map(async (letter) => ({
|
||||
letter,
|
||||
read: await readShare(letter).catch((): WslMappedDriveRead => 'unverifiable')
|
||||
}))
|
||||
)
|
||||
const unverifiableLetters = reads
|
||||
.filter(({ read }) => read === 'unverifiable')
|
||||
.map(({ letter }) => letter)
|
||||
const mappedDrives = reads.flatMap(({ letter, read }) =>
|
||||
read !== 'unverifiable' && wslMappedDriveMatches(read.share, distro, undefined)
|
||||
? [{ letter, share: read.share }]
|
||||
: []
|
||||
)
|
||||
return { mappedDrives, unverifiableLetters }
|
||||
}
|
||||
@@ -1,23 +1,33 @@
|
||||
// Convert only the moved distro's UNC paths; unrelated paths remain unchanged.
|
||||
import { wslUncPathToLinux } from '../../../../shared/file-access/wsl-paths'
|
||||
// Convert only the moved distro's UNC and mapped-drive paths; unrelated paths remain unchanged.
|
||||
import {
|
||||
wslMappedDriveFileUrlToLinux,
|
||||
wslMoveSourcePathToLinux,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { OrcadMigrationPathRewriter } from '../../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite'
|
||||
|
||||
export function createUncToLinuxPathRewriter(distro: string): OrcadMigrationPathRewriter {
|
||||
export function createUncToLinuxPathRewriter(
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): OrcadMigrationPathRewriter {
|
||||
const fileUrl = new RegExp(`^file://(?:wsl\\.localhost|wsl\\$)/([^/]+)(/.*)?$`, 'i')
|
||||
const toLinux = (value: string): string | null =>
|
||||
wslMoveSourcePathToLinux(value, distro, mappedDrives)
|
||||
return {
|
||||
path: (value, form) => {
|
||||
switch (form) {
|
||||
case 'absolute':
|
||||
return wslUncPathToLinux(value, distro) ?? value
|
||||
return toLinux(value) ?? value
|
||||
case 'maybe-absolute':
|
||||
return wslUncPathToLinux(value, distro) ?? (isRelative(value) ? toPosix(value) : value)
|
||||
return toLinux(value) ?? (isRelative(value) ? toPosix(value) : value)
|
||||
case 'relative':
|
||||
return toPosix(value)
|
||||
case 'url': {
|
||||
const match = fileUrl.exec(value)
|
||||
return match && decodeSegment(match[1]).toLowerCase() === distro.toLowerCase()
|
||||
? `file://${match[2] ?? '/'}`
|
||||
: value
|
||||
if (match && decodeSegment(match[1]).toLowerCase() === distro.toLowerCase()) {
|
||||
return `file://${match[2] ?? '/'}`
|
||||
}
|
||||
return wslMappedDriveFileUrlToLinux(value, distro, mappedDrives) ?? value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,21 @@ import type { ProjectGroup } from '../../../../shared/project/groups/project-gro
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import {
|
||||
isDrvfsLinuxPath,
|
||||
resolveWslRepoWorktreeBasePath,
|
||||
wslUncPathToLinux
|
||||
resolveWslRepoWorktreeBasePath
|
||||
} from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
toWslDistroUncPath,
|
||||
wslMoveSourcePathToLinux,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
|
||||
export type WslMoveScopeRefusal =
|
||||
/** Distro access does not make Windows-drive projects Linux-owned. */
|
||||
'windows-drive' | 'mixed-locations' | 'not-local'
|
||||
| 'windows-drive'
|
||||
| 'mixed-locations'
|
||||
| 'not-local'
|
||||
/** Linked worktrees Git for Windows created: the host's Git can't follow their links. */
|
||||
| 'windows-git-worktrees'
|
||||
|
||||
export type WslMoveScope = {
|
||||
repoIds: string[]
|
||||
@@ -27,15 +35,25 @@ type WslMoveScopeState = {
|
||||
projectGroups: readonly ProjectGroup[]
|
||||
}
|
||||
|
||||
export function collectWslMoveScope(state: WslMoveScopeState, distro: string): WslMoveScope {
|
||||
export function collectWslMoveScope(
|
||||
state: WslMoveScopeState,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = [],
|
||||
/** Mapped-drive repos with worktrees Git for Windows created (wsl-move-windows-git-worktrees). */
|
||||
windowsGitWorktreeRepoIds: ReadonlySet<string> = new Set()
|
||||
): WslMoveScope {
|
||||
const scope: WslMoveScope = { repoIds: [], folderWorkspaceIds: [], refused: [] }
|
||||
const toLinux = (path: string): string | null =>
|
||||
wslMoveSourcePathToLinux(path, distro, mappedDrives)
|
||||
for (const repo of state.repos) {
|
||||
const paths = wslMoveRepoPaths(repo)
|
||||
const paths = wslMoveMappedRepoPaths(repo, mappedDrives)
|
||||
// Partly in-distro repos must refuse visibly rather than disappear from the preview.
|
||||
if (!paths.some((path) => wslUncPathToLinux(path, distro) !== null)) {
|
||||
if (!paths.some((path) => toLinux(path) !== null)) {
|
||||
continue
|
||||
}
|
||||
const reason = refusalFor(paths, distro, getRepoExecutionHostId(repo) !== 'local')
|
||||
const reason =
|
||||
refusalFor(paths, toLinux, getRepoExecutionHostId(repo) !== 'local') ??
|
||||
(windowsGitWorktreeRepoIds.has(repo.id) ? 'windows-git-worktrees' : null)
|
||||
if (reason) {
|
||||
scope.refused.push({ kind: 'repo', id: repo.id, reason })
|
||||
} else {
|
||||
@@ -47,14 +65,14 @@ export function collectWslMoveScope(state: WslMoveScopeState, distro: string): W
|
||||
projectGroups: [...state.projectGroups]
|
||||
}
|
||||
for (const workspace of state.folderWorkspaces) {
|
||||
if (wslUncPathToLinux(workspace.folderPath, distro) === null) {
|
||||
if (toLinux(workspace.folderPath) === null) {
|
||||
continue
|
||||
}
|
||||
// Isolate this row: other hosts may reuse the same folder ID.
|
||||
const remote =
|
||||
resolveFolderWorkspaceHost({ ...hostState, folderWorkspaces: [workspace] }, workspace.id)
|
||||
.kind !== 'local'
|
||||
const reason = refusalFor([workspace.folderPath], distro, remote)
|
||||
const reason = refusalFor([workspace.folderPath], toLinux, remote)
|
||||
if (reason) {
|
||||
scope.refused.push({ kind: 'folder-workspace', id: workspace.id, reason })
|
||||
} else {
|
||||
@@ -65,13 +83,22 @@ export function collectWslMoveScope(state: WslMoveScopeState, distro: string): W
|
||||
}
|
||||
|
||||
export function wslMoveRepoPaths(repo: Repo): string[] {
|
||||
return wslMoveMappedRepoPaths(repo, [])
|
||||
}
|
||||
|
||||
/** Every folder a repo names; relative and Linux bases resolve against its share spelling. */
|
||||
export function wslMoveMappedRepoPaths(
|
||||
repo: Repo,
|
||||
mappedDrives: readonly WslMappedDrive[]
|
||||
): string[] {
|
||||
const repoPath = toWslDistroUncPath(repo.path, mappedDrives)
|
||||
const base = repo.worktreeBasePath
|
||||
? resolveWslRepoWorktreeBasePath(repo.path, repo.worktreeBasePath)
|
||||
? resolveWslRepoWorktreeBasePath(repoPath, repo.worktreeBasePath)
|
||||
: undefined
|
||||
return [
|
||||
repo.path,
|
||||
// Resolve relative bases before checking distro ownership.
|
||||
...(base ? [isRelative(base) ? posixJoinUnc(repo.path, base) : base] : []),
|
||||
...(base ? [isRelative(base) ? posixJoinUnc(repoPath, base) : base] : []),
|
||||
...(repo.folderUpgradeGitRootPath ? [repo.folderUpgradeGitRootPath] : []),
|
||||
...(repo.customWorktreeVisibilitySources ?? []).map((source) => source.rootPath),
|
||||
...(repo.externalWorktreeInboxBaselinePaths ?? []),
|
||||
@@ -90,7 +117,7 @@ function posixJoinUnc(repoUnc: string, relative: string): string {
|
||||
|
||||
function refusalFor(
|
||||
paths: readonly string[],
|
||||
distro: string,
|
||||
toLinux: (path: string) => string | null,
|
||||
remote: boolean
|
||||
): WslMoveScopeRefusal | null {
|
||||
if (remote) {
|
||||
@@ -98,7 +125,7 @@ function refusalFor(
|
||||
}
|
||||
const linuxPaths: string[] = []
|
||||
for (const path of paths) {
|
||||
const linux = wslUncPathToLinux(path, distro)
|
||||
const linux = toLinux(path)
|
||||
if (linux === null) {
|
||||
return 'mixed-locations'
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
createWslMoveStringNormalizer,
|
||||
isRecord
|
||||
} from './wsl-move-canonical-form'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { WSL_MOVE_DROPPED_PTY_BINDING_KEYS } from '../../../../shared/wsl-move/wsl-move-dispositions'
|
||||
import {
|
||||
fieldOf,
|
||||
@@ -34,6 +35,8 @@ import {
|
||||
|
||||
export type WslMoveProjectionScope = {
|
||||
distro: string
|
||||
/** The move's mapped drives, from its cutover. */
|
||||
mappedDrives?: readonly WslMappedDrive[]
|
||||
repoIds: ReadonlySet<string>
|
||||
folderWorkspaceIds: ReadonlySet<string>
|
||||
ownerHostId: ExecutionHostId
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import {
|
||||
findWindowsGitWorktreeRepoIds,
|
||||
windowsGitWorktreePaths
|
||||
} from './wsl-move-windows-git-worktrees'
|
||||
|
||||
let root: string
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'wsl-move-wingit-'))
|
||||
})
|
||||
afterEach(() => {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function worktreeLink(repo: string, name: string, link: string): void {
|
||||
const entry = join(repo, '.git', 'worktrees', name)
|
||||
mkdirSync(entry, { recursive: true })
|
||||
writeFileSync(join(entry, 'gitdir'), `${link}\n`)
|
||||
}
|
||||
|
||||
describe('windowsGitWorktreePaths', () => {
|
||||
it('names the worktrees whose links Git for Windows wrote', async () => {
|
||||
const repo = join(root, 'app')
|
||||
worktreeLink(repo, 'win', 'W:/home/me/app-trees/win/.git')
|
||||
worktreeLink(repo, 'linux', '/home/me/app-trees/linux/.git')
|
||||
expect(await windowsGitWorktreePaths(repo, 'Ubuntu')).toEqual(['W:/home/me/app-trees/win'])
|
||||
})
|
||||
|
||||
it('names a repo that is itself a worktree Git for Windows created', async () => {
|
||||
const repo = join(root, 'tree')
|
||||
mkdirSync(repo)
|
||||
writeFileSync(join(repo, '.git'), 'gitdir: W:/home/me/app/.git/worktrees/tree\n')
|
||||
expect(await windowsGitWorktreePaths(repo, 'Ubuntu')).toEqual([repo])
|
||||
})
|
||||
|
||||
it('finds none for a folder outside Git or a repo with Linux-only links', async () => {
|
||||
expect(await windowsGitWorktreePaths(join(root, 'none'), 'Ubuntu')).toEqual([])
|
||||
const repo = join(root, 'linux')
|
||||
worktreeLink(repo, 'a', '/home/me/a/.git')
|
||||
expect(await windowsGitWorktreePaths(repo, 'Ubuntu')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('findWindowsGitWorktreeRepoIds', () => {
|
||||
const repo = (id: string, path: string): Repo => ({
|
||||
id,
|
||||
path,
|
||||
displayName: id,
|
||||
badgeColor: '#000',
|
||||
addedAt: 0
|
||||
})
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
|
||||
it('checks only mapped-drive repos, and fails closed on an unreadable one', async () => {
|
||||
const checked: string[] = []
|
||||
const ids = await findWindowsGitWorktreeRepoIds(
|
||||
[
|
||||
repo('win', 'W:\\home\\me\\win'),
|
||||
repo('clean', 'W:\\home\\me\\clean'),
|
||||
repo('broken', 'W:\\home\\me\\broken'),
|
||||
repo('unc', '\\\\wsl.localhost\\Ubuntu\\home\\me\\unc')
|
||||
],
|
||||
'Ubuntu',
|
||||
[W],
|
||||
async (path) => {
|
||||
checked.push(path)
|
||||
if (path.endsWith('broken')) {
|
||||
throw new Error('EACCES')
|
||||
}
|
||||
return path.endsWith('win') ? ['W:/home/me/win-tree'] : []
|
||||
}
|
||||
)
|
||||
expect([...ids].sort()).toEqual(['broken', 'win'])
|
||||
expect(checked).not.toContain('\\\\wsl.localhost\\Ubuntu\\home\\me\\unc')
|
||||
})
|
||||
})
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* A repo saved under a mapped drive may have linked worktrees Git for Windows created: their
|
||||
* `.git` files and `.git/worktrees/<name>/gitdir` links hold `W:/…` paths. The host's Linux Git
|
||||
* can't follow those, and its `git worktree prune` would delete their metadata, so such a repo
|
||||
* stays here (the opposite of wsl-drive-project-windows-git's `wsl-authored-worktrees`).
|
||||
*/
|
||||
import { readFile, stat } from 'node:fs/promises'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { toWindowsWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import {
|
||||
wslMappedDriveOf,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import {
|
||||
isForeignLink,
|
||||
readWorktreeLinks
|
||||
} from '../../../git/worktrees/removal/worktree-prune-guard'
|
||||
import { isLocalWslMoveRow } from '../quiescence/wsl-move-scope-guard'
|
||||
|
||||
/** The worktrees of the repo at `repoPath` whose links Git for Windows wrote; none outside Git. */
|
||||
export async function windowsGitWorktreePaths(repoPath: string, distro: string): Promise<string[]> {
|
||||
const dotGit = join(repoPath, '.git')
|
||||
const info = await stat(dotGit).catch((error: unknown) => {
|
||||
// Only "no `.git`" means no Git; any other failure fails the check closed.
|
||||
if (isMissing(error)) {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
})
|
||||
if (!info) {
|
||||
return []
|
||||
}
|
||||
let commonDir = dotGit
|
||||
if (!info.isDirectory()) {
|
||||
const link = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'))?.[1]?.trim()
|
||||
if (!link) {
|
||||
return []
|
||||
}
|
||||
// The repo is itself a linked worktree Git for Windows created.
|
||||
if (isForeignLink(link, true)) {
|
||||
return [repoPath]
|
||||
}
|
||||
const gitDir = link.startsWith('/')
|
||||
? toWindowsWslUncPath(link, distro)
|
||||
: resolve(repoPath, link)
|
||||
const common = (await readFile(join(gitDir, 'commondir'), 'utf8').catch(() => '')).trim()
|
||||
commonDir = common ? resolve(gitDir, common) : gitDir
|
||||
}
|
||||
return (await readWorktreeLinks(join(commonDir, 'worktrees')))
|
||||
.filter(({ link }) => isForeignLink(link, true))
|
||||
.map(({ link }) => link.replace(/[\\/]\.git$/, ''))
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
|
||||
/**
|
||||
* The local repos on a mapped drive with worktrees the host's Git can't use. A repo whose links
|
||||
* can't be read counts as one: the check fails closed.
|
||||
*/
|
||||
export async function findWindowsGitWorktreeRepoIds(
|
||||
repos: readonly Repo[],
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[],
|
||||
windowsGitWorktrees: (repoPath: string, distro: string) => Promise<string[]>
|
||||
): Promise<Set<string>> {
|
||||
const onMappedDrive = repos.filter(
|
||||
(repo) => isLocalWslMoveRow(repo) && wslMappedDriveOf(repo.path, mappedDrives) !== null
|
||||
)
|
||||
const found = await Promise.all(
|
||||
onMappedDrive.map(async (repo) =>
|
||||
(await windowsGitWorktrees(repo.path, distro).catch(() => [repo.path])).length > 0
|
||||
? [repo.id]
|
||||
: []
|
||||
)
|
||||
)
|
||||
return new Set(found.flat())
|
||||
}
|
||||
+7
-1
@@ -3,6 +3,7 @@ import type {
|
||||
WslMovePreview,
|
||||
WslMoveResult
|
||||
} from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { WslMoveUseLocallyResult } from '../../../../shared/wsl-move/wsl-moved-project'
|
||||
import type {
|
||||
WslMoveOrchestratorRecord,
|
||||
@@ -42,7 +43,12 @@ export type WslMoveOrchestratorPorts = {
|
||||
* Runs the move. `stillWanted` turns false once the user released or snoozed the distro; the
|
||||
* port checks it after its own waits (the window's panes) and refuses rather than start.
|
||||
*/
|
||||
start: (distro: string, stillWanted: () => boolean) => Promise<WslMoveResult>
|
||||
start: (
|
||||
distro: string,
|
||||
stillWanted: () => boolean,
|
||||
/** The preview's mapped drives; the start refuses if they map elsewhere by now. */
|
||||
mappedDrives: readonly WslMappedDrive[]
|
||||
) => Promise<WslMoveResult>
|
||||
finishedMove: (distro: string) => WslMoveFinishedMove | null
|
||||
/** R38: reads the registry and, when ready, the host's catalog; never boots the distro. */
|
||||
checkMovedDistro: (distro: string, move: WslMoveFinishedMove) => Promise<WslMovedDistroVerdict>
|
||||
|
||||
+2
-1
@@ -147,7 +147,8 @@ export async function runWslMoveOrchestratorStep(
|
||||
}
|
||||
const started = record
|
||||
// The port re-checks this once it has the window's panes, just before the driver claims the run.
|
||||
const result = await settle(() => ports.start(distro, () => !changedUnder(started)))
|
||||
const mappedDrives = preview.outcome === 'ready' ? (preview.mappedDrives ?? []) : []
|
||||
const result = await settle(() => ports.start(distro, () => !changedUnder(started), mappedDrives))
|
||||
if (!changedUnder(record)) {
|
||||
commit(apply(record, result), result)
|
||||
}
|
||||
|
||||
@@ -2,18 +2,24 @@
|
||||
import { readWslHostDeployments } from '../../../../shared/remote-runtime/host-store/runtime-environment-registry'
|
||||
import { wslMoveJournalKey } from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import { parseWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
toWslDistroUncPath,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { Store } from '../../loading-store/store'
|
||||
import { isLocalWslMoveRow, wslMoveHostDistro } from './wsl-move-scope-guard'
|
||||
import { defaultWslOrcadEnvironmentId } from '../../../wsl/orcad/wsl-orcad-deploy'
|
||||
|
||||
/**
|
||||
* A bridge project of the distro (local, on its UNC path, not moved) or its WSL host record. A
|
||||
* host file that cannot be read counts as in use: a failed read never makes a distro look gone.
|
||||
* A bridge project of the distro (local, on its UNC path or a drive mapped into it, not moved) or
|
||||
* its WSL host record. A host file that cannot be read counts as in use: a failed read never makes
|
||||
* a distro look gone. Drives are read only when nothing else keeps the distro; unread, in use.
|
||||
*/
|
||||
export async function isDistroInUse(
|
||||
store: Pick<Store, 'getRepos' | 'getFolderWorkspaces'>,
|
||||
userDataPath: string,
|
||||
distro: string
|
||||
distro: string,
|
||||
readMappedDrives?: () => Promise<readonly WslMappedDrive[] | 'unverifiable'>
|
||||
): Promise<boolean> {
|
||||
const environmentId = defaultWslOrcadEnvironmentId(distro)
|
||||
try {
|
||||
@@ -29,10 +35,23 @@ export async function isDistroInUse(
|
||||
return true
|
||||
}
|
||||
const key = wslMoveJournalKey(distro)
|
||||
const onDistro = (path: string): boolean => {
|
||||
const unc = parseWslUncPath(path)
|
||||
return unc !== null && wslMoveJournalKey(unc.distro) === key
|
||||
const hasBridgeProject = (mappedDrives: readonly WslMappedDrive[]): boolean =>
|
||||
hasUnmovedProjectIn(store, (path) => {
|
||||
const unc = parseWslUncPath(toWslDistroUncPath(path, mappedDrives))
|
||||
return unc !== null && wslMoveJournalKey(unc.distro) === key
|
||||
})
|
||||
const onUnc = hasBridgeProject([])
|
||||
if (onUnc || !readMappedDrives) {
|
||||
return onUnc
|
||||
}
|
||||
const mappedDrives = await readMappedDrives().catch(() => 'unverifiable' as const)
|
||||
return mappedDrives === 'unverifiable' || hasBridgeProject(mappedDrives)
|
||||
}
|
||||
|
||||
function hasUnmovedProjectIn(
|
||||
store: Pick<Store, 'getRepos' | 'getFolderWorkspaces'>,
|
||||
onDistro: (path: string) => boolean
|
||||
): boolean {
|
||||
return (
|
||||
store
|
||||
.getRepos()
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
isLinuxSpelled
|
||||
} from '../manifest-scope/wsl-move-comparable-path'
|
||||
import type { SessionInfo } from '../../../daemon/protocol/daemon-session-info'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
|
||||
export type WslMoveExitProof =
|
||||
| { verdict: 'exited' }
|
||||
@@ -27,6 +28,8 @@ export type WslMoveExitProofSources = {
|
||||
|
||||
export type WslMoveExitProofScope = {
|
||||
distro: string
|
||||
/** The move's mapped drives, from its cutover: a Windows shell in `W:\x` is in the distro. */
|
||||
mappedDrives?: readonly WslMappedDrive[]
|
||||
/** Session workspace keys: <repoId>::<path> or folder:<id>. */
|
||||
workspaceKeys: ReadonlySet<string>
|
||||
/** Cover sessions whose IDs predate the minted workspace format. */
|
||||
@@ -62,11 +65,10 @@ export async function proveWslMoveTerminalsExited(
|
||||
if (fallbackSessions > 0) {
|
||||
return { verdict: 'unverifiable', reason: 'terminals are running outside the daemon' }
|
||||
}
|
||||
const { distro } = scope
|
||||
const scopeKeys = new Set([...scope.workspaceKeys].map((key) => comparableKey(key, distro)))
|
||||
const scopeKeys = new Set([...scope.workspaceKeys].map((key) => comparableKey(key, scope)))
|
||||
const roots = [...scope.workspaceKeys].flatMap((key) => {
|
||||
const path = keyPath(key)
|
||||
const root = path === null ? null : comparableWslPath(path, distro)
|
||||
const root = path === null ? null : comparableWslPath(path, scope.distro, scope.mappedDrives)
|
||||
return root === null ? [] : [root]
|
||||
})
|
||||
const live: string[] = []
|
||||
@@ -104,19 +106,19 @@ function attributeSession(
|
||||
}
|
||||
const { worktreeId } = parsePtySessionId(session.sessionId)
|
||||
if (worktreeId !== null) {
|
||||
if (scopeKeys.has(comparableKey(worktreeId, scope.distro))) {
|
||||
if (scopeKeys.has(comparableKey(worktreeId, scope))) {
|
||||
return 'in-scope'
|
||||
}
|
||||
// Another workspace's shell can still have changed into a moved folder.
|
||||
return attributeByCwd(session, scope.distro, roots) === 'in-scope' ? 'in-scope' : 'elsewhere'
|
||||
return attributeByCwd(session, scope, roots) === 'in-scope' ? 'in-scope' : 'elsewhere'
|
||||
}
|
||||
return attributeByCwd(session, scope.distro, roots)
|
||||
return attributeByCwd(session, scope, roots)
|
||||
}
|
||||
|
||||
// Without workspace identity, cwd is the only attribution evidence.
|
||||
function attributeByCwd(
|
||||
session: CensusSession,
|
||||
distro: string,
|
||||
{ distro, mappedDrives }: Pick<WslMoveExitProofScope, 'distro' | 'mappedDrives'>,
|
||||
roots: readonly string[]
|
||||
): Attribution {
|
||||
const { cwd, wslDistro } = session
|
||||
@@ -124,7 +126,7 @@ function attributeByCwd(
|
||||
return 'unknown'
|
||||
}
|
||||
const inDistro = typeof wslDistro === 'string' && sameDistro(wslDistro, distro)
|
||||
const path = comparableWslPath(cwd, distro)
|
||||
const path = comparableWslPath(cwd, distro, mappedDrives)
|
||||
const underRoot = path !== null && roots.some((root) => isAtOrUnder(path, root))
|
||||
// A POSIX folder is a Linux path only inside WSL. A Git Bash `/c/...` is not, but a native-tagged
|
||||
// or untagged `wsl.exe` shell's may be, so only one in a moved folder stays unknown.
|
||||
@@ -142,9 +144,12 @@ function keyPath(key: string): string | null {
|
||||
}
|
||||
|
||||
// Canonicalize distro case, UNC aliases, Linux spelling and trailing separators.
|
||||
function comparableKey(key: string, distro: string): string {
|
||||
function comparableKey(
|
||||
key: string,
|
||||
{ distro, mappedDrives }: Pick<WslMoveExitProofScope, 'distro' | 'mappedDrives'>
|
||||
): string {
|
||||
const path = keyPath(key)
|
||||
const comparable = path === null ? null : comparableWslPath(path, distro)
|
||||
const comparable = path === null ? null : comparableWslPath(path, distro, mappedDrives)
|
||||
if (comparable === null) {
|
||||
return key
|
||||
}
|
||||
|
||||
@@ -7,7 +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 type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { wslMoveScopeRootPaths } from '../manifest-scope/wsl-move-scope-roots'
|
||||
import {
|
||||
listWslDriveUncConversions,
|
||||
@@ -35,7 +35,12 @@ export type WslMoveFenceState = {
|
||||
}
|
||||
}
|
||||
|
||||
export type WslMoveFencedRoots = { distro: string; roots: readonly string[] }
|
||||
export type WslMoveFencedRoots = {
|
||||
distro: string
|
||||
roots: readonly string[]
|
||||
/** The move's mapped drives, from its cutover: a spawn in `W:\x` names a fenced folder too. */
|
||||
mappedDrives?: readonly WslMappedDrive[]
|
||||
}
|
||||
|
||||
const phaseIndex = (phase: WslMoveCutoverPhase): number => WSL_MOVE_CUTOVER_PHASES.indexOf(phase)
|
||||
const FENCED_FROM = phaseIndex('source-fenced')
|
||||
@@ -73,13 +78,9 @@ export function withWslDriveUncConversions(
|
||||
}
|
||||
const fencedRoots = [
|
||||
...fence.fencedRoots,
|
||||
...pending.map(({ distro, rootPaths, mappedDrive }) => ({
|
||||
...pending.map(({ distro, rootPaths }) => ({
|
||||
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)) ?? []
|
||||
})
|
||||
roots: rootPaths.flatMap((root) => comparableWslPath(root, distro) ?? [])
|
||||
}))
|
||||
]
|
||||
return { ...fence, fenced, fencedRoots }
|
||||
@@ -124,7 +125,9 @@ function fencedRootsOf(cutover: Readonly<WslMoveCutover>): WslMoveFencedRoots {
|
||||
const roots = wslMoveScopeRootPaths(cutover.manifest).flatMap(
|
||||
(root) => comparableWslPath(root, distro) ?? []
|
||||
)
|
||||
return { distro, roots }
|
||||
return cutover.mappedDrives?.length
|
||||
? { distro, roots, mappedDrives: cutover.mappedDrives }
|
||||
: { distro, roots }
|
||||
}
|
||||
|
||||
function addScope(
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
/** Every recovery and post-commit site maps `W:\` paths with the mapping the cutover journaled. */
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../../shared/remote-runtime/wsl-hosts/wsl-host-internal-gate'
|
||||
import { parseWslMoveCutover } from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import { wslMoveCutoverFixture as cutover } from '../../__fixtures__/wsl-mover/wsl-move-cutover-fixture'
|
||||
import { seedWslMoveCutover } from '../../__fixtures__/wsl-mover/wsl-move-journal-seeding'
|
||||
import {
|
||||
listWslMoveCutovers,
|
||||
writeWslMoveCutover
|
||||
} from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
import {
|
||||
listPendingWslMoveRendererRewrites,
|
||||
wslMoveDesktopRewriteContext
|
||||
} from '../desktop-state/wsl-move-desktop-rewrite'
|
||||
import { resetWslMoveDesktopRewriteStoresForTests } from '../desktop-state/wsl-move-desktop-rewrite-stores'
|
||||
import { proveWslMoveTerminalsExited } from './wsl-move-exit-proof'
|
||||
import { wslMoveFenceFromCutovers } from './wsl-move-fence'
|
||||
import {
|
||||
isWslMoveCwdFenced,
|
||||
loadWslMoveFence,
|
||||
resetWslMoveFenceForTests
|
||||
} from './wsl-move-scope-guard'
|
||||
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
|
||||
let userDataPath: string
|
||||
beforeEach(() => {
|
||||
userDataPath = mkdtempSync(join(tmpdir(), 'wsl-move-mapped-'))
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
resetWslMoveFenceForTests()
|
||||
resetWslMoveDesktopRewriteStoresForTests()
|
||||
rmSync(userDataPath, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('the exit proof with mapped drives', () => {
|
||||
const sources = {
|
||||
listSessions: async () => [
|
||||
{ sessionId: 'other', isAlive: true, cwd: 'W:\\home\\me\\App\\src', wslDistro: null }
|
||||
],
|
||||
countFallbackSessions: () => 0,
|
||||
isScopeFenced: () => true
|
||||
}
|
||||
const scope = {
|
||||
distro: 'Ubuntu',
|
||||
workspaceKeys: new Set(['repo-1::W:\\home\\me\\App']),
|
||||
sessionIds: new Set<string>()
|
||||
}
|
||||
|
||||
it('counts a Windows shell in a moved W: folder as in scope', async () => {
|
||||
expect(await proveWslMoveTerminalsExited(sources, { ...scope, mappedDrives: [W] })).toEqual({
|
||||
verdict: 'live',
|
||||
sessionIds: ['other']
|
||||
})
|
||||
expect(await proveWslMoveTerminalsExited(sources, scope)).toEqual({ verdict: 'exited' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('the fence and the desktop rewrite read the mapping from the cutover', () => {
|
||||
it('fences a spawn in a moved W: folder from the journaled mapping', () => {
|
||||
seedWslMoveCutover(userDataPath, cutover('move-1', 'source-fenced', { mappedDrives: [W] }))
|
||||
const fence = wslMoveFenceFromCutovers(listWslMoveCutovers(userDataPath))
|
||||
expect(fence.fencedRoots).toEqual([
|
||||
{ distro: 'Ubuntu', roots: ['//wsl.localhost/ubuntu/home/dev/repo-1'], mappedDrives: [W] }
|
||||
])
|
||||
loadWslMoveFence(userDataPath)
|
||||
expect(isWslMoveCwdFenced('W:\\home\\dev\\repo-1\\src')).toBe(true)
|
||||
expect(isWslMoveCwdFenced('X:\\home\\dev\\repo-1\\src')).toBe(false)
|
||||
})
|
||||
|
||||
it('rewrites W: paths after commit, for main stores and the renderer', () => {
|
||||
vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1')
|
||||
const committed = cutover('move-1', 'destination-committed', { mappedDrives: [W] })
|
||||
seedWslMoveCutover(userDataPath, committed)
|
||||
const context = wslMoveDesktopRewriteContext(userDataPath, committed)
|
||||
expect(context.rewritePath.path('W:\\home\\dev\\repo-1\\a.ts', 'absolute')).toBe(
|
||||
'/home/dev/repo-1/a.ts'
|
||||
)
|
||||
expect(listPendingWslMoveRendererRewrites(userDataPath)).toMatchObject([
|
||||
{ migrationId: 'move-1', mappedDrives: [W] }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('the cutover record with mapped drives', () => {
|
||||
it('round-trips as version 2, which builds that only read version 1 refuse', () => {
|
||||
const record = cutover('move-1', 'prepared', { mappedDrives: [W] })
|
||||
expect(record.version).toBe(2)
|
||||
const parsed = parseWslMoveCutover(JSON.parse(JSON.stringify(record)))
|
||||
expect(parsed).toMatchObject({ version: 2, mappedDrives: [W] })
|
||||
// Ordinary moves keep version 1.
|
||||
expect(parseWslMoveCutover(JSON.parse(JSON.stringify(cutover())))).toMatchObject({
|
||||
version: 1
|
||||
})
|
||||
})
|
||||
|
||||
it('fails closed on a version that disagrees with its mapping, or a malformed mapping', () => {
|
||||
const record = cutover('move-1', 'prepared', { mappedDrives: [W] })
|
||||
expect(() => parseWslMoveCutover({ ...record, version: 1 })).toThrow()
|
||||
expect(() => parseWslMoveCutover({ ...cutover(), version: 2 })).toThrow()
|
||||
expect(() =>
|
||||
parseWslMoveCutover({ ...record, mappedDrives: [{ letter: 'W', share: 'C:\\' }] })
|
||||
).toThrow()
|
||||
expect(() => parseWslMoveCutover({ ...record, mappedDrives: 'W' })).toThrow()
|
||||
})
|
||||
|
||||
it('never lets a later phase change the journaled mapping', () => {
|
||||
writeWslMoveCutover(userDataPath, cutover('move-1', 'prepared', { mappedDrives: [W] }))
|
||||
expect(() =>
|
||||
writeWslMoveCutover(
|
||||
userDataPath,
|
||||
cutover('move-1', 'source-fenced', {
|
||||
mappedDrives: [{ letter: 'W', share: '\\\\wsl.localhost\\Ubuntu\\home' }]
|
||||
})
|
||||
)
|
||||
).toThrow('wsl_move_binding_changed')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,10 @@
|
||||
// No files move: prove rewritten paths identify the same objects before fencing anything.
|
||||
import { ORCAD_MIGRATION_LOCAL_WSL_SOURCE_RUNTIME_CAPABILITY } from '../../../../shared/remote-runtime/protocol/orcad-runtime-capabilities'
|
||||
import { isDrvfsLinuxPath, wslUncPathToLinux } from '../../../../shared/file-access/wsl-paths'
|
||||
import { isDrvfsLinuxPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
wslMoveSourcePathToLinux,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
|
||||
/** Read once through desktop UNC paths and once on the host. */
|
||||
export type WslMovePathFacts = {
|
||||
@@ -33,11 +37,14 @@ export type WslMovePreflightResult = {
|
||||
export async function preflightWslMovePaths(
|
||||
uncPaths: readonly string[],
|
||||
distro: string,
|
||||
probes: WslMovePreflightProbes
|
||||
probes: WslMovePreflightProbes,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): Promise<WslMovePreflightResult> {
|
||||
const refused: WslMovePreflightResult['refused'] = []
|
||||
const toLinux = (path: string): string | null =>
|
||||
wslMoveSourcePathToLinux(path, distro, mappedDrives)
|
||||
for (const path of uncPaths) {
|
||||
const linux = wslUncPathToLinux(path, distro)
|
||||
const linux = toLinux(path)
|
||||
if (linux === null) {
|
||||
refused.push({ path, reason: 'not-in-distro' })
|
||||
continue
|
||||
@@ -53,7 +60,7 @@ export async function preflightWslMovePaths(
|
||||
? 'unreadable-on-desktop'
|
||||
: host === null
|
||||
? 'missing-on-host'
|
||||
: identityVerdict(desktop, host, distro)
|
||||
: identityVerdict(desktop, host, toLinux)
|
||||
if (reason) {
|
||||
refused.push({ path, reason })
|
||||
}
|
||||
@@ -64,7 +71,7 @@ export async function preflightWslMovePaths(
|
||||
function identityVerdict(
|
||||
desktop: WslMovePathFacts,
|
||||
host: WslMovePathFacts,
|
||||
distro: string
|
||||
toLinux: (path: string) => string | null
|
||||
): WslMovePreflightRefusal | null {
|
||||
if (desktop.marker !== null && host.marker !== null && desktop.marker !== host.marker) {
|
||||
return 'different-object'
|
||||
@@ -74,7 +81,7 @@ function identityVerdict(
|
||||
return desktop.marker !== null && desktop.marker === host.marker ? null : 'identity-unproven'
|
||||
}
|
||||
const asLinux = (value: string | null): string | null =>
|
||||
value === null ? null : (wslUncPathToLinux(value, distro) ?? value.replace(/\\/g, '/'))
|
||||
value === null ? null : (toLinux(value) ?? value.replace(/\\/g, '/'))
|
||||
const sorted = (paths: readonly string[], map: (path: string) => string | null): string[] =>
|
||||
paths.map((path) => map(path) ?? path).sort()
|
||||
const same =
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Fence, Sleep, then prove exit; refusal lifts the fence but leaves already-slept workspaces restorable.
|
||||
import type { WslMoveCutover } from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import type { WslMoveExitProof, WslMoveExitProofScope } from './wsl-move-exit-proof'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type {
|
||||
WslMoveRestoreHintCapture,
|
||||
WslMoveRestoreHintPane
|
||||
@@ -26,7 +27,8 @@ export type WslMoveQuiesceDeps = {
|
||||
livePtyIds: (workspaceIds: readonly string[]) => readonly string[]
|
||||
captureRestoreHints: (
|
||||
panes: WslMoveQuiesceScope['panes'],
|
||||
distro: string
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[]
|
||||
) => Promise<WslMoveRestoreHintCapture>
|
||||
proveExited: (scope: WslMoveExitProofScope) => Promise<WslMoveExitProof>
|
||||
writeCutover: (cutover: WslMoveCutover) => void
|
||||
@@ -197,10 +199,16 @@ async function proveAndRecord(
|
||||
return refuse({ reason: 'terminals-live', liveSessionIds: [...live] })
|
||||
}
|
||||
const distro = fenced.manifest.source.distro
|
||||
const restoreHints = await deps.captureRestoreHints(scope.panes, distro)
|
||||
const mappedDrives = fenced.mappedDrives ?? []
|
||||
const restoreHints = await deps.captureRestoreHints(scope.panes, distro, mappedDrives)
|
||||
const sessionIds = new Set(scope.panes.map((pane) => pane.sessionId))
|
||||
// Check exit last to catch sessions revived during hint capture.
|
||||
const proof = await deps.proveExited({ distro, workspaceKeys: scope.workspaceKeys, sessionIds })
|
||||
const proof = await deps.proveExited({
|
||||
distro,
|
||||
mappedDrives,
|
||||
workspaceKeys: scope.workspaceKeys,
|
||||
sessionIds
|
||||
})
|
||||
if (proof.verdict === 'live') {
|
||||
return refuse({ reason: 'terminals-live', liveSessionIds: proof.sessionIds })
|
||||
}
|
||||
|
||||
@@ -264,8 +264,8 @@ export function isWslMoveCwdFenced(cwd: string): boolean {
|
||||
if (!fence?.readable) {
|
||||
return false
|
||||
}
|
||||
return fence.state.fencedRoots.some(({ distro, roots }) => {
|
||||
const path = comparableWslPath(cwd, distro)
|
||||
return fence.state.fencedRoots.some(({ distro, roots, mappedDrives }) => {
|
||||
const path = comparableWslPath(cwd, distro, mappedDrives)
|
||||
return path !== null && roots.some((root) => isAtOrUnder(path, root))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// Restore the last checkpointed cwd after Sleep instead of silently reopening at the worktree root.
|
||||
import type { ColdRestoreDetection } from '../../../daemon/history/restoration/terminal-history-cold-restore-info'
|
||||
import { wslUncPathToLinux } from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
wslMoveSourcePathToLinux,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
|
||||
export type WslMoveRestoreHint = { paneKey: string; cwd: string }
|
||||
|
||||
@@ -36,7 +39,8 @@ export type ColdRestoreReader = {
|
||||
export async function captureWslMoveRestoreHints(
|
||||
reader: ColdRestoreReader,
|
||||
panes: readonly WslMoveRestoreHintPane[],
|
||||
distro: string
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): Promise<WslMoveRestoreHintCapture> {
|
||||
const capture: WslMoveRestoreHintCapture = {
|
||||
hints: [],
|
||||
@@ -69,7 +73,7 @@ export async function captureWslMoveRestoreHints(
|
||||
capture.noCwdPaneKeys.push(pane.paneKey)
|
||||
continue
|
||||
}
|
||||
const linux = wslMoveHostLinuxCwd(detection.restoreInfo.cwd, pane, distro)
|
||||
const linux = wslMoveHostLinuxCwd(detection.restoreInfo.cwd, pane, distro, mappedDrives)
|
||||
if (!linux) {
|
||||
capture.noCwdPaneKeys.push(pane.paneKey)
|
||||
continue
|
||||
@@ -87,9 +91,10 @@ export async function captureWslMoveRestoreHints(
|
||||
export function wslMoveHostLinuxCwd(
|
||||
cwd: string,
|
||||
pane: WslMoveRestoreHintPane,
|
||||
distro: string
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): string | null {
|
||||
const fromUnc = wslUncPathToLinux(cwd, distro)
|
||||
const fromUnc = wslMoveSourcePathToLinux(cwd, distro, mappedDrives)
|
||||
if (fromUnc) {
|
||||
return fromUnc
|
||||
}
|
||||
|
||||
+8
-4
@@ -3,6 +3,7 @@
|
||||
* Sleep and carries it as a `terminal-history` blob (checkpoint, cwd and size) for the host's own
|
||||
* daemon to cold-restore once. Each document is spooled to a file; only hashes stay in memory.
|
||||
*/
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { closeSync, mkdirSync, openSync, readSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
@@ -60,13 +61,14 @@ export async function readSleptScrollback(
|
||||
distro: string,
|
||||
migrationId: string,
|
||||
workspaceIds: readonly string[],
|
||||
reported: readonly WslMoveRestoreHintPane[] = []
|
||||
reported: readonly WslMoveRestoreHintPane[] = [],
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): Promise<WslMoveSleptScrollback> {
|
||||
if (!deps.sleptScrollback) {
|
||||
return emptyWslMoveSleptScrollback()
|
||||
}
|
||||
return deps
|
||||
.sleptScrollback(panes, distro, migrationId, workspaceIds, reported)
|
||||
.sleptScrollback(panes, distro, migrationId, workspaceIds, reported, mappedDrives)
|
||||
.catch((error: unknown) => {
|
||||
console.warn('[wsl-move] Slept terminal history unreadable:', error)
|
||||
return {
|
||||
@@ -174,7 +176,8 @@ export async function readWslMoveSleptScrollbackFromHistory(
|
||||
spoolRoot: string,
|
||||
/** What the tab bar calls it; an id means nothing to the user. */
|
||||
tabTitle: (tabId: string) => string | null = () => null,
|
||||
now: () => Date = () => new Date()
|
||||
now: () => Date = () => new Date(),
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): Promise<WslMoveSleptScrollback> {
|
||||
const buffers = new Map<string, WslMoveSleptBuffer>()
|
||||
const problems: string[] = []
|
||||
@@ -206,7 +209,8 @@ export async function readWslMoveSleptScrollbackFromHistory(
|
||||
continue
|
||||
}
|
||||
const shellCwd = pane.shellCwd && /^\/(?!\/)/.test(pane.shellCwd) ? pane.shellCwd : null
|
||||
const cwd = shellCwd ?? wslMoveHostLinuxCwd(detection.restoreInfo.cwd, pane, distro)
|
||||
const cwd =
|
||||
shellCwd ?? wslMoveHostLinuxCwd(detection.restoreInfo.cwd, pane, distro, mappedDrives)
|
||||
const document: OrcadMigrationTerminalHistoryDocument = {
|
||||
version: ORCAD_MIGRATION_TERMINAL_HISTORY_VERSION,
|
||||
paneKey: pane.paneKey,
|
||||
|
||||
@@ -93,7 +93,15 @@ async function runMove(
|
||||
const { distro } = request
|
||||
deps.progress({ distro, step: 'preparing' })
|
||||
const startedAt = deps.now()
|
||||
const prepared = await prepareWslMove(deps, request, migrationId, startedAt, 'finish-now')
|
||||
// The start re-reads the mapped drives and refuses if they moved since the preview showed them.
|
||||
const prepared = await prepareWslMove(
|
||||
deps,
|
||||
request,
|
||||
migrationId,
|
||||
startedAt,
|
||||
'finish-now',
|
||||
request.mappedDrives ?? []
|
||||
)
|
||||
if ('outcome' in prepared) {
|
||||
return prepared
|
||||
}
|
||||
@@ -116,7 +124,8 @@ async function runMove(
|
||||
distro,
|
||||
migrationId,
|
||||
scope.workspaceIds,
|
||||
request.sleptPanes
|
||||
request.sleptPanes,
|
||||
prepared.plan.mappedDrives
|
||||
)
|
||||
try {
|
||||
const journaled = await journalSleptWslMove(deps, prepared, migrationId, startedAt, slept)
|
||||
@@ -241,6 +250,7 @@ async function proveStillExited(
|
||||
): Promise<void> {
|
||||
const proof = await deps.quiesce.proveExited({
|
||||
distro: quiesced.manifest.source.distro,
|
||||
mappedDrives: quiesced.mappedDrives ?? [],
|
||||
workspaceKeys: prepared.scope.workspaceKeys,
|
||||
sessionIds: new Set(quiesced.provenExitedSessionIds)
|
||||
})
|
||||
|
||||
@@ -100,11 +100,6 @@ export abstract class RuntimeWorkspaceSleepOperations extends OrcaRuntimeWithRes
|
||||
return this.workspaceSleep.sleepOwnWorktree(worktree.id, opts)
|
||||
}
|
||||
|
||||
/** A workspace paused for a change that was then called off: woken as a phone's open wakes it. */
|
||||
wakePausedWorkspace(worktreeId: string): Promise<void> {
|
||||
return this.queueSleepingAgentWake(worktreeId)
|
||||
}
|
||||
|
||||
/** A phone's wake, queued: it waits out a sleep still running, and a delete cancels it. Never rejects. */
|
||||
protected queueSleepingAgentWake(worktreeId: string): Promise<void> {
|
||||
return this.workspaceSleep
|
||||
|
||||
@@ -2,14 +2,12 @@
|
||||
* 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. A mapped-drive respelling (`mappedDrive`) has a directory of its own too, so
|
||||
* an older build never runs it as a D1c conversion.
|
||||
* reads it as a move.
|
||||
*
|
||||
* - `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
|
||||
@@ -21,14 +19,9 @@ 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 saved (UNC, or on the mapped drive), for a spawn that
|
||||
* names no workspace.
|
||||
*/
|
||||
/** The converting projects' folders, as UNC paths, for a spawn that names no workspace. */
|
||||
rootPaths: string[]
|
||||
phase: WslDriveUncConversionPhase
|
||||
/** Old → new worktree ids, from the profile rewrite; empty before it. */
|
||||
@@ -56,32 +49,20 @@ export function onWslDriveUncConversionJournalChange(
|
||||
return () => changeListeners.delete(listener)
|
||||
}
|
||||
|
||||
const journalOptions = {
|
||||
const journals = createMigrationJournalDirectory({
|
||||
directoryName: 'wsl-drive-unc-conversions',
|
||||
maxFileBytes: 4 * 1024 * 1024,
|
||||
unreadable: (detail: string) => new WslDriveUncConversionJournalUnreadableError(detail),
|
||||
onChange: (userDataPath: string) => {
|
||||
parse: parseWslDriveUncConversion,
|
||||
unreadable: (detail) => new WslDriveUncConversionJournalUnreadableError(detail),
|
||||
onChange: (userDataPath) => {
|
||||
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), ...mappedDriveJournals.list(userDataPath)].map((record) =>
|
||||
structuredClone(record)
|
||||
)
|
||||
return journals.list(userDataPath).map((record) => structuredClone(record))
|
||||
}
|
||||
|
||||
/** A profile's conversions; one journaled before profiles were recorded counts for every profile. */
|
||||
@@ -98,26 +79,11 @@ export function writeWslDriveUncConversion(
|
||||
userDataPath: string,
|
||||
record: WslDriveUncConversion
|
||||
): void {
|
||||
;(record.mappedDrive ? mappedDriveJournals : journals).write(userDataPath, record)
|
||||
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 {
|
||||
@@ -145,9 +111,6 @@ 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],
|
||||
@@ -159,15 +122,6 @@ 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,7 +35,6 @@ 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,7 +49,6 @@ function deps(overrides: Partial<WslDriveUncConversionRunDeps> = {}): WslDriveUn
|
||||
userDataPath: root,
|
||||
profileId: 'profile-1',
|
||||
readDriveMounts: async () => [{ mountPoint: '/mnt/c', windowsRoot: 'C:\\' }],
|
||||
readMappedDriveShare: async () => ({ share: null }),
|
||||
readProfileState: async () => state(),
|
||||
pause: vi.fn(async () => ({ panes: [] })),
|
||||
runWindowsGit: vi.fn(async (args: string[]) =>
|
||||
@@ -160,100 +159,3 @@ 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',
|
||||
mappedDriveShare: SHARE
|
||||
}
|
||||
|
||||
it('journals the respelling with the drive mapping read now, and never asks Windows Git', async () => {
|
||||
const run = deps({
|
||||
readProfileState: async () => mappedState(),
|
||||
readMappedDriveShare: vi.fn(async () => ({ share: 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 () => ({ share: 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 drive remapped to another folder of the distro since the window looked', async () => {
|
||||
const run = deps({
|
||||
readProfileState: async () => mappedState(),
|
||||
readMappedDriveShare: async () => ({ share: String.raw`\\wsl.localhost\Ubuntu\home` })
|
||||
})
|
||||
expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({
|
||||
outcome: 'refused',
|
||||
blockers: [{ kind: 'drive-not-mapped' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('asks to try again when Windows did not answer in time, changing nothing', async () => {
|
||||
const run = deps({
|
||||
readProfileState: async () => mappedState(),
|
||||
readMappedDriveShare: async () => 'unverifiable'
|
||||
})
|
||||
expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({
|
||||
outcome: 'refused',
|
||||
blockers: [{ kind: 'drive-unverifiable' }]
|
||||
})
|
||||
expect(run.pause).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses a project already saved under its share path', async () => {
|
||||
const run = deps({
|
||||
readProfileState: async () => {
|
||||
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: SHARE })
|
||||
})
|
||||
expect(await startWslDriveUncConversion(run, MAPPED_REQUEST)).toEqual({
|
||||
outcome: 'refused',
|
||||
blockers: [{ kind: 'not-convertible', id: 'repo-a', reason: 'duplicate-windows-project' }]
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/**
|
||||
* 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
|
||||
* Starts converting UNC Windows-drive projects to their drive paths (D1c): 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.
|
||||
@@ -28,17 +27,9 @@ import { WslDriveUncKeyCollisionError } from './wsl-drive-unc-identity-rewrite'
|
||||
import {
|
||||
collectWslDriveUncScope,
|
||||
withNestedWslDriveUncProjects,
|
||||
wslDriveUncDuplicatesSplitBy,
|
||||
type WslDriveUncScope,
|
||||
type WslDriveUncTarget
|
||||
wslDriveUncDuplicatesSplitBy
|
||||
} from './wsl-drive-unc-project-scope'
|
||||
import { collectWslMappedDriveScope } from './wsl-mapped-drive-project-scope'
|
||||
import { wslMappedDriveMatches, type WslMappedDriveRead } from './wsl-mapped-drive-share'
|
||||
import { 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'
|
||||
|
||||
@@ -51,8 +42,6 @@ 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>
|
||||
/** Where a drive letter maps right now, never cached: this decides what gets rewritten. */
|
||||
readMappedDriveShare: (letter: string) => Promise<WslMappedDriveRead>
|
||||
/** 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>
|
||||
@@ -71,25 +60,8 @@ export async function startWslDriveUncConversion(
|
||||
if (journals.some((journal) => journal.phase === 'prepared')) {
|
||||
return refused([{ kind: 'conversion-pending' }])
|
||||
}
|
||||
const mappedDrive = request.mappedDriveLetter ? await readMappedDrive(deps, request) : undefined
|
||||
if (mappedDrive === 'unverifiable') {
|
||||
return refused([{ kind: 'drive-unverifiable' }])
|
||||
}
|
||||
if (mappedDrive === null) {
|
||||
return refused([{ kind: 'drive-not-mapped' }])
|
||||
}
|
||||
const state = await deps.readProfileState()
|
||||
const checked = mappedDrive
|
||||
? checkScope(state, request, collectWslMappedDriveScope(state, mappedDrive), mappedDrive)
|
||||
: checkScope(
|
||||
state,
|
||||
request,
|
||||
collectWslDriveUncScope(
|
||||
state,
|
||||
request.distro,
|
||||
(await deps.readDriveMounts(request.distro)) ?? []
|
||||
)
|
||||
)
|
||||
const checked = checkScope(state, request, (await deps.readDriveMounts(request.distro)) ?? [])
|
||||
if ('blockers' in checked) {
|
||||
return refused(checked.blockers)
|
||||
}
|
||||
@@ -98,7 +70,6 @@ export async function startWslDriveUncConversion(
|
||||
try {
|
||||
;({ worktreeIds } = rewriteWslDriveUncState(state, {
|
||||
distro: request.distro,
|
||||
mappedDrive,
|
||||
repoIds,
|
||||
folderWorkspaceIds
|
||||
}))
|
||||
@@ -106,8 +77,7 @@ export async function startWslDriveUncConversion(
|
||||
return refused([stateConflict(error)])
|
||||
}
|
||||
const repos = state.repos.filter((repo) => repoIds.includes(repo.id))
|
||||
// A respelled project keeps the Git it ran; only D1c switches to Git for Windows.
|
||||
const gitBlockers = mappedDrive ? [] : await windowsGitBlockers(deps, repos, request.distro)
|
||||
const gitBlockers = await windowsGitBlockers(deps, repos, request.distro)
|
||||
if (gitBlockers.length > 0) {
|
||||
return refused(gitBlockers)
|
||||
}
|
||||
@@ -131,7 +101,6 @@ export async function startWslDriveUncConversion(
|
||||
migrationId,
|
||||
profileId: deps.profileId,
|
||||
distro: request.distro,
|
||||
...(mappedDrive ? { mappedDrive } : {}),
|
||||
repoIds,
|
||||
folderWorkspaceIds,
|
||||
rootPaths: [
|
||||
@@ -151,36 +120,14 @@ export async function startWslDriveUncConversion(
|
||||
return { outcome: 'restarting', migrationId }
|
||||
}
|
||||
|
||||
/** The drive's share, read now; null when it no longer maps where the window showed. */
|
||||
async function readMappedDrive(
|
||||
deps: Pick<WslDriveUncConversionRunDeps, 'readMappedDriveShare'>,
|
||||
request: WslDriveUncConversionRequest
|
||||
): Promise<WslMappedDrive | null | 'unverifiable'> {
|
||||
const letter = request.mappedDriveLetter ?? ''
|
||||
if (!/^[A-Za-z]$/.test(letter)) {
|
||||
return null
|
||||
}
|
||||
const read = await deps.readMappedDriveShare(letter)
|
||||
if (read === 'unverifiable') {
|
||||
return read
|
||||
}
|
||||
return wslMappedDriveMatches(read.share, request.distro, request.mappedDriveShare)
|
||||
? { letter: letter.toUpperCase(), share: read.share }
|
||||
: null
|
||||
}
|
||||
|
||||
function checkScope(
|
||||
state: PersistedState,
|
||||
request: WslDriveUncConversionRequest,
|
||||
scope: WslDriveUncScope,
|
||||
mappedDrive?: WslMappedDrive
|
||||
mounts: readonly WindowsDriveMount[]
|
||||
):
|
||||
| { repoIds: string[]; folderWorkspaceIds: string[] }
|
||||
| { blockers: WslDriveUncConversionBlocker[] } {
|
||||
const toTarget: WslDriveUncTarget = wslDriveUncRespelling({
|
||||
distro: request.distro,
|
||||
mappedDrive
|
||||
}).path
|
||||
const scope = collectWslDriveUncScope(state, request.distro, mounts)
|
||||
const blockers: WslDriveUncConversionBlocker[] = []
|
||||
const pick = (ids: readonly string[], allowed: readonly string[]): string[] =>
|
||||
ids.filter((id) => {
|
||||
@@ -200,15 +147,15 @@ function checkScope(
|
||||
return { blockers }
|
||||
}
|
||||
const rewriteRoots = (project: { repoIds: string[]; folderWorkspaceIds: string[] }): string[] =>
|
||||
wslDriveUncRewriteRoots(state, { distro: request.distro, mappedDrive, ...project })
|
||||
wslDriveUncRewriteRoots(state, { distro: request.distro, ...project })
|
||||
// Bare paths are re-keyed by folder, so a nested project's rows would move without its ids.
|
||||
const converting = withNestedWslDriveUncProjects(
|
||||
scope,
|
||||
toTarget,
|
||||
request.distro,
|
||||
{ repoIds, folderWorkspaceIds },
|
||||
rewriteRoots
|
||||
)
|
||||
const split = wslDriveUncDuplicatesSplitBy(state, scope, toTarget, converting, () =>
|
||||
const split = wslDriveUncDuplicatesSplitBy(state, scope, request.distro, converting, () =>
|
||||
rewriteRoots(converting)
|
||||
)
|
||||
return split.length > 0
|
||||
|
||||
@@ -30,17 +30,6 @@ 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 { WslMappedDriveRestartReport } from '../../../shared/wsl-move/wsl-drive-unc-conversion-types'
|
||||
import { readWslMappedDriveShareNow, type WslMappedDriveRead } from './wsl-mapped-drive-share'
|
||||
import {
|
||||
assertMappedDriveStillMatches,
|
||||
pausedOf,
|
||||
profileStillNamesMappedDrive,
|
||||
wslMappedDriveMovesDueOf,
|
||||
wslMappedDriveRollbacksOf
|
||||
} from './wsl-mapped-drive-conversion-plan'
|
||||
|
||||
const STARTUP_DRIVE_READ_TIMEOUT_MS = 10_000
|
||||
|
||||
export type WslDriveUncConversionStartupDeps = {
|
||||
/** Where the journal lives. */
|
||||
@@ -50,30 +39,12 @@ export type WslDriveUncConversionStartupDeps = {
|
||||
profileId: string
|
||||
stores: readonly WslDriveUncConversionStore[]
|
||||
now?: () => Date
|
||||
/** Where a drive letter maps right now; a mapped-drive plan runs only while it still matches. */
|
||||
readMappedDriveShare?: (letter: string) => Promise<WslMappedDriveRead>
|
||||
}
|
||||
|
||||
export type WslDriveUncConversionOutcome =
|
||||
| {
|
||||
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
|
||||
/** This run rewrote the profile; a later run only finishes outside stores. */
|
||||
respelledThisRun?: boolean
|
||||
}
|
||||
| { migrationId: string; outcome: 'converted'; repoIds: string[]; folderWorkspaceIds: string[] }
|
||||
/** The profile could not be rewritten; nothing changed, and the panes stay asleep. */
|
||||
| {
|
||||
migrationId: string
|
||||
outcome: 'rolled-back'
|
||||
detail: string
|
||||
/** Set for a mapped-drive plan, which the window reports and whose panes it wakes. */
|
||||
mappedDrive?: { letter: string; workspaceIds: string[] }
|
||||
}
|
||||
| { migrationId: string; outcome: 'rolled-back'; detail: string }
|
||||
/** The profile is converted; `store` failed and retries at the next startup. */
|
||||
| { migrationId: string; outcome: 'resuming'; store: string; detail: string }
|
||||
|
||||
@@ -94,25 +65,12 @@ async function runOne(
|
||||
): Promise<WslDriveUncConversionOutcome> {
|
||||
const { migrationId } = initial
|
||||
let record = initial
|
||||
const advancing = record.phase === 'prepared'
|
||||
if (advancing) {
|
||||
if (record.phase === 'prepared') {
|
||||
try {
|
||||
// Only a plan that hasn't touched the profile may be refused; one past its commit (a crash
|
||||
// before the journal said so) finishes forward with the mapping it recorded.
|
||||
if (record.mappedDrive && profileStillNamesMappedDrive(deps, record)) {
|
||||
await assertMappedDriveStillMatches(deps, record)
|
||||
}
|
||||
record = rewriteProfile(deps, record)
|
||||
} catch (error) {
|
||||
removeWslDriveUncConversion(deps.userDataPath, migrationId)
|
||||
return {
|
||||
migrationId,
|
||||
outcome: 'rolled-back',
|
||||
detail: describe(error),
|
||||
...(record.mappedDrive
|
||||
? { mappedDrive: { letter: record.mappedDrive.letter, workspaceIds: pausedOf(record) } }
|
||||
: {})
|
||||
}
|
||||
return { migrationId, outcome: 'rolled-back', detail: describe(error) }
|
||||
}
|
||||
// Past the commit, so never a rollback: if this write fails the journal stays 'prepared', and
|
||||
// the next startup's rewrite is idempotent.
|
||||
@@ -142,10 +100,7 @@ async function runOne(
|
||||
migrationId,
|
||||
outcome: 'converted',
|
||||
repoIds: record.repoIds,
|
||||
folderWorkspaceIds: record.folderWorkspaceIds,
|
||||
distro: record.distro,
|
||||
...(record.mappedDrive ? { mappedDrive: true } : {}),
|
||||
...(advancing ? { respelledThisRun: true } : {})
|
||||
folderWorkspaceIds: record.folderWorkspaceIds
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,29 +172,8 @@ export function lastWslDriveUncConversionOutcomes(): WslDriveUncConversionOutcom
|
||||
return [...lastOutcomes]
|
||||
}
|
||||
|
||||
let reportTaken = false
|
||||
|
||||
/**
|
||||
* Once per run: a window reload must not open the move, or report a rollback, again. A rolled-back
|
||||
* plan changed nothing, so the workspaces its confirm paused are woken as the window takes this.
|
||||
*/
|
||||
export function takeWslMappedDriveRestartReport(
|
||||
wake: (worktreeId: string) => void,
|
||||
outcomes: readonly WslDriveUncConversionOutcome[] = lastOutcomes
|
||||
): WslMappedDriveRestartReport {
|
||||
if (reportTaken) {
|
||||
return { moves: [], rolledBack: [] }
|
||||
}
|
||||
reportTaken = true
|
||||
const rolledBack = wslMappedDriveRollbacksOf(outcomes)
|
||||
for (const worktreeId of rolledBack.flatMap((rollback) => rollback.workspaceIds)) {
|
||||
wake(worktreeId)
|
||||
}
|
||||
return { moves: wslMappedDriveMovesDueOf(outcomes), rolledBack }
|
||||
}
|
||||
|
||||
/**
|
||||
* Startup, before the profile store opens: with nothing journaled it only lists its directories.
|
||||
* Startup, before the profile store opens: with nothing journaled it only lists one directory.
|
||||
* 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.
|
||||
*/
|
||||
@@ -257,9 +191,6 @@ export async function runPendingWslDriveUncConversions(paths: {
|
||||
}
|
||||
lastOutcomes = await runWslDriveUncConversionsAtStartup({
|
||||
...paths,
|
||||
// Longer than an add's wait: the distro may still be starting with the app.
|
||||
readMappedDriveShare: (letter) =>
|
||||
readWslMappedDriveShareNow(letter, undefined, STARTUP_DRIVE_READ_TIMEOUT_MS),
|
||||
stores: wslDriveUncConversionStores({
|
||||
daemonHistoryDir: getHistoryRoot(),
|
||||
shellHistoryRoots: [getHistoryRoot(), ...listWslHistoryRoots()],
|
||||
|
||||
@@ -68,32 +68,3 @@ describe('rewriteWslDriveUncValue', () => {
|
||||
expect(rewriteWslDriveUncValue(untouched, rewriter)).toBe(untouched)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createWslDriveUncRewriter for a mapped drive', () => {
|
||||
const mapped = createWslDriveUncRewriter({
|
||||
distro: 'Ubuntu',
|
||||
mappedDrive: { letter: 'W', share: String.raw`\\wsl.localhost\Ubuntu` },
|
||||
repoIds: new Set(['r1']),
|
||||
folderWorkspaceIds: new Set(),
|
||||
roots: [String.raw`W:\home\me\App`]
|
||||
})
|
||||
|
||||
it.each([
|
||||
[
|
||||
'a saved path',
|
||||
String.raw`W:\home\me\App\src`,
|
||||
String.raw`\\wsl.localhost\Ubuntu\home\me\App\src`
|
||||
],
|
||||
// Case is folded in the key; the root's own spelling restores it.
|
||||
['a comparison key of the root', 'w:/home/me/app', '//wsl/ubuntu/home/me/App'],
|
||||
['a comparison key inside it', 'w:/home/me/app/src', '//wsl/ubuntu/home/me/App/src'],
|
||||
['a comparison key of another folder', 'w:/home/me/other', 'w:/home/me/other'],
|
||||
['a path of another folder', String.raw`W:\home\me\other`, String.raw`W:\home\me\other`]
|
||||
])('re-keys %s', (_label, value, expected) => {
|
||||
expect(mapped.identity(value)).toBe(expected)
|
||||
})
|
||||
|
||||
it('keeps a D1c comparison key in comparison form', () => {
|
||||
expect(rewriter.identity('//wsl/ubuntu/mnt/c/src/app/lib')).toBe('c:/src/app/lib')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/**
|
||||
* 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`); 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.
|
||||
* 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.
|
||||
*/
|
||||
import { isDeepStrictEqual } from 'node:util'
|
||||
import { normalizeRuntimePathForComparison } from '../../../shared/file-access/cross-platform-path'
|
||||
@@ -25,18 +24,13 @@ import {
|
||||
rewriteOrcadMigrationPathValue,
|
||||
type OrcadMigrationPathRewriter
|
||||
} from '../../persistence/migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite'
|
||||
import {
|
||||
wslDriveUncRespelling,
|
||||
type WslMappedDrive
|
||||
} from '../../../shared/wsl-move/wsl-drive-unc-respelling'
|
||||
import { wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths'
|
||||
|
||||
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>
|
||||
/** The converting projects' folders as saved; a bare path is rewritten only at or under one. */
|
||||
/** UNC folders of the converting projects; a bare path is rewritten only at or under one. */
|
||||
roots: readonly string[]
|
||||
}
|
||||
|
||||
@@ -49,27 +43,54 @@ export type WslDriveUncRewriter = {
|
||||
const VERBATIM_KEYS: ReadonlySet<string> = new Set(['priorWorktreeIds'])
|
||||
|
||||
export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDriveUncRewriter {
|
||||
const respelling = wslDriveUncRespelling(scope, scope.roots)
|
||||
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 roots = scope.roots.flatMap((root) => {
|
||||
const converted = respelling.path(root)
|
||||
return converted ? [normalizeRuntimePathForComparison(converted)] : []
|
||||
const drive = wslUncDrivePathToWindows(root, scope.distro)
|
||||
return drive ? [normalizeRuntimePathForComparison(drive)] : []
|
||||
})
|
||||
const inRoot = (convertedPath: string): boolean => {
|
||||
const comparable = normalizeRuntimePathForComparison(convertedPath)
|
||||
const inRoot = (drivePath: string): boolean => {
|
||||
const comparable = normalizeRuntimePathForComparison(drivePath)
|
||||
return roots.some(
|
||||
(root) => comparable === root || comparable.startsWith(root.endsWith('/') ? root : `${root}/`)
|
||||
)
|
||||
}
|
||||
// Any converted path: an id's owner was checked first.
|
||||
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.
|
||||
const drive: OrcadMigrationPathRewriter = {
|
||||
path: (value, form) => {
|
||||
if (form === 'relative') {
|
||||
return value
|
||||
}
|
||||
if (form === 'url') {
|
||||
return respelling.fileUrl(value)?.url ?? value
|
||||
const parsed = fileUrlDrivePath(value)
|
||||
return parsed
|
||||
? `file:///${parsed.drive.slice(0, 2)}${parsed.tail || '/'}${parsed.extra}`
|
||||
: value
|
||||
}
|
||||
return respelling.path(value) ?? value
|
||||
return wslUncDrivePathToWindows(value, scope.distro) ?? value
|
||||
}
|
||||
}
|
||||
const ownerInScope = (owner: string): boolean => {
|
||||
@@ -84,12 +105,12 @@ export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDr
|
||||
)
|
||||
}
|
||||
const barePath = (value: string): string => {
|
||||
// A comparison key stays one; the respelling checks its root itself.
|
||||
const comparison = respelling.comparisonForm(value)
|
||||
const comparison = comparisonForm.exec(value)
|
||||
if (comparison) {
|
||||
return comparison
|
||||
const mapped = `${comparison[1]}:${comparison[2] ?? '/'}`
|
||||
return inRoot(mapped) ? mapped : value
|
||||
}
|
||||
const mapped = respelling.path(value)
|
||||
const mapped = wslUncDrivePathToWindows(value, scope.distro)
|
||||
return mapped && inRoot(mapped) ? mapped : value
|
||||
}
|
||||
const identity = (value: string): string => {
|
||||
@@ -116,8 +137,8 @@ export function createWslDriveUncRewriter(scope: WslDriveUncRewriteScope): WslDr
|
||||
return ownerInScope(value) ? rewriteOrcadMigrationPathValue(value, 'owner-key', drive) : value
|
||||
}
|
||||
if (/^file:/i.test(value)) {
|
||||
const parsed = respelling.fileUrl(value)
|
||||
return parsed && inRoot(parsed.path) ? parsed.url : value
|
||||
const parsed = fileUrlDrivePath(value)
|
||||
return parsed && inRoot(parsed.drive) ? drive.path(value, 'url') : value
|
||||
}
|
||||
return barePath(value)
|
||||
}
|
||||
@@ -210,3 +231,15 @@ 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,10 +30,6 @@ 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'
|
||||
/** Respelling a mapped drive's project would change where its terminals and Git run. */
|
||||
| 'runtime-would-change'
|
||||
|
||||
export type WslDriveUncScope = {
|
||||
repoIds: string[]
|
||||
@@ -54,7 +50,6 @@ 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)
|
||||
@@ -91,7 +86,7 @@ export function collectWslDriveUncScope(
|
||||
scope.repoIds.push(repo.id)
|
||||
}
|
||||
}
|
||||
refuseWslDriveUncOverlaps(scope, state.repos, uncDrive)
|
||||
refuseOverlaps(scope, state.repos, distro)
|
||||
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 =>
|
||||
@@ -127,18 +122,14 @@ export function collectWslDriveUncScope(
|
||||
}
|
||||
|
||||
/** A bare path is re-keyed by the folder it lies in, so nested projects must convert together. */
|
||||
export function refuseWslDriveUncOverlaps(
|
||||
scope: WslDriveUncScope,
|
||||
repos: readonly Repo[],
|
||||
toTarget: WslDriveUncTarget
|
||||
): void {
|
||||
function refuseOverlaps(scope: WslDriveUncScope, repos: readonly Repo[], distro: string): 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[] => targetRoots(wslMoveRepoPaths(repo), toTarget)
|
||||
const comparable = (repo: Repo): string[] => driveRoots(wslMoveRepoPaths(repo), distro)
|
||||
const refusedRoots = repos.filter((repo) => refusedIds.has(repo.id)).flatMap(comparable)
|
||||
const overlapping = new Set(
|
||||
repos
|
||||
@@ -157,7 +148,7 @@ export function refuseWslDriveUncOverlaps(
|
||||
/** The picked projects and every convertible one nesting with them, which must convert together. */
|
||||
export function withNestedWslDriveUncProjects(
|
||||
scope: WslDriveUncScope,
|
||||
toTarget: WslDriveUncTarget,
|
||||
distro: string,
|
||||
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[]
|
||||
@@ -168,12 +159,12 @@ export function withNestedWslDriveUncProjects(
|
||||
...scope.repoIds.map((id) => ({
|
||||
ids: repoIds,
|
||||
id,
|
||||
roots: targetRoots(rewriteRoots({ repoIds: [id], folderWorkspaceIds: [] }), toTarget)
|
||||
roots: driveRoots(rewriteRoots({ repoIds: [id], folderWorkspaceIds: [] }), distro)
|
||||
})),
|
||||
...scope.folderWorkspaceIds.map((id) => ({
|
||||
ids: folderWorkspaceIds,
|
||||
id,
|
||||
roots: targetRoots(rewriteRoots({ repoIds: [], folderWorkspaceIds: [id] }), toTarget)
|
||||
roots: driveRoots(rewriteRoots({ repoIds: [], folderWorkspaceIds: [id] }), distro)
|
||||
}))
|
||||
]
|
||||
for (let added = true; added;) {
|
||||
@@ -201,7 +192,7 @@ export function withNestedWslDriveUncProjects(
|
||||
export function wslDriveUncDuplicatesSplitBy(
|
||||
state: WslDriveUncScopeState,
|
||||
scope: WslDriveUncScope,
|
||||
toTarget: WslDriveUncTarget,
|
||||
distro: string,
|
||||
converting: { repoIds: readonly string[]; folderWorkspaceIds: readonly string[] },
|
||||
rewriteRoots: () => readonly string[]
|
||||
): string[] {
|
||||
@@ -210,20 +201,20 @@ export function wslDriveUncDuplicatesSplitBy(
|
||||
return []
|
||||
}
|
||||
const convertingFolders = new Set(
|
||||
targetRoots(
|
||||
driveRoots(
|
||||
[
|
||||
...state.repos.filter(({ id }) => converting.repoIds.includes(id)).map(({ path }) => path),
|
||||
...state.folderWorkspaces
|
||||
.filter(({ id }) => converting.folderWorkspaceIds.includes(id))
|
||||
.map(({ folderPath }) => folderPath)
|
||||
],
|
||||
toTarget
|
||||
distro
|
||||
)
|
||||
)
|
||||
const roots = targetRoots(rewriteRoots(), toTarget)
|
||||
const roots = driveRoots(rewriteRoots(), distro)
|
||||
const splits = (folder: string, paths: readonly string[]): boolean =>
|
||||
!targetRoots([folder], toTarget).some((path) => convertingFolders.has(path)) &&
|
||||
targetRoots(paths, toTarget).some((path) => roots.some((root) => isInside(path, root)))
|
||||
!driveRoots([folder], distro).some((path) => convertingFolders.has(path)) &&
|
||||
driveRoots(paths, distro).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)
|
||||
@@ -234,13 +225,10 @@ export function wslDriveUncDuplicatesSplitBy(
|
||||
})
|
||||
}
|
||||
|
||||
/** 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[] {
|
||||
function driveRoots(paths: readonly string[], distro: string): string[] {
|
||||
return paths.flatMap((path) => {
|
||||
const target = toTarget(path)
|
||||
return target ? [normalizeRuntimePathForComparison(target)] : []
|
||||
const drive = wslUncDrivePathToWindows(path, distro)
|
||||
return drive ? [normalizeRuntimePathForComparison(drive)] : []
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
import { composeWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host/execution-host'
|
||||
@@ -24,11 +23,7 @@ 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 {
|
||||
wslDriveUncRespelling,
|
||||
type WslDriveUncRespelling,
|
||||
type WslMappedDrive
|
||||
} from '../../../shared/wsl-move/wsl-drive-unc-respelling'
|
||||
import { wslUncDrivePathToWindows } from '../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
createWslDriveUncRewriter,
|
||||
mergeWslDriveUncKeyedEntries,
|
||||
@@ -40,8 +35,6 @@ 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 = {
|
||||
@@ -61,12 +54,10 @@ 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) {
|
||||
@@ -81,13 +72,11 @@ export function rewriteWslDriveUncState(
|
||||
}
|
||||
next.projects = sameIfUnchanged(
|
||||
next.projects,
|
||||
scope.mappedDrive
|
||||
? withPinnedRuntime(next.projects, repoIds)
|
||||
: withWindowsGit(next.projects, repoIds, scope.distro)
|
||||
withWindowsGit(next.projects, repoIds, scope.distro)
|
||||
)
|
||||
next.projectGroups = sameIfUnchanged(
|
||||
next.projectGroups,
|
||||
withConvertedGroupFolders(next, repoIds, folderWorkspaceIds, respelling)
|
||||
withConvertedGroupFolders(next, repoIds, folderWorkspaceIds, scope.distro)
|
||||
)
|
||||
next.worktreeMeta = withPriorIds(next.worktreeMeta, worktreeIds, (id) => [id])
|
||||
if (next.worktreeMetaByIdentity) {
|
||||
@@ -159,7 +148,6 @@ function collectRewriteRoots(
|
||||
]
|
||||
const ids = createWslDriveUncRewriter({
|
||||
distro: scope.distro,
|
||||
mappedDrive: scope.mappedDrive,
|
||||
repoIds,
|
||||
folderWorkspaceIds,
|
||||
roots
|
||||
@@ -252,25 +240,12 @@ function windowsGitPreference(
|
||||
return { kind: 'wsl', distro, git: 'windows-host' }
|
||||
}
|
||||
|
||||
/**
|
||||
* A project with no saved runtime infers WSL from a share path, so respelling alone would move its
|
||||
* terminals and Git from the global default into the distro, even if the move is then cancelled.
|
||||
*/
|
||||
function withPinnedRuntime(projects: Project[], repoIds: ReadonlySet<string>): Project[] {
|
||||
return projects.map((project) =>
|
||||
project.localWindowsRuntimePreference === undefined &&
|
||||
project.sourceRepoIds.some((id) => repoIds.has(id))
|
||||
? { ...project, localWindowsRuntimePreference: { kind: 'inherit-global' } }
|
||||
: project
|
||||
)
|
||||
}
|
||||
|
||||
/** A group whose projects all convert was made from their parent folder, which converts too. */
|
||||
function withConvertedGroupFolders(
|
||||
state: PersistedState,
|
||||
repoIds: ReadonlySet<string>,
|
||||
folderWorkspaceIds: ReadonlySet<string>,
|
||||
respelling: WslDriveUncRespelling
|
||||
distro: string
|
||||
): PersistedState['projectGroups'] {
|
||||
return state.projectGroups.map((group) => {
|
||||
const members = [
|
||||
@@ -281,7 +256,7 @@ function withConvertedGroupFolders(
|
||||
.filter((folder) => folder.projectGroupId === group.id)
|
||||
.map((folder) => folderWorkspaceIds.has(folder.id))
|
||||
]
|
||||
const parentPath = group.parentPath && respelling.path(group.parentPath)
|
||||
const parentPath = group.parentPath && wslUncDrivePathToWindows(group.parentPath, distro)
|
||||
return parentPath && members.length > 0 && members.every(Boolean)
|
||||
? { ...group, parentPath }
|
||||
: group
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
/**
|
||||
* The mapped-drive half of the startup conversion: whether a respelling plan may still run, and
|
||||
* what the window hears about the ones that ran or rolled back.
|
||||
*/
|
||||
import type {
|
||||
WslMappedDriveMoveDue,
|
||||
WslMappedDriveRollback
|
||||
} from '../../../shared/wsl-move/wsl-drive-unc-conversion-types'
|
||||
import { wslMappedDrivePathToShare } from '../../../shared/wsl-move/wsl-drive-unc-respelling'
|
||||
import { readProfileProjectTransferState } from '../../orca-profiles/project-transfer/profile-project-domain-state'
|
||||
import type { WslDriveUncConversion } from './wsl-drive-unc-conversion-journal'
|
||||
import type {
|
||||
WslDriveUncConversionOutcome,
|
||||
WslDriveUncConversionStartupDeps
|
||||
} from './wsl-drive-unc-conversion-startup'
|
||||
import { wslMappedDriveMatches } from './wsl-mapped-drive-share'
|
||||
|
||||
/** The restart follows the confirm within seconds; a plan this old was left by another run. */
|
||||
const MAPPED_DRIVE_PLAN_MAX_AGE_MS = 60 * 60 * 1000
|
||||
|
||||
/** The workspaces the confirm slept: every re-keyed worktree, and each folder. */
|
||||
export function pausedOf(record: WslDriveUncConversion): string[] {
|
||||
return [
|
||||
...record.worktreeIds.map(([oldId]) => oldId),
|
||||
...record.folderWorkspaceIds.map((id) => `folder:${id}`)
|
||||
]
|
||||
}
|
||||
|
||||
/** Any project of the plan still saved under the drive letter: the profile commit hasn't run. */
|
||||
export function profileStillNamesMappedDrive(
|
||||
deps: WslDriveUncConversionStartupDeps,
|
||||
record: WslDriveUncConversion
|
||||
): boolean {
|
||||
const drive = record.mappedDrive
|
||||
if (!drive) {
|
||||
return false
|
||||
}
|
||||
const { state } = readProfileProjectTransferState(deps.profileId, deps.profileUserDataPath)
|
||||
const onDrive = (path: string): boolean => wslMappedDrivePathToShare(path, drive) !== null
|
||||
return (
|
||||
state.repos.some((repo) => record.repoIds.includes(repo.id) && onDrive(repo.path)) ||
|
||||
state.folderWorkspaces.some(
|
||||
(folder) => record.folderWorkspaceIds.includes(folder.id) && onDrive(folder.folderPath)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A mapped-drive plan names the drive's share as it was at the confirm. One left over (an older
|
||||
* build ran in between, say) or a drive remapped since rolls back instead of rewriting into the
|
||||
* wrong distro or folder.
|
||||
*/
|
||||
export async function assertMappedDriveStillMatches(
|
||||
deps: WslDriveUncConversionStartupDeps,
|
||||
record: WslDriveUncConversion
|
||||
): Promise<void> {
|
||||
const drive = record.mappedDrive
|
||||
if (!drive) {
|
||||
return
|
||||
}
|
||||
const age = (deps.now?.() ?? new Date()).getTime() - Date.parse(record.createdAt)
|
||||
if (!(age >= 0 && age <= MAPPED_DRIVE_PLAN_MAX_AGE_MS)) {
|
||||
throw new Error('wsl_mapped_drive_plan_expired')
|
||||
}
|
||||
const read = deps.readMappedDriveShare
|
||||
? await deps.readMappedDriveShare(drive.letter)
|
||||
: 'unverifiable'
|
||||
if (read === 'unverifiable') {
|
||||
throw new Error('wsl_mapped_drive_unverifiable')
|
||||
}
|
||||
if (!wslMappedDriveMatches(read.share, record.distro, drive.share)) {
|
||||
throw new Error('wsl_mapped_drive_remapped')
|
||||
}
|
||||
}
|
||||
|
||||
export function wslMappedDriveRollbacksOf(
|
||||
outcomes: readonly WslDriveUncConversionOutcome[]
|
||||
): WslMappedDriveRollback[] {
|
||||
return outcomes.flatMap((outcome) =>
|
||||
outcome.outcome === 'rolled-back' && outcome.mappedDrive
|
||||
? [{ reason: rollbackReason(outcome.detail), ...outcome.mappedDrive }]
|
||||
: []
|
||||
)
|
||||
}
|
||||
|
||||
function rollbackReason(detail: string): WslMappedDriveRollback['reason'] {
|
||||
switch (detail) {
|
||||
case 'wsl_mapped_drive_remapped':
|
||||
return 'remapped'
|
||||
case 'wsl_mapped_drive_unverifiable':
|
||||
return 'unverifiable'
|
||||
case 'wsl_mapped_drive_plan_expired':
|
||||
return 'expired'
|
||||
default:
|
||||
return 'failed'
|
||||
}
|
||||
}
|
||||
|
||||
export function wslMappedDriveMovesDueOf(
|
||||
outcomes: readonly WslDriveUncConversionOutcome[]
|
||||
): WslMappedDriveMoveDue[] {
|
||||
return outcomes.flatMap((outcome) =>
|
||||
outcome.outcome === 'converted' &&
|
||||
outcome.mappedDrive &&
|
||||
outcome.respelledThisRun &&
|
||||
outcome.distro
|
||||
? [
|
||||
{
|
||||
distro: outcome.distro,
|
||||
repoIds: outcome.repoIds,
|
||||
folderWorkspaceIds: outcome.folderWorkspaceIds
|
||||
}
|
||||
]
|
||||
: []
|
||||
)
|
||||
}
|
||||
@@ -1,336 +0,0 @@
|
||||
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, vi } 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,
|
||||
takeWslMappedDriveRestartReport
|
||||
} from './wsl-drive-unc-conversion-startup'
|
||||
import {
|
||||
wslMappedDriveMovesDueOf,
|
||||
wslMappedDriveRollbacksOf
|
||||
} from './wsl-mapped-drive-conversion-plan'
|
||||
import type { WslDriveUncConversionStore } from './wsl-drive-unc-conversion-stores'
|
||||
import { rewriteWslDriveUncState } from './wsl-drive-unc-state-rewrite'
|
||||
import type { WslMappedDriveRead } from './wsl-mapped-drive-share'
|
||||
|
||||
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
|
||||
}
|
||||
]
|
||||
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(
|
||||
read: WslMappedDriveRead = { share: SHARE },
|
||||
stores: WslDriveUncConversionStore[] = []
|
||||
) {
|
||||
return runWslDriveUncConversionsAtStartup({
|
||||
userDataPath: root,
|
||||
profileUserDataPath: root,
|
||||
profileId: PROFILE,
|
||||
stores,
|
||||
now: () => new Date('2026-11-16T00:00:05.000Z'),
|
||||
readMappedDriveShare: async () => read
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
respelledThisRun: 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
|
||||
})
|
||||
// With nothing saved it ran the global default; the share path alone would now infer WSL.
|
||||
expect(state.projects[0].localWindowsRuntimePreference).toEqual({ kind: 'inherit-global' })
|
||||
expect(wslMappedDriveMovesDueOf(outcomes)).toEqual([
|
||||
{ distro: 'Ubuntu', repoIds: ['repo-a'], folderWorkspaceIds: ['notes'] }
|
||||
])
|
||||
})
|
||||
|
||||
it('reports the move due only on the run that rewrote the profile', async () => {
|
||||
seedProfile(profileState())
|
||||
// The window's stores never recorded themselves, so the journal outlives the first run.
|
||||
journal()
|
||||
expect(wslMappedDriveMovesDueOf(await run())).toHaveLength(1)
|
||||
expect(listWslDriveUncConversions(root)).toHaveLength(1)
|
||||
expect(wslMappedDriveMovesDueOf(await run())).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['the drive now maps elsewhere', { share: String.raw`\\wsl.localhost\Debian` }, {}],
|
||||
['Windows cannot say where it maps', 'unverifiable' as const, {}],
|
||||
[
|
||||
'the plan is left over from long ago',
|
||||
{ share: SHARE },
|
||||
{ createdAt: '2026-11-01T00:00:00.000Z' }
|
||||
]
|
||||
])('rolls back, changing nothing, when %s', async (_why, read, overrides) => {
|
||||
seedProfile(profileState())
|
||||
journal(overrides)
|
||||
const outcomes = await run(read)
|
||||
expect(outcomes[0]).toMatchObject({ migrationId: 'conv-1', outcome: 'rolled-back' })
|
||||
expect(readProfileProjectTransferState(PROFILE, root).state.repos[0].path).toBe(MAPPED)
|
||||
expect(listWslDriveUncConversions(root)).toEqual([])
|
||||
// The window says why, and main wakes what the confirm paused.
|
||||
expect(wslMappedDriveRollbacksOf(outcomes)).toEqual([
|
||||
{
|
||||
reason: expect.stringMatching(/^(remapped|unverifiable|expired)$/),
|
||||
letter: 'W',
|
||||
workspaceIds: [OLD_ID, 'folder:notes']
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['the drive now maps elsewhere', { share: String.raw`\\wsl.localhost\Debian` }, {}],
|
||||
['Windows cannot say where it maps', 'unverifiable' as const, {}],
|
||||
[
|
||||
'the plan is left over from long ago',
|
||||
{ share: SHARE },
|
||||
{ createdAt: '2026-11-01T00:00:00.000Z' }
|
||||
]
|
||||
])(
|
||||
'finishes forward when the profile already committed and %s',
|
||||
async (_why, read, overrides) => {
|
||||
// A crash between the profile commit and the journal's phase write left it `prepared`.
|
||||
const committed = rewriteWslDriveUncState(profileState(), {
|
||||
distro: 'Ubuntu',
|
||||
mappedDrive: { letter: 'W', share: SHARE },
|
||||
repoIds: ['repo-a'],
|
||||
folderWorkspaceIds: ['notes']
|
||||
}).state
|
||||
seedProfile(committed)
|
||||
journal(overrides)
|
||||
const store = { id: 'terminal-history', run: vi.fn() }
|
||||
const [outcome] = await run(read, [store])
|
||||
expect(outcome).toMatchObject({ outcome: 'converted', respelledThisRun: true })
|
||||
expect(store.run).toHaveBeenCalledWith(new Map([[OLD_ID, NEW_ID]]))
|
||||
expect(readProfileProjectTransferState(PROFILE, root).state.repos[0].path).toBe(UNC)
|
||||
expect(listWslDriveUncConversions(root)).toEqual([
|
||||
expect.objectContaining({
|
||||
phase: 'profile-rewritten',
|
||||
rewrittenStores: ['terminal-history']
|
||||
})
|
||||
])
|
||||
}
|
||||
)
|
||||
|
||||
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('wakes the paused workspaces of a rolled-back plan once, as the window takes the report', () => {
|
||||
const wake = vi.fn()
|
||||
const outcomes = [
|
||||
{
|
||||
migrationId: 'conv-1',
|
||||
outcome: 'rolled-back' as const,
|
||||
detail: 'wsl_mapped_drive_remapped',
|
||||
mappedDrive: { letter: 'W', workspaceIds: [OLD_ID] }
|
||||
}
|
||||
]
|
||||
expect(takeWslMappedDriveRestartReport(wake, outcomes)).toEqual({
|
||||
moves: [],
|
||||
rolledBack: [{ reason: 'remapped', letter: 'W', workspaceIds: [OLD_ID] }]
|
||||
})
|
||||
expect(wake).toHaveBeenCalledWith(OLD_ID)
|
||||
expect(takeWslMappedDriveRestartReport(wake, outcomes)).toEqual({ moves: [], rolledBack: [] })
|
||||
expect(wake).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('reports no move due for a D1c conversion', () => {
|
||||
expect(
|
||||
wslMappedDriveMovesDueOf([
|
||||
{
|
||||
migrationId: 'conv-2',
|
||||
outcome: 'converted',
|
||||
repoIds: ['repo-b'],
|
||||
folderWorkspaceIds: [],
|
||||
distro: 'Ubuntu'
|
||||
}
|
||||
])
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,150 +0,0 @@
|
||||
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 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: [],
|
||||
// A folder has no runtime setting, so its share path alone would switch it to WSL.
|
||||
refused: [{ kind: 'folder-workspace', id: 'notes', reason: 'runtime-would-change' }]
|
||||
})
|
||||
})
|
||||
|
||||
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: [],
|
||||
// Saved, so the worktrees on the share keep running where they did.
|
||||
projects: [
|
||||
{ sourceRepoIds: ['app'], localWindowsRuntimePreference: { kind: 'windows-host' } }
|
||||
]
|
||||
},
|
||||
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 project whose single runtime could not keep every workspace where it ran', () => {
|
||||
const project = (id: string, preference?: { kind: 'wsl'; distro: string }) => ({
|
||||
sourceRepoIds: [id],
|
||||
localWindowsRuntimePreference: preference
|
||||
})
|
||||
const scope = collectWslMappedDriveScope(
|
||||
{
|
||||
repos: [
|
||||
repo('base-on-share', String.raw`W:\home\me\a`, {
|
||||
worktreeBasePath: String.raw`\\wsl.localhost\Ubuntu\home\me\trees`
|
||||
}),
|
||||
repo('linked-on-share', String.raw`W:\home\me\b`),
|
||||
repo('saved-choice', String.raw`W:\home\me\c`, {
|
||||
worktreeBasePath: String.raw`\\wsl.localhost\Ubuntu\home\me\trees`
|
||||
})
|
||||
],
|
||||
folderWorkspaces: [],
|
||||
projectGroups: [],
|
||||
projects: [
|
||||
project('base-on-share'),
|
||||
project('linked-on-share'),
|
||||
project('saved-choice', { kind: 'wsl', distro: 'Ubuntu' })
|
||||
],
|
||||
worktreeMeta: { [String.raw`linked-on-share::\\wsl.localhost\Ubuntu\home\me\Feature`]: {} }
|
||||
},
|
||||
DRIVE
|
||||
)
|
||||
// A saved choice already decides every workspace, so it carries over unchanged.
|
||||
expect(scope.repoIds).toEqual(['saved-choice'])
|
||||
expect(scope.refused).toEqual([
|
||||
{ kind: 'repo', id: 'base-on-share', reason: 'runtime-would-change' },
|
||||
{ kind: 'repo', id: 'linked-on-share', reason: 'runtime-would-change' }
|
||||
])
|
||||
})
|
||||
|
||||
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'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,142 +0,0 @@
|
||||
/**
|
||||
* 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 {
|
||||
isWslUncPath,
|
||||
parseWslUncPath,
|
||||
wslHostMovableDistroOfPath,
|
||||
wslUncPathToLinux
|
||||
} from '../../../shared/file-access/wsl-paths'
|
||||
import type { Project } from '../../../shared/project/project-types'
|
||||
import { getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem } from '../../../shared/worktree/id'
|
||||
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[]
|
||||
projects?: readonly Pick<Project, 'sourceRepoIds' | 'localWindowsRuntimePreference'>[]
|
||||
/** Saved worktree rows, keyed by worktree id, which names each worktree's folder. */
|
||||
worktreeMeta?: Readonly<Record<string, unknown>>
|
||||
}
|
||||
|
||||
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'
|
||||
: runtimeWouldChange(state, repo.id)
|
||||
? 'runtime-would-change'
|
||||
: 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)
|
||||
// A folder has no runtime setting: its share path alone would switch its terminals to WSL.
|
||||
const reason = !isLocal(workspace)
|
||||
? 'not-local'
|
||||
: (refusalOf([workspace.folderPath]) ??
|
||||
(claimedFolderPaths.has(key) ? 'duplicate-windows-project' : 'runtime-would-change'))
|
||||
if (reason) {
|
||||
scope.refused.push({ kind: 'folder-workspace', id: workspace.id, reason })
|
||||
} else {
|
||||
claimedFolderPaths.add(key)
|
||||
scope.folderWorkspaceIds.push(workspace.id)
|
||||
}
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
/**
|
||||
* A project with no saved runtime runs each workspace by its own path: a drive path on the global
|
||||
* default, a share path in the distro. The respelling pins the global default, which would move a
|
||||
* workspace already on the share out of the distro, so a project with one is refused instead.
|
||||
*/
|
||||
function runtimeWouldChange(state: WslMappedDriveScopeState, repoId: string): boolean {
|
||||
const project = state.projects?.find((entry) => entry.sourceRepoIds.includes(repoId))
|
||||
if (project?.localWindowsRuntimePreference !== undefined) {
|
||||
return false
|
||||
}
|
||||
const repoIds = new Set(project?.sourceRepoIds ?? [repoId])
|
||||
const paths = [
|
||||
...state.repos.filter((repo) => repoIds.has(repo.id)).flatMap(wslMoveRepoPaths),
|
||||
...Object.keys(state.worktreeMeta ?? {}).flatMap((worktreeId) => {
|
||||
const split = splitWorktreeIdForFilesystem(worktreeId)
|
||||
return split && repoIds.has(getRepoIdFromWorktreeId(worktreeId)) ? [split.worktreePath] : []
|
||||
})
|
||||
]
|
||||
return paths.some(isWslUncPath)
|
||||
}
|
||||
@@ -1,18 +1,15 @@
|
||||
import { ipcRenderer } from 'electron'
|
||||
import type {
|
||||
WslDriveUncConversionRequest,
|
||||
WslDriveUncConversionResult,
|
||||
WslMappedDriveRestartReport
|
||||
WslDriveUncConversionResult
|
||||
} 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, or a mapped-drive one to its share; main gates every call. */
|
||||
/** Converting a UNC Windows-drive project to its drive path; main gates every call. */
|
||||
export type WslDriveUncConversionApi = {
|
||||
/** Checks, pauses the project's terminals and restarts the app to convert. */
|
||||
convert: (request: WslDriveUncConversionRequest) => Promise<WslDriveUncConversionResult>
|
||||
/** This startup's mapped-drive plans, once per run: moves to open, rollbacks to report. */
|
||||
takeMappedDriveRestartReport: () => Promise<WslMappedDriveRestartReport>
|
||||
listPendingRendererRewrites: () => Promise<WslDriveUncPendingRendererRewrite[]>
|
||||
recordStoreRewritten: (request: {
|
||||
migrationId: string
|
||||
@@ -22,8 +19,6 @@ export type WslDriveUncConversionApi = {
|
||||
|
||||
export const wslDriveUncConversionApi: WslDriveUncConversionApi = {
|
||||
convert: (request) => ipcRenderer.invoke('wslDriveUnc:convert', request),
|
||||
takeMappedDriveRestartReport: () =>
|
||||
ipcRenderer.invoke('wslDriveUnc:takeMappedDriveRestartReport'),
|
||||
listPendingRendererRewrites: () => ipcRenderer.invoke('wslDriveUnc:listPendingRendererRewrites'),
|
||||
recordStoreRewritten: (request) => ipcRenderer.invoke('wslDriveUnc:recordStoreRewritten', request)
|
||||
}
|
||||
|
||||
+3
-3
@@ -54,7 +54,7 @@ export function RepositoryWindowsRuntimeSection({
|
||||
// A mapped-drive project keeps its runtime toggle; its move is on the project menu. Swapping the
|
||||
// toggle out once the drive lookup answers would make the setting jump.
|
||||
const resolvedMoveTarget = useWslMoveTargetForRepo(repo)
|
||||
const wslMoveTarget = resolvedMoveTarget?.mappedDrive ? null : resolvedMoveTarget
|
||||
const wslMoveDistro = resolvedMoveTarget?.viaMappedDrive ? null : resolvedMoveTarget?.distro
|
||||
// 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()
|
||||
@@ -82,8 +82,8 @@ export function RepositoryWindowsRuntimeSection({
|
||||
className="space-y-3"
|
||||
forceVisible={forceVisible || matchesSettingsSearch(searchQuery, searchEntries)}
|
||||
>
|
||||
{wslMoveTarget && repo ? (
|
||||
<WslMoveRuntimeRow target={wslMoveTarget} repoId={repo.id} name={repoDisplayName} />
|
||||
{wslMoveDistro && repo ? (
|
||||
<WslMoveRuntimeRow distro={wslMoveDistro} repoId={repo.id} />
|
||||
) : (
|
||||
<ProjectWindowsRuntimeSetting
|
||||
project={project}
|
||||
|
||||
@@ -2,13 +2,11 @@ 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'
|
||||
@@ -26,7 +24,6 @@ const offer = {
|
||||
afterEach(() => {
|
||||
toastError.mockReset()
|
||||
openWslMoveDialogFor.mockReset()
|
||||
openWslMappedDriveMove.mockReset()
|
||||
resolveWslMappedDrivePath.mockReset()
|
||||
resolveWslMappedDrivePath.mockResolvedValue(null)
|
||||
useAppStore.setState(initialState, true)
|
||||
@@ -42,25 +39,17 @@ describe('moveWslHostOfferProject', () => {
|
||||
expect(toastError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reopens a project the add found saved as W: at its share path before the move', async () => {
|
||||
it('opens the move for a project the add found saved as W:, as it is saved', async () => {
|
||||
// Registration matches by real path, so the share spelling resolves to the saved W: row.
|
||||
resolveWslMappedDrivePath.mockResolvedValue('\\\\wsl.localhost\\Ubuntu')
|
||||
moveWslHostOfferProject(offer, {
|
||||
status: 'completed',
|
||||
repo: { id: 'repo-w', path: 'W:\\home\\u\\repo', displayName: 'repo' }
|
||||
repo: { id: 'repo-w', path: 'W:\\home\\u\\repo' }
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(openWslMappedDriveMove).toHaveBeenCalledWith({
|
||||
distro: 'Ubuntu',
|
||||
letter: 'W',
|
||||
share: '\\\\wsl.localhost\\Ubuntu',
|
||||
sharePath: offer.sharePath,
|
||||
ref: { kind: 'repo', id: 'repo-w' },
|
||||
name: 'repo'
|
||||
})
|
||||
expect(openWslMoveDialogFor).toHaveBeenCalledWith('Ubuntu', { kind: 'repo', id: 'repo-w' })
|
||||
)
|
||||
expect(resolveWslMappedDrivePath).toHaveBeenCalledWith('W:\\')
|
||||
expect(openWslMoveDialogFor).not.toHaveBeenCalled()
|
||||
expect(toastError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -72,7 +61,7 @@ describe('moveWslHostOfferProject', () => {
|
||||
await vi.waitFor(() =>
|
||||
expect(toastError).toHaveBeenCalledWith(expect.stringContaining('W:\\home\\u\\repo'))
|
||||
)
|
||||
expect(openWslMappedDriveMove).not.toHaveBeenCalled()
|
||||
expect(openWslMoveDialogFor).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to the share spelling when the add names no repo', () => {
|
||||
|
||||
@@ -12,9 +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 { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-drive-unc-respelling'
|
||||
import { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { wslMoveDistroOfPath } from '../wsl-move/wsl-move-scope-rows'
|
||||
import type { WslHostOffer } from './wsl-host-offer-actions'
|
||||
|
||||
@@ -58,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; name: string } | null {
|
||||
function addedRepoOf(added: unknown): { id: string; path: string } | null {
|
||||
if (typeof added !== 'object' || added === null || !('repo' in added)) {
|
||||
return null
|
||||
}
|
||||
@@ -69,41 +68,20 @@ function addedRepoOf(added: unknown): { id: string; path: string; name: string }
|
||||
typeof repo.id === 'string' &&
|
||||
'path' in repo &&
|
||||
typeof repo.path === 'string'
|
||||
? {
|
||||
id: repo.id,
|
||||
path: repo.path,
|
||||
name:
|
||||
'displayName' in repo && typeof repo.displayName === 'string'
|
||||
? repo.displayName
|
||||
: repo.path
|
||||
}
|
||||
? { id: repo.id, path: repo.path }
|
||||
: 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.
|
||||
*/
|
||||
/** A project saved as `W:\…` moves as it is when its drive still maps into the offered distro. */
|
||||
async function moveSavedUnderMappedDrive(
|
||||
offer: WslHostOffer,
|
||||
repo: { id: string; path: string; name: string }
|
||||
repo: { id: string; path: string }
|
||||
): Promise<void> {
|
||||
const letter = repo.path[0]?.toUpperCase() ?? ''
|
||||
const share = /^[A-Z]$/.test(letter) ? await resolveWslMappedDrivePath(`${letter}:\\`) : null
|
||||
const sharePath = share ? wslMappedDrivePathToShare(repo.path, { letter, share }) : null
|
||||
if (
|
||||
share &&
|
||||
sharePath &&
|
||||
wslMoveDistroOfPath(sharePath)?.toLowerCase() === offer.distro.toLowerCase()
|
||||
) {
|
||||
openWslMappedDriveMove({
|
||||
distro: offer.distro,
|
||||
letter,
|
||||
share,
|
||||
sharePath,
|
||||
ref: { kind: 'repo', id: repo.id },
|
||||
name: repo.name
|
||||
})
|
||||
if (sharePath && wslMoveDistroOfPath(sharePath)?.toLowerCase() === offer.distro.toLowerCase()) {
|
||||
openWslMoveDialogFor(offer.distro, { kind: 'repo', id: repo.id })
|
||||
return
|
||||
}
|
||||
toast.error(
|
||||
@@ -115,9 +93,13 @@ async function moveSavedUnderMappedDrive(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function moveWslHostOfferProject(offer: WslHostOffer, added?: unknown): void {
|
||||
const repo = addedRepoOf(added)
|
||||
// The same folder was already saved under another spelling (`W:\…`): reopen it at its share first.
|
||||
// The same folder was already saved under another spelling (`W:\…`).
|
||||
if (repo && wslMoveDistroOfPath(repo.path)?.toLowerCase() !== offer.distro.toLowerCase()) {
|
||||
void moveSavedUnderMappedDrive(offer, repo)
|
||||
return
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** Plain-language copy for why a UNC Windows-drive project can't be converted right now. */
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type {
|
||||
WslDriveUncConversionBlocker,
|
||||
@@ -11,18 +8,11 @@ import { wslDriveProjectBlockerMessage } from './wsl-drive-project-copy'
|
||||
|
||||
export function wslDriveUncConversionMessages(
|
||||
result: Exclude<WslDriveUncConversionResult, { outcome: 'restarting' }>,
|
||||
/** Where the project would reopen: its drive path, or its share path for a mapped drive. */
|
||||
drivePath: string,
|
||||
mappedDriveLetter?: string
|
||||
drivePath: string
|
||||
): string[] {
|
||||
switch (result.outcome) {
|
||||
case 'refused':
|
||||
return result.blockers.map((blocker) =>
|
||||
mappedDriveLetter
|
||||
? (mappedDriveBlockerMessage(blocker, mappedDriveLetter) ??
|
||||
blockerMessage(blocker, drivePath))
|
||||
: blockerMessage(blocker, drivePath)
|
||||
)
|
||||
return result.blockers.map((blocker) => blockerMessage(blocker, drivePath))
|
||||
case 'terminals-blocked':
|
||||
return [
|
||||
translate(
|
||||
@@ -40,59 +30,8 @@ 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-unverifiable') {
|
||||
return translate(
|
||||
'wslDriveUnc.mappedDrive.unverifiable',
|
||||
'Orca couldn’t check where drive {{letter}}: points just now, so nothing changed. Try again in a moment.',
|
||||
{ letter }
|
||||
)
|
||||
}
|
||||
if (blocker.kind === 'drive-not-mapped') {
|
||||
return translate(
|
||||
'wslDriveUnc.mappedDrive.notMapped',
|
||||
'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-unverifiable':
|
||||
return translate(
|
||||
'wslDriveUnc.blocker.driveUnverifiable',
|
||||
'Orca couldn’t check where that drive points just now, so nothing changed. Try again in a moment.'
|
||||
)
|
||||
case 'drive-not-mapped':
|
||||
return translate(
|
||||
'wslDriveUnc.blocker.driveNotMapped',
|
||||
'That drive no longer points into this distro, so nothing changed.'
|
||||
)
|
||||
case 'conversion-pending':
|
||||
return translate(
|
||||
'wslDriveUnc.blocker.pending',
|
||||
@@ -143,17 +82,6 @@ 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 'runtime-would-change':
|
||||
return translate(
|
||||
'wslDriveUnc.blocker.runtimeWouldChange',
|
||||
'Reopening this at {{drivePath}} would change where its terminals and Git run, so nothing changed. Choose its Project runtime first, or add the folder again at {{drivePath}}.',
|
||||
{ drivePath }
|
||||
)
|
||||
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(
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
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,
|
||||
wslMappedDriveMoveBusy
|
||||
} 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 = wslMappedDriveMoveBusy(step)
|
||||
const confirmLabel =
|
||||
step.kind === 'converting'
|
||||
? t('wslMove.mappedDrive.pausing', 'Pausing terminals…')
|
||||
: step.kind === 'restarting'
|
||||
? t('wslMove.mappedDrive.restartingLabel', 'Restarting…')
|
||||
: step.kind === 'problem'
|
||||
? t('wslMove.mappedDrive.retry', 'Try again')
|
||||
: t('wslMove.mappedDrive.confirm', 'Restart and continue')
|
||||
return (
|
||||
<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-destructive">
|
||||
{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>
|
||||
{/* Fixed width: the label changes with each stage, and the footer must not shift. */}
|
||||
<Button
|
||||
type="button"
|
||||
className="w-48"
|
||||
disabled={converting}
|
||||
onClick={() => void confirmWslMappedDriveMove()}
|
||||
>
|
||||
{converting ? <LoadingSpinner className="size-4" /> : null}
|
||||
{confirmLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -33,9 +33,7 @@ import {
|
||||
import { adoptWslMoveProgress } from './wsl-move-run-adoption'
|
||||
import { closeWslMoveDialog, reloadAfterWslMove } from './wsl-move-dialog-close'
|
||||
import { RecoverableRenderErrorBoundary } from '../error-boundaries/RecoverableRenderErrorBoundary'
|
||||
import { useWslHostsAcceptNewWork, useWslHostsEnabled } from '../sidebar/use-wsl-hosts-enabled'
|
||||
import { WslMappedDriveMoveDialog } from './WslMappedDriveMoveDialog'
|
||||
import { openWslMappedDriveMovesDue } from './wsl-mapped-drive-move-store'
|
||||
import { useWslHostsEnabled } from '../sidebar/use-wsl-hosts-enabled'
|
||||
import { useConfirmationDialog } from '../confirmation-dialog-context'
|
||||
import { useWslMoveQuitGuard } from './use-wsl-move-quit-guard'
|
||||
import { WslMovePreviewBody, wslMoveNotMovingLines } from './WslMovePreviewBody'
|
||||
@@ -116,29 +114,11 @@ export function WslMoveDialogHost(): React.JSX.Element | null {
|
||||
: undefined,
|
||||
[enabled]
|
||||
)
|
||||
// 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>
|
||||
</>
|
||||
)
|
||||
return open ? (
|
||||
<RecoverableRenderErrorBoundary boundaryId="modal.wsl-move" surface="modal" compact>
|
||||
<WslMoveDialog />
|
||||
</RecoverableRenderErrorBoundary>
|
||||
) : null
|
||||
}
|
||||
|
||||
function WslMoveDialog(): React.JSX.Element | null {
|
||||
|
||||
@@ -13,9 +13,9 @@ import type {
|
||||
import {
|
||||
wslMoveBrowserLoginsNotCarried,
|
||||
wslMoveChatsStayCopy,
|
||||
wslMoveRefusalMessage,
|
||||
wslMoveScopeRefusalReason
|
||||
wslMoveRefusalMessage
|
||||
} from './wsl-move-copy'
|
||||
import { wslMoveScopeRefusalReason } from './wsl-move-scope-refusal-copy'
|
||||
import type { WslMoveCounts, WslMoveProjectRow } from './wsl-move-scope-rows'
|
||||
import { WslMoveBlockerList, type WslMoveBlockerView } from './WslMoveBlockerList'
|
||||
|
||||
|
||||
@@ -7,24 +7,25 @@ import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-rec
|
||||
import { resolveFolderWorkspaceHost } from '../../../../shared/folder-workspaces/folder-workspace-execution-host'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import { useWslMoveTargetForPath, useWslMoveTargetForRepo } from './wsl-move-entry'
|
||||
import { openWslMoveForProject } from './wsl-mapped-drive-move-store'
|
||||
import {
|
||||
openWslMoveDialogFor,
|
||||
useWslMoveTargetForPath,
|
||||
useWslMoveTargetForRepo
|
||||
} from './wsl-move-entry'
|
||||
|
||||
function MoveItem({
|
||||
target,
|
||||
project,
|
||||
name
|
||||
project
|
||||
}: {
|
||||
target: ReturnType<typeof useWslMoveTargetForRepo>
|
||||
project: WslMoveRowRef
|
||||
name: string
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
if (!target) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<DropdownMenuItem onSelect={() => openWslMoveForProject(target, project, name)}>
|
||||
<DropdownMenuItem onSelect={() => openWslMoveDialogFor(target.distro, project)}>
|
||||
<FolderInput className="size-3.5" />
|
||||
{t('wslMove.entry.projectMenu', 'Move to {{distro}} host…', { distro: target.distro })}
|
||||
</DropdownMenuItem>
|
||||
@@ -34,9 +35,7 @@ function MoveItem({
|
||||
/** "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} />
|
||||
)
|
||||
return <MoveItem target={target} project={{ kind: 'repo', id: repo.id }} />
|
||||
}
|
||||
|
||||
/** The same for a local folder workspace, from its row's menu. */
|
||||
@@ -57,8 +56,5 @@ export function WslMoveFolderWorkspaceMenuItem({
|
||||
: undefined
|
||||
})
|
||||
const target = useWslMoveTargetForPath(folder?.folderPath, !!folder)
|
||||
// A folder has no runtime setting to keep, so main refuses to reopen one from a mapped drive.
|
||||
return folder && !target?.mappedDrive ? (
|
||||
<MoveItem target={target} project={{ kind: 'folder', id: folder.id }} name={folder.name} />
|
||||
) : null
|
||||
return folder ? <MoveItem target={target} project={{ kind: 'folder', id: folder.id }} /> : null
|
||||
}
|
||||
|
||||
@@ -2,21 +2,17 @@ import React from 'react'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { SettingsRow } from '../settings/form-controls/SettingsFormControls'
|
||||
import type { WslMoveTarget } from './wsl-move-entry'
|
||||
import { openWslMoveForProject } from './wsl-mapped-drive-move-store'
|
||||
import { openWslMoveDialogFor } from './wsl-move-entry'
|
||||
|
||||
/** The project runtime setting of a WSL project whose distro has a host: a move, not a toggle. */
|
||||
export function WslMoveRuntimeRow({
|
||||
target,
|
||||
repoId,
|
||||
name
|
||||
distro,
|
||||
repoId
|
||||
}: {
|
||||
target: WslMoveTarget
|
||||
distro: string
|
||||
repoId: string
|
||||
name: string
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const { distro } = target
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t('wslMove.runtime.label', 'Project runtime')}
|
||||
@@ -30,7 +26,7 @@ export function WslMoveRuntimeRow({
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => openWslMoveForProject(target, { kind: 'repo', id: repoId }, name)}
|
||||
onClick={() => openWslMoveDialogFor(distro, { kind: 'repo', id: repoId })}
|
||||
>
|
||||
{t('wslMove.runtime.move', 'Move project')}
|
||||
</Button>
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: 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 = String.raw`\\wsl.localhost\Ubuntu`
|
||||
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 takeMappedDriveRestartReport = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('window', { api: { wslDriveUnc: { convert, takeMappedDriveRestartReport } } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
convert.mockReset()
|
||||
takeMappedDriveRestartReport.mockReset()
|
||||
toast.error.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, [host])).toEqual({
|
||||
distro: 'Ubuntu',
|
||||
mappedDrive: { letter: 'W', share: SHARE, sharePath: SHARE_PATH }
|
||||
})
|
||||
})
|
||||
|
||||
it('offers nothing without a host, or for a share into a Windows drive', () => {
|
||||
expect(wslMoveTargetOfPath(String.raw`W:\home\u\repo`, SHARE, [])).toBeNull()
|
||||
expect(wslMoveTargetOfPath(String.raw`W:\mnt\c\src`, SHARE, [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', share: SHARE, 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',
|
||||
// What the window showed, so main refuses a drive remapped since.
|
||||
mappedDriveShare: SHARE
|
||||
})
|
||||
expect(useWslMappedDriveMoveStore.getState().step).toEqual({ kind: 'restarting' })
|
||||
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('says to try again when the drive could not be checked in time', async () => {
|
||||
convert.mockResolvedValue({ outcome: 'refused', blockers: [{ kind: 'drive-unverifiable' }] })
|
||||
openWslMoveForProject(target, { kind: 'repo', id: 'repo-w' }, 'repo')
|
||||
await confirmWslMappedDriveMove()
|
||||
expect(useWslMappedDriveMoveStore.getState().step).toEqual({
|
||||
kind: 'problem',
|
||||
messages: [expect.stringContaining('Try again')]
|
||||
})
|
||||
})
|
||||
|
||||
it('tells the user a restart that changed nothing, and opens no move', async () => {
|
||||
takeMappedDriveRestartReport.mockResolvedValue({
|
||||
moves: [],
|
||||
rolledBack: [{ reason: 'remapped', letter: 'W', workspaceIds: ['repo-w::W:\\x'] }]
|
||||
})
|
||||
await openWslMappedDriveMovesDue()
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('now points somewhere else'))
|
||||
expect(openWslMoveDialog).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the move with every reopened project checked once the restart is done', async () => {
|
||||
takeMappedDriveRestartReport.mockResolvedValue({
|
||||
moves: [
|
||||
{ distro: 'Ubuntu', repoIds: ['repo-w', 'repo-nested'], folderWorkspaceIds: ['notes'] }
|
||||
],
|
||||
rolledBack: []
|
||||
})
|
||||
await openWslMappedDriveMovesDue()
|
||||
expect(openWslMoveDialog).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
distro: 'Ubuntu',
|
||||
only: [
|
||||
{ kind: 'repo', id: 'repo-w' },
|
||||
{ kind: 'repo', id: 'repo-nested' },
|
||||
{ kind: 'folder', id: 'notes' }
|
||||
]
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,171 +0,0 @@
|
||||
/**
|
||||
* 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,
|
||||
WslMappedDriveRestartReport,
|
||||
WslMappedDriveRollback
|
||||
} 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, and the share it showed. */
|
||||
letter: string
|
||||
share: string
|
||||
/** Where the project reopens: its folder on the distro share. */
|
||||
sharePath: string
|
||||
ref: WslMoveRowRef
|
||||
name: string
|
||||
}
|
||||
|
||||
type Step =
|
||||
| { kind: 'review' }
|
||||
/** Main is checking the drive and putting the project's terminals to sleep. */
|
||||
| { kind: 'converting' }
|
||||
/** Main accepted; the app is about to restart. */
|
||||
| { kind: 'restarting' }
|
||||
| { kind: 'problem'; messages: string[] }
|
||||
|
||||
export function wslMappedDriveMoveBusy(step: Step): boolean {
|
||||
return step.kind === 'converting' || step.kind === 'restarting'
|
||||
}
|
||||
|
||||
type State = { request: WslMappedDriveMoveRequest | null; step: Step }
|
||||
|
||||
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 (!wslMappedDriveMoveBusy(useWslMappedDriveMoveStore.getState().step)) {
|
||||
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,
|
||||
mappedDriveShare: request.share
|
||||
})
|
||||
} 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 until the window goes away.
|
||||
useWslMappedDriveMoveStore.setState({ step: { kind: 'restarting' } })
|
||||
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: the move for the projects it reopened, with only those checked; or, for a
|
||||
* plan it rolled back, why. Main wakes the terminals that plan paused as it hands this over.
|
||||
*/
|
||||
export async function openWslMappedDriveMovesDue(): Promise<void> {
|
||||
let report: WslMappedDriveRestartReport
|
||||
try {
|
||||
report = await window.api.wslDriveUnc.takeMappedDriveRestartReport()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const rollback of report.rolledBack) {
|
||||
toast.error(rollbackMessage(rollback))
|
||||
}
|
||||
// One dialog at a time; a second distro's projects are listed on its host row.
|
||||
const first = report.moves[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)
|
||||
}
|
||||
|
||||
function rollbackMessage(rollback: WslMappedDriveRollback): string {
|
||||
const { letter } = rollback
|
||||
switch (rollback.reason) {
|
||||
case 'remapped':
|
||||
return translate(
|
||||
'wslMove.mappedDrive.rolledBack.remapped',
|
||||
'Orca didn’t reopen your project: drive {{letter}}: now points somewhere else. Nothing changed.',
|
||||
{ letter }
|
||||
)
|
||||
case 'unverifiable':
|
||||
return translate(
|
||||
'wslMove.mappedDrive.rolledBack.unverifiable',
|
||||
'Orca didn’t reopen your project: it couldn’t check drive {{letter}}: in time. Nothing changed; try the move again.',
|
||||
{ letter }
|
||||
)
|
||||
case 'expired':
|
||||
return translate(
|
||||
'wslMove.mappedDrive.rolledBack.expired',
|
||||
'Orca didn’t reopen your project from drive {{letter}}: the request was too old. Nothing changed; try the move again.',
|
||||
{ letter }
|
||||
)
|
||||
case 'failed':
|
||||
return translate(
|
||||
'wslMove.mappedDrive.rolledBack.failed',
|
||||
'Orca couldn’t reopen your project from drive {{letter}}:. Nothing changed; try the move again.',
|
||||
{ letter }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
/** Plain-language copy for the WSL move dialog: no "manifest", "orcad" or "UNC". */
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
WslMoveBlockerKind,
|
||||
WslMoveProgressStep,
|
||||
WslMoveRefusal
|
||||
import {
|
||||
WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL,
|
||||
type WslMoveBlockerKind,
|
||||
type WslMoveProgressStep,
|
||||
type WslMoveRefusal
|
||||
} from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
|
||||
/** Decision C, verbatim from the design. */
|
||||
@@ -40,6 +41,12 @@ export function wslMoveRefusalMessage(
|
||||
if (refusal.detail === 'preview-failed') {
|
||||
return t('wslMove.refusal.previewFailed', 'Orca could not check these projects. Try again.')
|
||||
}
|
||||
if (refusal.detail === WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL) {
|
||||
return t(
|
||||
'wslMove.refusal.mappedDriveUnverifiable',
|
||||
'Orca could not check a drive letter some projects are saved on. Make sure the drive is connected, then try again.'
|
||||
)
|
||||
}
|
||||
if (refusal.detail === 'start-failed') {
|
||||
return t(
|
||||
'wslMove.refusal.startFailed',
|
||||
@@ -253,25 +260,6 @@ export function wslMoveBlockerHint(kind: WslMoveBlockerKind, t: Translate = tran
|
||||
}
|
||||
}
|
||||
|
||||
export function wslMoveScopeRefusalReason(reason: string, t: Translate = translate): string {
|
||||
switch (reason) {
|
||||
case 'windows-drive':
|
||||
return t(
|
||||
'wslMove.scopeRefused.windowsDrive',
|
||||
'Its folder is on a Windows drive, so it stays on this computer.'
|
||||
)
|
||||
case 'mixed-locations':
|
||||
return t(
|
||||
'wslMove.scopeRefused.mixedLocations',
|
||||
'Some of its folders are outside this distro, so it stays on this computer.'
|
||||
)
|
||||
case 'not-local':
|
||||
return t('wslMove.scopeRefused.notLocal', 'It already runs on another host.')
|
||||
default:
|
||||
return t('wslMove.scopeRefused.other', 'It cannot move.')
|
||||
}
|
||||
}
|
||||
|
||||
/** 7f's reasons the host's browser starts signed out; an unknown one reads generically. */
|
||||
export function wslMoveBrowserLoginsNotCopied(reason: string, t: Translate = translate): string {
|
||||
switch (reason) {
|
||||
|
||||
@@ -241,6 +241,9 @@ export async function startWslMove(): Promise<void> {
|
||||
return
|
||||
}
|
||||
const { distro, selected } = dialog
|
||||
// Main moves only if the drives still map where this preview read them.
|
||||
const previewed = dialog.preview?.outcome === 'ready' ? dialog.preview : null
|
||||
const mappedDrives = previewed?.mappedDrives ?? []
|
||||
++previewToken
|
||||
setDialog({ stage: 'running', distro, selected, progress: null, cancel: 'idle' })
|
||||
const unsubscribe = window.api.wslMove.onProgress((progress) => {
|
||||
@@ -253,7 +256,8 @@ export async function startWslMove(): Promise<void> {
|
||||
try {
|
||||
result = await window.api.wslMove.start({
|
||||
...requestOf(distro, selected),
|
||||
sleptPanes: collectWslMoveSleptPaneBindings(useAppStore.getState())
|
||||
sleptPanes: collectWslMoveSleptPaneBindings(useAppStore.getState()),
|
||||
mappedDrives
|
||||
})
|
||||
} catch (error) {
|
||||
// The IPC itself failed; main's own failures arrive as results.
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
LOCAL_EXECUTION_HOST_ID
|
||||
} from '../../../../shared/execution-host/execution-host'
|
||||
import { wslHostMovableDistroOfPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-drive-unc-respelling'
|
||||
import { wslMappedDrivePathToShare } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { Repo } from '../../../../shared/repository/repo-types'
|
||||
import type { WslMoveRowRef } from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import {
|
||||
@@ -43,11 +43,8 @@ export function openWslMoveDialogFor(
|
||||
/** 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.
|
||||
* `share` is the drive's own share, `sharePath` the project's folder on it.
|
||||
*/
|
||||
mappedDrive?: { letter: string; share: string; sharePath: string }
|
||||
/** Saved under a drive letter mapped to the distro's share; main reads that mapping itself. */
|
||||
viaMappedDrive?: boolean
|
||||
}
|
||||
|
||||
const DRIVE_PATH = /^[A-Za-z]:[\\/]/
|
||||
@@ -116,9 +113,7 @@ export function wslMoveTargetOfPath(
|
||||
if (!host) {
|
||||
return null
|
||||
}
|
||||
return sharePath && share
|
||||
? { distro: host.distro, mappedDrive: { letter, share, sharePath } }
|
||||
: { distro: host.distro }
|
||||
return sharePath ? { distro: host.distro, viaMappedDrive: true } : { distro: host.distro }
|
||||
}
|
||||
|
||||
/** The distro host a local WSL repo can move to, or null where no move is offered. */
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/** Why a project of the distro is listed under "Not moving", in the move dialog's words. */
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
|
||||
export function wslMoveScopeRefusalReason(reason: string, t: Translate = translate): string {
|
||||
switch (reason) {
|
||||
case 'windows-drive':
|
||||
return t(
|
||||
'wslMove.scopeRefused.windowsDrive',
|
||||
'Its folder is on a Windows drive, so it stays on this computer.'
|
||||
)
|
||||
case 'mixed-locations':
|
||||
return t(
|
||||
'wslMove.scopeRefused.mixedLocations',
|
||||
'Some of its folders are outside this distro, so it stays on this computer.'
|
||||
)
|
||||
case 'not-local':
|
||||
return t('wslMove.scopeRefused.notLocal', 'It already runs on another host.')
|
||||
case 'windows-git-worktrees':
|
||||
return t(
|
||||
'wslMove.scopeRefused.windowsGitWorktrees',
|
||||
'Git for Windows created some of its worktrees, and Git on the WSL host can’t use them. Remove those worktrees, then move it.'
|
||||
)
|
||||
default:
|
||||
return t('wslMove.scopeRefused.other', 'It cannot move.')
|
||||
}
|
||||
}
|
||||
@@ -24772,7 +24772,8 @@
|
||||
"pauseFailed": "Orca could not pause the terminals in these projects, so nothing was moved. Paused terminals start again when you open them. Try again.",
|
||||
"scopeChanged": "A project changed while the move was getting ready, so nothing was moved. Check the projects and try again.",
|
||||
"cancelled": "Move cancelled. Nothing was moved.",
|
||||
"finishedEarlierMove": "Orca first finished an earlier move into {{distro}}. Reload the window, then start this move again."
|
||||
"finishedEarlierMove": "Orca first finished an earlier move into {{distro}}. Reload the window, then start this move again.",
|
||||
"mappedDriveUnverifiable": "Orca could not check a drive letter some projects are saved on. Make sure the drive is connected, then try again."
|
||||
},
|
||||
"step": {
|
||||
"preparing": "Preparing",
|
||||
@@ -24810,7 +24811,8 @@
|
||||
"windowsDrive": "Its folder is on a Windows drive, so it stays on this computer.",
|
||||
"mixedLocations": "Some of its folders are outside this distro, so it stays on this computer.",
|
||||
"notLocal": "It already runs on another host.",
|
||||
"other": "It cannot move."
|
||||
"other": "It cannot move.",
|
||||
"windowsGitWorktrees": "Git for Windows created some of its worktrees, and Git on the WSL host can’t use them. Remove those worktrees, then move it."
|
||||
},
|
||||
"reloadToast": {
|
||||
"title": "Reload to finish the move"
|
||||
@@ -24833,23 +24835,6 @@
|
||||
"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…",
|
||||
"pausing": "Pausing terminals…",
|
||||
"restartingLabel": "Restarting…",
|
||||
"rolledBack": {
|
||||
"remapped": "Orca didn’t reopen your project: drive {{letter}}: now points somewhere else. Nothing changed.",
|
||||
"unverifiable": "Orca didn’t reopen your project: it couldn’t check drive {{letter}}: in time. Nothing changed; try the move again.",
|
||||
"expired": "Orca didn’t reopen your project from drive {{letter}}: the request was too old. Nothing changed; try the move again.",
|
||||
"failed": "Orca couldn’t reopen your project from drive {{letter}}:. Nothing changed; try the move again."
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboarding": {
|
||||
@@ -25275,17 +25260,7 @@
|
||||
"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.",
|
||||
"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.",
|
||||
"driveUnverifiable": "Orca couldn’t check where that drive points just now, so nothing changed. Try again in a moment.",
|
||||
"runtimeWouldChange": "Reopening this at {{drivePath}} would change where its terminals and Git run, so nothing changed. Choose its Project runtime first, or add the folder again at {{drivePath}}."
|
||||
},
|
||||
"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.",
|
||||
"unverifiable": "Orca couldn’t check where drive {{letter}}: points just now, so nothing changed. Try again in a moment."
|
||||
"projectSplit": "This project also holds a repository that isn’t converting, so nothing changed."
|
||||
}
|
||||
},
|
||||
"runtime": {
|
||||
|
||||
@@ -170,7 +170,6 @@ 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: [] }),
|
||||
takeMappedDriveRestartReport: () => Promise.resolve({ moves: [], rolledBack: [] }),
|
||||
listPendingRendererRewrites: () => Promise.resolve([]),
|
||||
recordStoreRewritten: () => Promise.resolve({ recorded: false, reason: 'gated-off' })
|
||||
},
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
/**
|
||||
* Converting a UNC Windows-drive project to its drive path (D1c), or a mapped-drive project to its
|
||||
* share path; desktop-only IPC.
|
||||
*/
|
||||
/** Converting a UNC Windows-drive project to its drive path (D1c); desktop-only IPC. */
|
||||
import type { WslMoveBlocker } from './wsl-move-driver-types'
|
||||
|
||||
export type WslDriveUncConversionRequest = {
|
||||
@@ -9,13 +6,6 @@ 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
|
||||
/** The share the window showed for that drive; a drive remapped since is refused. */
|
||||
mappedDriveShare?: string
|
||||
}
|
||||
|
||||
export type WslDriveUncConversionBlocker =
|
||||
@@ -32,13 +22,7 @@ export type WslDriveUncConversionBlocker =
|
||||
| 'duplicate-windows-project'
|
||||
| 'overlaps-refused-project'
|
||||
| 'not-windows-drive-mount'
|
||||
| 'windows-drive-folder'
|
||||
| 'runtime-would-change'
|
||||
}
|
||||
/** The mapped drive no longer points where the window showed (`mappedDriveShare`). */
|
||||
| { kind: 'drive-not-mapped' }
|
||||
/** Windows didn't say in time where the drive points (a distro still starting, say). */
|
||||
| { kind: 'drive-unverifiable' }
|
||||
| { kind: 'windows-git-missing' }
|
||||
/** WSL Git made these worktrees; their links are Linux paths Windows Git can't follow. */
|
||||
| { kind: 'wsl-authored-worktrees'; repoId: string; paths: string[] }
|
||||
@@ -52,27 +36,6 @@ 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[]
|
||||
}
|
||||
|
||||
/** A mapped-drive plan the restart rolled back: nothing changed, and its panes were asleep. */
|
||||
export type WslMappedDriveRollback = {
|
||||
reason: 'remapped' | 'unverifiable' | 'expired' | 'failed'
|
||||
letter: string
|
||||
/** The workspaces whose terminals the confirm put to sleep. */
|
||||
workspaceIds: string[]
|
||||
}
|
||||
|
||||
/** What this startup did with mapped-drive plans, handed to the window once. */
|
||||
export type WslMappedDriveRestartReport = {
|
||||
moves: WslMappedDriveMoveDue[]
|
||||
rolledBack: WslMappedDriveRollback[]
|
||||
}
|
||||
|
||||
export type WslDriveUncConversionResult =
|
||||
/** Journaled with the panes asleep; the app restarts and converts before the window opens. */
|
||||
| { outcome: 'restarting'; migrationId: string }
|
||||
|
||||
@@ -6,17 +6,14 @@
|
||||
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 { wslDriveUncRespelling, type WslMappedDrive } from './wsl-drive-unc-respelling'
|
||||
import { splitWorktreeIdForFilesystem } from '../worktree/id'
|
||||
import { wslUncDrivePathToWindows } from '../file-access/wsl-paths'
|
||||
|
||||
/** 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 saved before the conversion. */
|
||||
/** The converted projects' folders, as UNC paths. */
|
||||
rootPaths: string[]
|
||||
/** Renderer stores still to record. */
|
||||
storeIds: string[]
|
||||
@@ -24,44 +21,37 @@ export type WslDriveUncPendingRendererRewrite = {
|
||||
|
||||
export type WslDriveUncRendererKeys = {
|
||||
worktreeId: (worktreeId: string) => string | null
|
||||
/** A path inside a converted folder, in its converted form; null for any other path. */
|
||||
/** A path inside a converted folder, in its drive form; null for any other path. */
|
||||
path: (path: string) => string | null
|
||||
/** A comparison-form key inside a converted folder, re-keyed in comparison form; else null. */
|
||||
comparisonKey: (key: string) => string | null
|
||||
}
|
||||
|
||||
export function wslDriveUncRendererKeys(
|
||||
conversion: Pick<
|
||||
WslDriveUncPendingRendererRewrite,
|
||||
'distro' | 'mappedDrive' | 'worktreeIds' | 'rootPaths'
|
||||
>
|
||||
conversion: Pick<WslDriveUncPendingRendererRewrite, 'distro' | 'worktreeIds' | 'rootPaths'>
|
||||
): WslDriveUncRendererKeys {
|
||||
const ids = new Map(conversion.worktreeIds)
|
||||
// Each converted worktree's own folder too: its exact case restores a folded quick-open root.
|
||||
const worktreeRoots = conversion.worktreeIds.flatMap(
|
||||
([oldId]) => splitWorktreeIdForFilesystem(oldId)?.worktreePath ?? []
|
||||
)
|
||||
const respelling = wslDriveUncRespelling(conversion, [...conversion.rootPaths, ...worktreeRoots])
|
||||
const { distro } = conversion
|
||||
const roots = conversion.rootPaths.flatMap((root) => {
|
||||
const converted = respelling.path(root)
|
||||
return converted ? [normalizeRuntimePathForComparison(converted)] : []
|
||||
const drive = wslUncDrivePathToWindows(root, distro)
|
||||
return drive ? [normalizeRuntimePathForComparison(drive)] : []
|
||||
})
|
||||
const comparisonForm = /^\/\/wsl\/([^/]+)(\/[\s\S]*)?$/
|
||||
const path = (value: string): string | null => {
|
||||
const converted = respelling.path(value)
|
||||
if (!converted) {
|
||||
// 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) {
|
||||
return null
|
||||
}
|
||||
const comparable = normalizeRuntimePathForComparison(converted)
|
||||
const comparable = normalizeRuntimePathForComparison(drive)
|
||||
const inRoot = roots.some(
|
||||
(root) => comparable === root || comparable.startsWith(root.endsWith('/') ? root : `${root}/`)
|
||||
)
|
||||
return inRoot ? converted : null
|
||||
}
|
||||
return {
|
||||
worktreeId: (worktreeId) => ids.get(worktreeId) ?? null,
|
||||
path,
|
||||
comparisonKey: respelling.comparisonForm
|
||||
return inRoot ? drive : null
|
||||
}
|
||||
return { worktreeId: (worktreeId) => ids.get(worktreeId) ?? null, path }
|
||||
}
|
||||
|
||||
function parseArray(value: string): unknown[] | null {
|
||||
@@ -94,9 +84,10 @@ export function convertedQuickOpenHistoryScope(
|
||||
return null
|
||||
}
|
||||
const nextId = keys.worktreeId(worktreeId)
|
||||
// Quick-open keeps its roots in comparison form, which folds both UNC spellings into one.
|
||||
const nextRoot = keys.comparisonKey(root)
|
||||
return nextId !== null && nextRoot !== null ? JSON.stringify([route, nextId, nextRoot]) : null
|
||||
const nextRoot = keys.path(root)
|
||||
return nextId !== null && nextRoot !== null
|
||||
? JSON.stringify([route, nextId, normalizeRuntimePathForComparison(nextRoot)])
|
||||
: null
|
||||
}
|
||||
|
||||
/** `[worktreeId, environment, sshTarget, filePath]`, as buildFileViewPreferenceKey writes it. */
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
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' }, [
|
||||
String.raw`\\wsl.localhost\Ubuntu\mnt\c\src`
|
||||
])
|
||||
expect(d1c.path(String.raw`\\wsl.localhost\Ubuntu\mnt\c\src`)).toBe(String.raw`C:\src`)
|
||||
expect(d1c.comparisonForm('//wsl/ubuntu/mnt/c/src')).toBe('c:/src')
|
||||
expect(d1c.path(String.raw`W:\home`)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
it('keeps a linked worktree’s own case below a broader worktree base', () => {
|
||||
const oldId = String.raw`r::W:\home\me\trees\Feature`
|
||||
const newId = String.raw`r::\\wsl.localhost\Ubuntu\home\me\trees\Feature`
|
||||
const keys = wslDriveUncRendererKeys({
|
||||
distro: 'Ubuntu',
|
||||
mappedDrive: DRIVE,
|
||||
worktreeIds: [[oldId, newId]],
|
||||
// The base is listed before the worktree, so only innermost-first matching finds it.
|
||||
rootPaths: [String.raw`W:\home\me\App`, String.raw`W:\home\me\trees`]
|
||||
})
|
||||
const route = { executionHostId: 'local' }
|
||||
expect(
|
||||
convertedQuickOpenHistoryScope(
|
||||
JSON.stringify([route, oldId, 'w:/home/me/trees/feature']),
|
||||
keys
|
||||
)
|
||||
).toBe(JSON.stringify([route, newId, '//wsl/ubuntu/home/me/trees/Feature']))
|
||||
})
|
||||
|
||||
it('treats only an exactly folded string as a comparison key', () => {
|
||||
const respelling = wslDriveUncRespelling({ distro: 'Ubuntu', mappedDrive: DRIVE }, [
|
||||
String.raw`W:\home\me\App`
|
||||
])
|
||||
expect(respelling.comparisonForm('w:/home/me/app')).toBe('//wsl/ubuntu/home/me/App')
|
||||
expect(respelling.comparisonForm('w:/home/me/app/')).toBeNull()
|
||||
expect(respelling.comparisonForm('w:/home//me/app')).toBeNull()
|
||||
expect(respelling.comparisonForm(String.raw`w:\home\me\app`)).toBeNull()
|
||||
})
|
||||
|
||||
it("keeps the root's case for a mixed-case folder, whose key is folded", () => {
|
||||
const oldId = String.raw`r::W:\home\me\App`
|
||||
const newId = String.raw`r::\\wsl.localhost\Ubuntu\home\me\App`
|
||||
const keys = wslDriveUncRendererKeys({
|
||||
distro: 'Ubuntu',
|
||||
mappedDrive: DRIVE,
|
||||
worktreeIds: [[oldId, newId]],
|
||||
rootPaths: [String.raw`W:\home\me\App`]
|
||||
})
|
||||
const route = { executionHostId: 'local' }
|
||||
expect(
|
||||
convertedQuickOpenHistoryScope(JSON.stringify([route, oldId, 'w:/home/me/app']), keys)
|
||||
).toBe(JSON.stringify([route, newId, '//wsl/ubuntu/home/me/App']))
|
||||
})
|
||||
})
|
||||
@@ -1,158 +0,0 @@
|
||||
/**
|
||||
* 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 { normalizeRuntimePathForComparison } from '../file-access/cross-platform-path'
|
||||
import { parseWslUncPath, wslUncDrivePathToWindows } from '../file-access/wsl-paths'
|
||||
|
||||
/** A drive letter mapped to a distro share, as the resolver read it when the conversion began. */
|
||||
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 at or inside a converted root, re-keyed in that form;
|
||||
* null otherwise. Folded case can't be unfolded, so the root's own spelling supplies it.
|
||||
*/
|
||||
comparisonForm: (value: string) => string | null
|
||||
}
|
||||
|
||||
type PathMap = Omit<WslDriveUncRespelling, 'comparisonForm'> & {
|
||||
/** A string only `normalizeRuntimePathForComparison` produces in this conversion's source form. */
|
||||
isComparisonKey: (value: string) => boolean
|
||||
}
|
||||
|
||||
export function wslDriveUncRespelling(
|
||||
conversion: { distro: string; mappedDrive?: WslMappedDrive | null },
|
||||
/** The converting folders as saved; comparison keys are re-keyed only at or inside one. */
|
||||
roots: readonly string[] = []
|
||||
): WslDriveUncRespelling {
|
||||
const map = conversion.mappedDrive
|
||||
? mappedDriveRespelling(conversion.mappedDrive)
|
||||
: uncDriveRespelling(conversion.distro)
|
||||
const rootKeys = roots
|
||||
.flatMap((root) => {
|
||||
const converted = map.path(root)
|
||||
return converted ? [{ from: normalizeRuntimePathForComparison(root), to: converted }] : []
|
||||
})
|
||||
// Innermost first: a worktree's own root keeps its case, which its broader base can't restore.
|
||||
.sort((a, b) => b.from.length - a.from.length)
|
||||
return {
|
||||
path: map.path,
|
||||
fileUrl: map.fileUrl,
|
||||
comparisonForm: (value) => {
|
||||
if (!map.isComparisonKey(value)) {
|
||||
return null
|
||||
}
|
||||
for (const { from, to } of rootKeys) {
|
||||
const prefix = from.endsWith('/') ? from : `${from}/`
|
||||
if (value === from || value.startsWith(prefix)) {
|
||||
const rest = value === from ? '' : value.slice(prefix.length)
|
||||
const joined = rest ? `${to.replace(/[\\/]+$/, '')}\\${rest.replace(/\//g, '\\')}` : to
|
||||
return normalizeRuntimePathForComparison(joined)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function uncDriveRespelling(distro: string): PathMap {
|
||||
const fileUrl = new RegExp(
|
||||
`^file://(?:wsl\\.localhost|wsl\\$)/${escapeRegExp(distro)}(/mnt/[a-z](?:/[^?#]*)?)([?#].*)?$`,
|
||||
'i'
|
||||
)
|
||||
const comparisonKey = new RegExp(`^//wsl/${escapeRegExp(distro.toLowerCase())}/mnt/[a-z](?:/|$)`)
|
||||
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 }
|
||||
},
|
||||
isComparisonKey: (value) => comparisonKey.test(value)
|
||||
}
|
||||
}
|
||||
|
||||
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): PathMap {
|
||||
const letter = drive.letter.toLowerCase()
|
||||
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
|
||||
},
|
||||
// Exactly what folding produces (lowercase, single forward slashes, no trailing one); saved
|
||||
// paths keep their `W:\` spelling. Only a key at or inside a converted root is re-keyed.
|
||||
isComparisonKey: (value) =>
|
||||
value.startsWith(`${letter}:/`) &&
|
||||
value === value.toLowerCase() &&
|
||||
value === normalizeRuntimePathForComparison(value)
|
||||
}
|
||||
}
|
||||
|
||||
/** `\\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, '\\$&')
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
sameWslMappedDrives,
|
||||
toWslDistroUncPath,
|
||||
wslMappedDriveComparisonKeyToLinux,
|
||||
wslMappedDriveFileUrlToLinux,
|
||||
wslMoveSourcePathToLinux
|
||||
} from './wsl-mapped-drive-paths'
|
||||
import { parseWslMoveRequest } from './wsl-move-request'
|
||||
import { wslMoveRendererRewriteScope } from './wsl-move-renderer-rewrite-scope'
|
||||
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
const H = { letter: 'H', share: '\\\\wsl$\\Ubuntu\\home' }
|
||||
|
||||
describe('mapped-drive paths', () => {
|
||||
it('spells a mapped path as the share and leaves other drives alone', () => {
|
||||
expect(toWslDistroUncPath('W:\\home\\me\\App', [W])).toBe(
|
||||
'\\\\wsl.localhost\\Ubuntu\\home\\me\\App'
|
||||
)
|
||||
expect(toWslDistroUncPath('w:/home/me/App/', [W])).toBe(
|
||||
'\\\\wsl.localhost\\Ubuntu\\home\\me\\App'
|
||||
)
|
||||
expect(toWslDistroUncPath('X:\\home\\me\\App', [W])).toBe('X:\\home\\me\\App')
|
||||
expect(wslMoveSourcePathToLinux('H:\\me\\App', 'ubuntu', [H])).toBe('/home/me/App')
|
||||
expect(wslMoveSourcePathToLinux('W:\\..\\x', 'Ubuntu', [W])).toBeNull()
|
||||
})
|
||||
|
||||
it('maps a file URL on a mapped drive, keeping its encoding', () => {
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///W:/home/me/a%20b.ts', 'Ubuntu', [W])).toBe(
|
||||
'file:///home/me/a%20b.ts'
|
||||
)
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///H:/me/x#L2', 'Ubuntu', [H])).toBe(
|
||||
'file:///home/me/x#L2'
|
||||
)
|
||||
expect(wslMappedDriveFileUrlToLinux('file:///X:/home/me', 'Ubuntu', [W])).toBeNull()
|
||||
})
|
||||
|
||||
it('restores a folded key case from the innermost moved root', () => {
|
||||
const roots = ['/home/me/App', '/home/me/App/Trees/Feature']
|
||||
expect(wslMappedDriveComparisonKeyToLinux('w:/home/me/app/src', 'Ubuntu', [W], roots)).toBe(
|
||||
'/home/me/App/src'
|
||||
)
|
||||
expect(
|
||||
wslMappedDriveComparisonKeyToLinux('w:/home/me/app/trees/feature/x', 'Ubuntu', [W], roots)
|
||||
).toBe('/home/me/App/Trees/Feature/x')
|
||||
// A saved path keeps its own case; only folded keys are re-keyed.
|
||||
expect(wslMappedDriveComparisonKeyToLinux('W:\\home\\me\\App', 'Ubuntu', [W], roots)).toBeNull()
|
||||
expect(wslMappedDriveComparisonKeyToLinux('w:/srv/other', 'Ubuntu', [W], roots)).toBeNull()
|
||||
})
|
||||
|
||||
it('compares mappings by letter and share, not order or spelling', () => {
|
||||
expect(
|
||||
sameWslMappedDrives([W, H], [{ letter: 'H', share: '\\\\wsl.localhost\\ubuntu\\home' }, W])
|
||||
).toBe(true)
|
||||
expect(sameWslMappedDrives([W], [{ letter: 'W', share: '\\\\wsl.localhost\\Debian' }])).toBe(
|
||||
false
|
||||
)
|
||||
expect(sameWslMappedDrives([W], [])).toBe(false)
|
||||
})
|
||||
|
||||
it('accepts the mapping a start sends back, and refuses one that names no distro', () => {
|
||||
expect(parseWslMoveRequest({ distro: 'Ubuntu', mappedDrives: [W] })?.mappedDrives).toEqual([W])
|
||||
expect(
|
||||
parseWslMoveRequest({ distro: 'Ubuntu', mappedDrives: [{ letter: 'W', share: 'C:\\x' }] })
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('wslMoveRendererRewriteScope with mapped drives', () => {
|
||||
const move = {
|
||||
distro: 'Ubuntu',
|
||||
scopeRepoIds: ['repo-1'],
|
||||
scopeFolderWorkspaceIds: [],
|
||||
destinationHostId: 'runtime:wsl:Ubuntu' as const,
|
||||
destinationEnvironmentId: 'wsl:Ubuntu',
|
||||
scopeRootPaths: ['/home/me/App'],
|
||||
mappedDrives: [W]
|
||||
}
|
||||
|
||||
it('maps W: paths, folded w:/ keys and worktree ids to the host with exact case', () => {
|
||||
const scope = wslMoveRendererRewriteScope(move)
|
||||
expect(scope.hostPath('W:\\home\\me\\App\\src\\Main.ts')).toBe('/home/me/App/src/Main.ts')
|
||||
expect(scope.hostPath('w:/home/me/app')).toBe('/home/me/App')
|
||||
expect(scope.hostWorktreeId('repo-1::W:\\home\\me\\App')).toBe('repo-1::/home/me/App')
|
||||
expect(scope.hostPath('X:\\home\\me\\App')).toBeNull()
|
||||
})
|
||||
|
||||
it('leaves W: paths alone for a move that mapped no drive', () => {
|
||||
const scope = wslMoveRendererRewriteScope({ ...move, mappedDrives: undefined })
|
||||
expect(scope.hostPath('W:\\home\\me\\App')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* Paths on a drive letter mapped to a distro share (`net use W: \\wsl.localhost\Ubuntu`), as the
|
||||
* WSL move reads them: the same folder as the share's UNC spelling. The mapping is the one read
|
||||
* when the move was previewed and journaled, never a fresh read, so recovery maps what it moved.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
import { normalizeRuntimePathForComparison } from '../file-access/cross-platform-path'
|
||||
import { parseWslUncPath, wslUncPathToLinux } from '../file-access/wsl-paths'
|
||||
|
||||
/** A drive letter mapped to a distro share; `share` may be a folder inside the distro. */
|
||||
export type WslMappedDrive = { letter: string; share: string }
|
||||
|
||||
export const WslMappedDrivesSchema = z
|
||||
.array(
|
||||
z.object({
|
||||
letter: z.string().regex(/^[A-Z]$/),
|
||||
share: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(4_096)
|
||||
.refine((share) => parseWslUncPath(share) !== null)
|
||||
})
|
||||
)
|
||||
.max(26)
|
||||
|
||||
const DRIVE_ABSOLUTE = /^([A-Za-z]):[\\/]([\s\S]*)$/
|
||||
const DRIVE_FILE_URL = /^file:\/\/\/([A-Za-z]):(\/[^?#]*)?([?#][\s\S]*)?$/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
|
||||
}
|
||||
|
||||
/** The drive `path` sits on among `mappedDrives`; null for any other path. */
|
||||
export function wslMappedDriveOf(
|
||||
path: string,
|
||||
mappedDrives: readonly WslMappedDrive[]
|
||||
): WslMappedDrive | null {
|
||||
const letter = DRIVE_ABSOLUTE.exec(path)?.[1].toUpperCase()
|
||||
return (letter && mappedDrives.find((drive) => drive.letter.toUpperCase() === letter)) || null
|
||||
}
|
||||
|
||||
/** The share spelling of a path on one of `mappedDrives`; any other path unchanged. */
|
||||
export function toWslDistroUncPath(path: string, mappedDrives: readonly WslMappedDrive[]): string {
|
||||
const drive = mappedDrives.length > 0 ? wslMappedDriveOf(path, mappedDrives) : null
|
||||
return (drive && wslMappedDrivePathToShare(path, drive)) ?? path
|
||||
}
|
||||
|
||||
/** A UNC or mapped-drive path's Linux path in `distro`; null outside it. */
|
||||
export function wslMoveSourcePathToLinux(
|
||||
path: string,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = []
|
||||
): string | null {
|
||||
return wslUncPathToLinux(toWslDistroUncPath(path, mappedDrives), distro)
|
||||
}
|
||||
|
||||
/** `file:///W:/x` -> `file:///<linux>/x`, keeping the URL's own encoding of the tail. */
|
||||
export function wslMappedDriveFileUrlToLinux(
|
||||
url: string,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[]
|
||||
): string | null {
|
||||
const match = mappedDrives.length > 0 ? DRIVE_FILE_URL.exec(url) : null
|
||||
const drive = match ? wslMappedDriveOf(`${match[1]}:\\`, mappedDrives) : null
|
||||
const root = drive ? wslUncPathToLinux(drive.share, distro) : null
|
||||
if (!match || root === null) {
|
||||
return null
|
||||
}
|
||||
const encodedRoot = root === '/' ? '' : root.split('/').map(encodeURIComponent).join('/')
|
||||
return `file://${encodedRoot}${match[2] ?? '/'}${match[3] ?? ''}`
|
||||
}
|
||||
|
||||
/**
|
||||
* A `normalizeRuntimePathForComparison` key on a mapped drive (`w:/home/me/app`), which folded
|
||||
* the case Linux needs: its Linux path with the case of the innermost `linuxRoots` entry holding
|
||||
* it. Null when it is not such a key or no root holds it.
|
||||
*/
|
||||
export function wslMappedDriveComparisonKeyToLinux(
|
||||
key: string,
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[],
|
||||
linuxRoots: readonly string[]
|
||||
): string | null {
|
||||
if (
|
||||
mappedDrives.length === 0 ||
|
||||
key !== key.toLowerCase() ||
|
||||
key.includes('\\') ||
|
||||
key !== normalizeRuntimePathForComparison(key)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const folded = wslMoveSourcePathToLinux(key, distro, mappedDrives)
|
||||
if (folded === null) {
|
||||
return null
|
||||
}
|
||||
// Innermost first: a worktree's own root keeps its case, which its broader base can't restore.
|
||||
const roots = [...linuxRoots].sort((a, b) => b.length - a.length)
|
||||
for (const root of roots) {
|
||||
const lower = root.toLowerCase().replace(/\/+$/, '')
|
||||
const target = folded.toLowerCase()
|
||||
if (target === lower || target.startsWith(`${lower}/`)) {
|
||||
return `${root.replace(/\/+$/, '')}${folded.slice(lower.length)}` || '/'
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The same drives mapped to the same shares; order and spelling of the share don't count. */
|
||||
export function sameWslMappedDrives(
|
||||
left: readonly WslMappedDrive[],
|
||||
right: readonly WslMappedDrive[]
|
||||
): boolean {
|
||||
const key = (drives: readonly WslMappedDrive[]): string =>
|
||||
JSON.stringify(
|
||||
drives
|
||||
.map((drive) => [
|
||||
drive.letter.toUpperCase(),
|
||||
normalizeRuntimePathForComparison(drive.share)
|
||||
])
|
||||
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
)
|
||||
return key(left) === key(right)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
} from '../orcad-migration/orcad-migration-manifest'
|
||||
import { isOrcadMigrationLocalWslSource } from '../orcad-migration/orcad-migration-source-kind'
|
||||
import { WslMoveBrowserCookieCopySchema } from './wsl-move-browser-cookie-copy'
|
||||
import { WslMappedDrivesSchema } from './wsl-mapped-drive-paths'
|
||||
import {
|
||||
MAX_ORCAD_MIGRATION_TERMINAL_RESTORE_HINTS,
|
||||
isOrcadMigrationTerminalRestoreHintCwd,
|
||||
@@ -14,6 +15,12 @@ import {
|
||||
} from '../orcad-migration/orcad-migration-terminal-restore-hints'
|
||||
|
||||
export const WSL_MOVE_CUTOVER_VERSION = 1
|
||||
/**
|
||||
* A move that took mapped-drive projects. Builds before it accept only version 1, so they read
|
||||
* such a record as unreadable and fence every WSL project rather than recover it without the
|
||||
* mapping (their parser would drop `mappedDrives` and treat `W:\` rows as outside the move).
|
||||
*/
|
||||
export const WSL_MOVE_MAPPED_DRIVE_CUTOVER_VERSION = 2
|
||||
|
||||
/** In order; each crash point resumes from the last one written (design, section 4.4). */
|
||||
export const WSL_MOVE_CUTOVER_PHASES = [
|
||||
@@ -31,7 +38,10 @@ export type WslMoveCutoverPhase = (typeof WSL_MOVE_CUTOVER_PHASES)[number]
|
||||
|
||||
// Accept newer optional fields without making journals unreadable.
|
||||
const WslMoveCutoverSchema = z.object({
|
||||
version: z.literal(WSL_MOVE_CUTOVER_VERSION),
|
||||
version: z.union([
|
||||
z.literal(WSL_MOVE_CUTOVER_VERSION),
|
||||
z.literal(WSL_MOVE_MAPPED_DRIVE_CUTOVER_VERSION)
|
||||
]),
|
||||
migrationId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
|
||||
phase: z.enum(WSL_MOVE_CUTOVER_PHASES),
|
||||
startedAt: z.string().datetime(),
|
||||
@@ -79,6 +89,9 @@ const WslMoveCutoverSchema = z.object({
|
||||
.record(z.string().min(1).max(1_024), z.boolean())
|
||||
.optional()
|
||||
.catch(undefined),
|
||||
// Drive letters mapped into the distro when the move was planned; every recovery reads these,
|
||||
// never the drive. Strict: a malformed list fails closed.
|
||||
mappedDrives: WslMappedDrivesSchema.optional(),
|
||||
manifest: z.unknown()
|
||||
})
|
||||
|
||||
@@ -91,9 +104,20 @@ export function wslMoveJournalKey(distro: string): string {
|
||||
return `local-wsl:${distro.toLowerCase()}`
|
||||
}
|
||||
|
||||
/** The record version a move with these mapped drives is written as. */
|
||||
export function wslMoveCutoverVersionFor(
|
||||
mappedDrives: readonly unknown[] | undefined
|
||||
): WslMoveCutover['version'] {
|
||||
return mappedDrives?.length ? WSL_MOVE_MAPPED_DRIVE_CUTOVER_VERSION : WSL_MOVE_CUTOVER_VERSION
|
||||
}
|
||||
|
||||
/** Throws on anything that is not exactly a WSL move whose manifest matches its binding. */
|
||||
export function parseWslMoveCutover(value: unknown): WslMoveCutover {
|
||||
const record = WslMoveCutoverSchema.parse(value)
|
||||
// Version 2 exactly when drives were mapped, so no older build can read a mapped move.
|
||||
if (record.version !== wslMoveCutoverVersionFor(record.mappedDrives)) {
|
||||
throw new Error('wsl_move_cutover_version_mismatch')
|
||||
}
|
||||
const manifest = parseOrcadMigrationManifest(record.manifest)
|
||||
const { source } = manifest
|
||||
if (
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
import type { WslMoveBrowserCookieFreshPartitionReason } from './wsl-move-browser-cookie-copy'
|
||||
import type { WslMoveCutoverPhase } from './wsl-move-cutover'
|
||||
import type { WslMappedDrive } from './wsl-mapped-drive-paths'
|
||||
|
||||
/** Which projects of a distro to move; omitted ids mean every project in the distro. */
|
||||
export type WslMoveRequest = {
|
||||
@@ -13,6 +14,8 @@ export type WslMoveRequest = {
|
||||
folderWorkspaceIds?: string[]
|
||||
/** The window's bindings of panes with no live terminal: main retires a slept pane's on Sleep. */
|
||||
sleptPanes?: { paneKey: string; sessionId: string }[]
|
||||
/** At start: the preview's `mappedDrives`; main refuses if the drives map elsewhere now. */
|
||||
mappedDrives?: WslMappedDrive[]
|
||||
}
|
||||
|
||||
export type WslMoveRowRef = { kind: 'repo' | 'folder'; id: string }
|
||||
@@ -83,6 +86,8 @@ export type WslMovePreview =
|
||||
blockers: WslMoveBlocker[]
|
||||
/** Set when the host's browser would start signed out; listed, never a blocker (R44). */
|
||||
browserLoginsNotCarried?: WslMoveBrowserCookieFreshPartitionReason
|
||||
/** Drive letters mapped into the distro that this preview read; the start sends them back. */
|
||||
mappedDrives?: WslMappedDrive[]
|
||||
}
|
||||
| WslMoveRefusal
|
||||
|
||||
@@ -163,5 +168,8 @@ export type WslMoveUnfinished = {
|
||||
|
||||
export const WSL_MOVE_PROGRESS_CHANNEL = 'wslMove:progress'
|
||||
|
||||
/** The `detail` of a refusal because Windows did not say where a project's mapped drive points. */
|
||||
export const WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL = 'mapped-drive-unverifiable'
|
||||
|
||||
/** The `detail` of an earlier move committed on the host whose desktop half waits for a restart. */
|
||||
export const WSL_MOVE_FINISH_PENDING_DETAIL = 'finish-pending'
|
||||
|
||||
@@ -4,7 +4,10 @@
|
||||
* the moved distro changes, as the main-side rewrite (wsl-move-rewrite-scope.ts) maps it.
|
||||
*/
|
||||
import { parseWorkspaceKey } from '../workspace/identity/workspace-scope'
|
||||
import { wslUncPathToLinux } from '../file-access/wsl-paths'
|
||||
import {
|
||||
wslMappedDriveComparisonKeyToLinux,
|
||||
wslMoveSourcePathToLinux
|
||||
} from './wsl-mapped-drive-paths'
|
||||
import { getRepoIdFromWorktreeId, rewriteWorktreeIdPath } from '../worktree/id'
|
||||
import type { WslMovePendingRendererRewrite } from './wsl-move-renderer-rewrite-types'
|
||||
|
||||
@@ -31,13 +34,17 @@ export function wslMoveRendererRewriteScope(
|
||||
| 'destinationHostId'
|
||||
| 'destinationEnvironmentId'
|
||||
| 'scopeRootPaths'
|
||||
| 'mappedDrives'
|
||||
>
|
||||
): WslMoveRendererRewriteScope {
|
||||
const repoIds = new Set(move.scopeRepoIds)
|
||||
const folderIds = new Set(move.scopeFolderWorkspaceIds)
|
||||
const distro = move.distro.toLowerCase()
|
||||
const mappedDrives = move.mappedDrives ?? []
|
||||
const hostPath = (path: string): string | null => {
|
||||
const linux = wslUncPathToLinux(path, distro)
|
||||
// A folded `w:/…` key lost the case Linux needs; the moved roots restore it.
|
||||
const key = wslMappedDriveComparisonKeyToLinux(path, distro, mappedDrives, move.scopeRootPaths)
|
||||
const linux = key ?? wslMoveSourcePathToLinux(path, distro, mappedDrives)
|
||||
if (linux !== null) {
|
||||
return linux
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** The renderer's half of a committed WSL move's desktop rewrite, as carried over IPC. */
|
||||
import type { WslMappedDrive } from './wsl-mapped-drive-paths'
|
||||
|
||||
/** The renderer-side stores, in run order; main registers each so the ledger waits on it. */
|
||||
export const WSL_MOVE_RENDERER_REWRITE_STORE_IDS = [
|
||||
@@ -24,6 +25,8 @@ export type WslMovePendingRendererRewrite = {
|
||||
scopeFolderWorkspaceIds: string[]
|
||||
/** The moved projects' directories on the host, for stores keyed by a bare file path. */
|
||||
scopeRootPaths: string[]
|
||||
/** The move's mapped drives, from its journal: `W:\x` paths and `w:/x` keys moved too. */
|
||||
mappedDrives?: WslMappedDrive[]
|
||||
}
|
||||
|
||||
export type WslMoveRecordStoreRewrittenRequest = {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** The move dialog's request as main accepts it from the renderer: anything else is refused. */
|
||||
import { z } from 'zod'
|
||||
import type { WslMoveRequest } from './wsl-move-driver-types'
|
||||
import { WslMappedDrivesSchema } from './wsl-mapped-drive-paths'
|
||||
|
||||
const Ids = z.array(z.string().min(1).max(1_024)).max(10_000)
|
||||
|
||||
@@ -18,7 +19,8 @@ const WslMoveRequestSchema = z.object({
|
||||
z.object({ paneKey: z.string().min(1).max(1_024), sessionId: z.string().min(1).max(1_024) })
|
||||
)
|
||||
.max(10_000)
|
||||
.optional()
|
||||
.optional(),
|
||||
mappedDrives: WslMappedDrivesSchema.optional()
|
||||
})
|
||||
|
||||
export function parseWslMoveRequest(value: unknown): WslMoveRequest | null {
|
||||
|
||||
Reference in New Issue
Block a user