fix(wsl-hosts): finish committed respellings forward and keep runtimes exact

- Startup re-checks a mapped-drive plan only while the profile still names the
  drive; a plan past its profile commit finishes forward with its recorded map.
- Refuse respellings that would change where a workspace runs: standalone folder
  workspaces (no runtime setting) and projects with no saved runtime that already
  have workspaces on the share. The folder menu no longer offers them.
- Re-key folded comparison keys from each worktree's own folder, innermost first,
  and treat only exactly folded strings as comparison keys.
- Report a rolled-back plan to the window once, and wake the workspaces its
  confirm paused.

Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
Neil
2026-11-17 00:08:03 -08:00
parent 661d63be9c
commit 64c9d448a9
19 changed files with 482 additions and 110 deletions
@@ -9,7 +9,7 @@ import { app, ipcMain, type IpcMainInvokeEvent } from 'electron'
import type {
WslDriveUncConversionRequest,
WslDriveUncConversionResult,
WslMappedDriveMoveDue
WslMappedDriveRestartReport
} 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,7 +23,7 @@ import { quitProcess } from '../../startup/quit/process-quit-request'
import { startWslDriveUncConversion } from '../../wsl/filesystem/wsl-drive-unc-conversion-run'
import {
lastWslDriveUncConversionOutcomes,
takeWslMappedDriveMovesDue,
takeWslMappedDriveRestartReport,
type WslDriveUncConversionOutcome
} from '../../wsl/filesystem/wsl-drive-unc-conversion-startup'
import { readWslMappedDriveShareNow } from '../../wsl/filesystem/wsl-mapped-drive-share'
@@ -43,7 +43,7 @@ import { readWslDistroDriveMounts } from '../../wsl/filesystem/wsl-drive-unc-mou
export const WSL_DRIVE_UNC_CONVERSION_CHANNELS = [
'wslDriveUnc:convert',
'wslDriveUnc:lastOutcomes',
'wslDriveUnc:takeMappedDriveMovesDue',
'wslDriveUnc:takeMappedDriveRestartReport',
'wslDriveUnc:listPendingRendererRewrites',
'wslDriveUnc:recordStoreRewritten'
] as const
@@ -103,11 +103,13 @@ export function registerWslDriveUncConversionHandlers(
wslHostsGateOpen() ? lastWslDriveUncConversionOutcomes() : []
)
ipcMain.handle(
'wslDriveUnc:takeMappedDriveMovesDue',
(event: IpcMainInvokeEvent): WslMappedDriveMoveDue[] =>
'wslDriveUnc:takeMappedDriveRestartReport',
(event: IpcMainInvokeEvent): WslMappedDriveRestartReport =>
wslHostsGateOpen() && getTrustedUIRendererWebContents()?.id === event.sender.id
? takeWslMappedDriveMovesDue()
: []
? takeWslMappedDriveRestartReport(
(worktreeId) => void runtime.wakePausedWorkspace(worktreeId)
)
: { moves: [], rolledBack: [] }
)
ipcMain.handle(
'wslDriveUnc:listPendingRendererRewrites',
@@ -100,6 +100,11 @@ 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
@@ -30,12 +30,15 @@ import { orchestrationDbFile } from '../../runtime/orchestration/db/orchestratio
import { journalDomainDatabasePath } from '../../native-chat/agent-session-journal/database/journal-domain-database'
import { rewriteWslDriveUncState } from './wsl-drive-unc-state-rewrite'
import { WSL_DRIVE_UNC_STATE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-drive-unc-state-dispositions'
import type { WslMappedDriveMoveDue } from '../../../shared/wsl-move/wsl-drive-unc-conversion-types'
import type { WslMappedDriveRestartReport } from '../../../shared/wsl-move/wsl-drive-unc-conversion-types'
import { readWslMappedDriveShareNow, type WslMappedDriveRead } from './wsl-mapped-drive-share'
import {
readWslMappedDriveShareNow,
wslMappedDriveMatches,
type WslMappedDriveRead
} from './wsl-mapped-drive-share'
assertMappedDriveStillMatches,
pausedOf,
profileStillNamesMappedDrive,
wslMappedDriveMovesDueOf,
wslMappedDriveRollbacksOf
} from './wsl-mapped-drive-conversion-plan'
const STARTUP_DRIVE_READ_TIMEOUT_MS = 10_000
@@ -51,9 +54,6 @@ export type WslDriveUncConversionStartupDeps = {
readMappedDriveShare?: (letter: string) => Promise<WslMappedDriveRead>
}
/** The restart follows the confirm within seconds; a plan this old was left by another run. */
const MAPPED_DRIVE_PLAN_MAX_AGE_MS = 60 * 60 * 1000
export type WslDriveUncConversionOutcome =
| {
migrationId: string
@@ -67,7 +67,13 @@ export type WslDriveUncConversionOutcome =
respelledThisRun?: boolean
}
/** The profile could not be rewritten; nothing changed, and the panes stay asleep. */
| { migrationId: string; outcome: 'rolled-back'; detail: string }
| {
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[] }
}
/** The profile is converted; `store` failed and retries at the next startup. */
| { migrationId: string; outcome: 'resuming'; store: string; detail: string }
@@ -91,11 +97,22 @@ async function runOne(
const advancing = record.phase === 'prepared'
if (advancing) {
try {
await assertMappedDriveStillMatches(deps, record)
// 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) }
return {
migrationId,
outcome: 'rolled-back',
detail: describe(error),
...(record.mappedDrive
? { mappedDrive: { letter: record.mappedDrive.letter, workspaceIds: pausedOf(record) } }
: {})
}
}
// Past the commit, so never a rollback: if this write fails the journal stays 'prepared', and
// the next startup's rewrite is idempotent.
@@ -132,34 +149,6 @@ async function runOne(
}
}
/**
* A mapped-drive plan names the drive's share as it was at the confirm. One left over (an older
* build ran in between, say) or a drive remapped since rolls back instead of rewriting into the
* wrong distro or folder.
*/
async function assertMappedDriveStillMatches(
deps: WslDriveUncConversionStartupDeps,
record: WslDriveUncConversion
): Promise<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')
}
}
/**
* Idempotent: a profile already rewritten (a crash after its commit) rewrites to itself, and the
* id map was journaled before the commit, so the other stores still get it. Ends at the commit.
@@ -228,34 +217,25 @@ export function lastWslDriveUncConversionOutcomes(): WslDriveUncConversionOutcom
return [...lastOutcomes]
}
let movesTaken = false
let reportTaken = false
/** Once per run: a window reload must not open the move again. */
export function takeWslMappedDriveMovesDue(): WslMappedDriveMoveDue[] {
if (movesTaken) {
return []
/**
* 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: [] }
}
movesTaken = true
return wslMappedDriveMovesDueOf(lastOutcomes)
}
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
}
]
: []
)
reportTaken = true
const rolledBack = wslMappedDriveRollbacksOf(outcomes)
for (const worktreeId of rolledBack.flatMap((rollback) => rollback.workspaceIds)) {
wake(worktreeId)
}
return { moves: wslMappedDriveMovesDueOf(outcomes), rolledBack }
}
/**
@@ -32,6 +32,8 @@ export type WslDriveUncRefusal =
| '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[]
@@ -0,0 +1,116 @@
/**
* 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
}
]
: []
)
}
@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'
import '../../sqlite/sync-database'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
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'
@@ -18,8 +18,14 @@ import {
} from './wsl-drive-unc-conversion-journal'
import {
runWslDriveUncConversionsAtStartup,
wslMappedDriveMovesDueOf
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'
@@ -151,12 +157,15 @@ function journal(overrides: Partial<WslDriveUncConversion> = {}): void {
})
}
function run(read: WslMappedDriveRead = { share: SHARE }) {
function run(
read: WslMappedDriveRead = { share: SHARE },
stores: WslDriveUncConversionStore[] = []
) {
return runWslDriveUncConversionsAtStartup({
userDataPath: root,
profileUserDataPath: root,
profileId: PROFILE,
stores: [],
stores,
now: () => new Date('2026-11-16T00:00:05.000Z'),
readMappedDriveShare: async () => read
})
@@ -222,12 +231,54 @@ describe('a mapped-drive conversion at startup', () => {
])('rolls back, changing nothing, when %s', async (_why, read, overrides) => {
seedProfile(profileState())
journal(overrides)
const [outcome] = await run(read)
expect(outcome).toMatchObject({ migrationId: 'conv-1', outcome: 'rolled-back' })
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)
@@ -250,6 +301,25 @@ describe('a mapped-drive conversion at startup', () => {
])
})
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([
@@ -29,7 +29,7 @@ function folder(id: string, folderPath: string, extra: Partial<FolderWorkspace>
}
describe('collectWslMappedDriveScope', () => {
it('takes local repos and folders on the drive, and nothing elsewhere', () => {
it('takes local repos on the drive, and nothing elsewhere', () => {
const scope = collectWslMappedDriveScope(
{
repos: [
@@ -42,7 +42,12 @@ describe('collectWslMappedDriveScope', () => {
},
DRIVE
)
expect(scope).toEqual({ repoIds: ['on-drive'], folderWorkspaceIds: ['notes'], refused: [] })
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', () => {
@@ -54,7 +59,11 @@ describe('collectWslMappedDriveScope', () => {
})
],
folderWorkspaces: [],
projectGroups: []
projectGroups: [],
// Saved, so the worktrees on the share keep running where they did.
projects: [
{ sourceRepoIds: ['app'], localWindowsRuntimePreference: { kind: 'windows-host' } }
]
},
DRIVE
)
@@ -85,6 +94,41 @@ describe('collectWslMappedDriveScope', () => {
])
})
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(
{
@@ -13,10 +13,13 @@ import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-w
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
@@ -32,6 +35,9 @@ 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(
@@ -70,7 +76,11 @@ export function collectWslMappedDriveScope(
getRepoExecutionHostId(repo) !== LOCAL_EXECUTION_HOST_ID
? 'not-local'
: (refusalOf(wslMoveRepoPaths(repo)) ??
(claimedRepoPaths.has(key) ? 'duplicate-windows-project' : null))
(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 {
@@ -95,10 +105,11 @@ export function collectWslMappedDriveScope(
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' : null))
(claimedFolderPaths.has(key) ? 'duplicate-windows-project' : 'runtime-would-change'))
if (reason) {
scope.refused.push({ kind: 'folder-workspace', id: workspace.id, reason })
} else {
@@ -108,3 +119,24 @@ export function collectWslMappedDriveScope(
}
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)
}
@@ -2,7 +2,7 @@ import { ipcRenderer } from 'electron'
import type {
WslDriveUncConversionRequest,
WslDriveUncConversionResult,
WslMappedDriveMoveDue
WslMappedDriveRestartReport
} 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'
@@ -11,8 +11,8 @@ import type { WslMoveRecordStoreRewrittenResult } from '../../../shared/wsl-move
export type WslDriveUncConversionApi = {
/** Checks, pauses the project's terminals and restarts the app to convert. */
convert: (request: WslDriveUncConversionRequest) => Promise<WslDriveUncConversionResult>
/** Mapped-drive projects this startup respelled, once per run, for the window to move. */
takeMappedDriveMovesDue: () => Promise<WslMappedDriveMoveDue[]>
/** 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,7 +22,8 @@ export type WslDriveUncConversionApi = {
export const wslDriveUncConversionApi: WslDriveUncConversionApi = {
convert: (request) => ipcRenderer.invoke('wslDriveUnc:convert', request),
takeMappedDriveMovesDue: () => ipcRenderer.invoke('wslDriveUnc:takeMappedDriveMovesDue'),
takeMappedDriveRestartReport: () =>
ipcRenderer.invoke('wslDriveUnc:takeMappedDriveRestartReport'),
listPendingRendererRewrites: () => ipcRenderer.invoke('wslDriveUnc:listPendingRendererRewrites'),
recordStoreRewritten: (request) => ipcRenderer.invoke('wslDriveUnc:recordStoreRewritten', request)
}
@@ -143,6 +143,12 @@ 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',
@@ -57,7 +57,8 @@ export function WslMoveFolderWorkspaceMenuItem({
: undefined
})
const target = useWslMoveTargetForPath(folder?.folderPath, !!folder)
return 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
}
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const toast = vi.hoisted(() => vi.fn())
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 }))
@@ -22,15 +22,16 @@ const host = {
}
const convert = vi.fn()
const takeMappedDriveMovesDue = vi.fn()
const takeMappedDriveRestartReport = vi.fn()
beforeEach(() => {
vi.stubGlobal('window', { api: { wslDriveUnc: { convert, takeMappedDriveMovesDue } } })
vi.stubGlobal('window', { api: { wslDriveUnc: { convert, takeMappedDriveRestartReport } } })
})
afterEach(() => {
convert.mockReset()
takeMappedDriveMovesDue.mockReset()
takeMappedDriveRestartReport.mockReset()
toast.error.mockReset()
openWslMoveDialog.mockClear()
toast.mockReset()
vi.unstubAllGlobals()
@@ -98,10 +99,23 @@ describe('the mapped-drive move', () => {
})
})
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 () => {
takeMappedDriveMovesDue.mockResolvedValue([
{ distro: 'Ubuntu', repoIds: ['repo-w', 'repo-nested'], folderWorkspaceIds: ['notes'] }
])
takeMappedDriveRestartReport.mockResolvedValue({
moves: [
{ distro: 'Ubuntu', repoIds: ['repo-w', 'repo-nested'], folderWorkspaceIds: ['notes'] }
],
rolledBack: []
})
await openWslMappedDriveMovesDue()
expect(openWslMoveDialog).toHaveBeenCalledWith(
expect.objectContaining({
@@ -8,7 +8,8 @@ import { toast } from 'sonner'
import { translate } from '@/i18n/i18n'
import type {
WslDriveUncConversionResult,
WslMappedDriveMoveDue
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'
@@ -113,16 +114,22 @@ export async function confirmWslMappedDriveMove(): Promise<void> {
})
}
/** After the restart that reopened them: the move, with only those projects checked. */
/**
* 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 due: WslMappedDriveMoveDue[]
let report: WslMappedDriveRestartReport
try {
due = await window.api.wslDriveUnc.takeMappedDriveMovesDue()
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 = due[0]
const first = report.moves[0]
if (!first) {
return
}
@@ -132,3 +139,33 @@ export async function openWslMappedDriveMovesDue(): Promise<void> {
]
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 }
)
}
}
+9 -2
View File
@@ -24843,7 +24843,13 @@
"failed": "Orca could not reopen this project, so nothing changed.",
"restarting": "Restarting Orca to reopen this project…",
"pausing": "Pausing terminals…",
"restartingLabel": "Restarting…"
"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": {
@@ -25272,7 +25278,8 @@
"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."
"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.",
+1 -1
View File
@@ -170,7 +170,7 @@ function createWebPreloadApi(): Omit<Partial<PreloadApi>, 'settings' | 'plugins'
// Desktop-only: a web client never converts this computer's projects.
wslDriveUnc: {
convert: () => Promise.resolve({ outcome: 'refused', blockers: [] }),
takeMappedDriveMovesDue: () => Promise.resolve([]),
takeMappedDriveRestartReport: () => Promise.resolve({ moves: [], rolledBack: [] }),
listPendingRendererRewrites: () => Promise.resolve([]),
recordStoreRewritten: () => Promise.resolve({ recorded: false, reason: 'gated-off' })
},
@@ -33,6 +33,7 @@ export type WslDriveUncConversionBlocker =
| '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' }
@@ -58,6 +59,20 @@ export type WslMappedDriveMoveDue = {
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 }
@@ -7,6 +7,7 @@ import { normalizeRuntimePathForComparison } from '../file-access/cross-platform
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'
/** A converted conversion's renderer half, as main lists it. */
export type WslDriveUncPendingRendererRewrite = {
@@ -36,7 +37,11 @@ export function wslDriveUncRendererKeys(
>
): WslDriveUncRendererKeys {
const ids = new Map(conversion.worktreeIds)
const respelling = wslDriveUncRespelling(conversion, conversion.rootPaths)
// 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 roots = conversion.rootPaths.flatMap((root) => {
const converted = respelling.path(root)
return converted ? [normalizeRuntimePathForComparison(converted)] : []
@@ -83,6 +83,35 @@ describe('wslDriveUncRendererKeys for a mapped drive', () => {
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`
@@ -35,10 +35,13 @@ export function 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 }] : []
})
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,
@@ -127,9 +130,12 @@ function mappedDriveRespelling(drive: WslMappedDrive): PathMap {
// The share's own segments encoded; the tail keeps the URL's encoding.
return path ? { url: `${shareUrl}${match[2] ?? '/'}${match[3] ?? ''}`, path } : null
},
// Folded: lowercase, forward slashes only. Saved paths keep their `W:\` spelling.
// 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.includes('\\')
value.startsWith(`${letter}:/`) &&
value === value.toLowerCase() &&
value === normalizeRuntimePathForComparison(value)
}
}