Merge PR #744 (extracted): fix(paths): 识别 remote-mirror 工作区命名空间投影(#788 #703;html-cwd 半边已由 d71261ac 覆盖)

This commit is contained in:
HuanLinOTO committed 2026-10-01 17:18:49 +08:00
commit 3345b72699
2 files changed
+193 -14

No files matched your search

+109 -13
View File
@@ -1,22 +1,102 @@
import { readFileSync, statSync } from 'node:fs'
import { win32 } from 'node:path'
/** `\\wsl.localhost\<distro>` root of a Windows-hosted WSL workspace. */
const WSL_LOCALHOST_ROOT = /^\\\\wsl\.localhost\\([^\\]+)(?:\\|$)/i
/**
* `<...>\.dsh\remote-workspaces\<host-key>\<workspace>` mirror root of a
* dsh-remote session. The captured group is the mirror root itself: the
* local directory that mirrors one remote workspace.
*/
const REMOTE_MIRROR_ROOT = /^(.*\\\.dsh\\remote-workspaces\\[^\\]+\\[^\\]+)(?:\\|$)/i
/** Metadata file dsh-remote writes at the root of every mirror directory. */
const REMOTE_META_FILE = '.dsh-remote-meta.json'
/** One cached mirror metadata read, invalidated by the file's mtime. */
interface RemoteMetaEntry {
mtimeMs: number
/** The remote workspace path (POSIX), or undefined when unusable. */
remotePath: string | undefined
}
/**
* Mirror metadata cache. `resolveSessionPath` is synchronous and sits on
* every filesystem request, so the metadata is read synchronously and
* memoized per mirror root; an mtime change re-reads it.
*/
const remoteMetaCache = new Map<string, RemoteMetaEntry>()
/**
* The remote workspace path a mirror root stands for, or undefined when the
* directory carries no usable metadata. Failures are swallowed on purpose:
* an unreadable or malformed meta file must leave the caller's path alone
* rather than break the request.
*/
function remotePathOf(mirrorRoot: string): string | undefined {
const metaFile = win32.join(mirrorRoot, REMOTE_META_FILE)
let mtimeMs: number
try {
mtimeMs = statSync(metaFile).mtimeMs
} catch {
remoteMetaCache.delete(mirrorRoot)
return undefined
}
const cached = remoteMetaCache.get(mirrorRoot)
if (cached !== undefined && cached.mtimeMs === mtimeMs) return cached.remotePath
let remotePath: string | undefined
try {
const parsed: unknown = JSON.parse(readFileSync(metaFile, 'utf8'))
const value = (parsed as { remotePath?: unknown } | null)?.remotePath
// Only POSIX-rooted remote paths can be projected; a Windows remote
// (drive path) needs no reinterpretation and is left to the caller.
remotePath = typeof value === 'string' && value.startsWith('/') ? value : undefined
} catch {
remotePath = undefined
}
remoteMetaCache.set(mirrorRoot, { mtimeMs, remotePath })
return remotePath
}
/**
* The POSIX path segments of `target` relative to `base`, or undefined when
* `target` does not lie under `base`. Both are remote (POSIX) paths, so the
* comparison is case-SENSITIVE and separator handling is plain '/'.
*/
function relativeUnderPosix(base: string, target: string): string | undefined {
const normalize = (value: string): string => value.replace(/\/+$/, '')
const root = normalize(base)
if (target === root) return ''
if (!target.startsWith(`${root}/`)) return undefined
return target.slice(root.length + 1)
}
/**
* Reinterpret an already-absolute path in the namespace of one session.
*
* Windows treats `/foo` as rooted on the current drive, so `path.resolve()`
* turns it into e.g. `C:\\foo`. That is wrong for a session whose cwd is a
* WSL UNC path: in that namespace `/foo` means the distro's Linux `/foo`.
* Project only that unambiguous combination onto the matching distro root;
* drive paths, UNC paths, ordinary Windows sessions and non-Windows hosts
* keep their existing semantics.
* It is equally wrong for a dsh-remote mirror session, whose cwd is a local
* directory (`...\\.dsh\\remote-workspaces\\<host>\\<workspace>`) standing in
* for a remote POSIX workspace: there `/srv/app/src/a.ts` means the mirrored
* file, not `C:\\srv\\app\\src\\a.ts` (which does not exist — the symptom is
* `ENOENT ... realpath 'C:\\Users\\...'`).
*
* Workspace containment is intentionally NOT handled here. A projected path
* such as `/tmp/x` can still be rejected later for lying outside the session
* workspace; the important part is that it is checked as WSL `/tmp/x`, not
* silently redirected to `C:\\tmp\\x`.
* Project only those unambiguous combinations onto the matching root; drive
* paths, UNC paths, ordinary Windows sessions and non-Windows hosts keep
* their existing semantics.
*
* What happens AFTER projection is the caller's business (the old workspace
* fence is gone; `resolveTarget` only normalizes). The important part for a
* WSL session is that `/tmp/x` is read as WSL `/tmp/x`, not silently
* redirected to `C:\\tmp\\x`. For a mirror session a remote path OUTSIDE the
* mirrored workspace (e.g. `/etc/hosts`) is deliberately left unprojected:
* it stays slash-rooted, `resolve()` then drive-roots it and the request
* fails as a missing local file — it is never mapped onto an unrelated file
* inside the mirror.
*/
export function resolveSessionPath(
cwd: string,
@@ -26,12 +106,28 @@ export function resolveSessionPath(
if (platform !== 'win32' || !/^\/(?!\/)/.test(target)) return target
// Session cwd can be spelled with either separator style. Normalize only
// for detection; the returned host path is always canonical win32 UNC.
// for detection; the returned host path is always canonical win32.
const normalizedCwd = cwd.replace(/\//g, '\\')
const match = WSL_LOCALHOST_ROOT.exec(normalizedCwd)
if (match === null) return target
const wsl = WSL_LOCALHOST_ROOT.exec(normalizedCwd)
if (wsl !== null) {
const distroRoot = `\\\\wsl.localhost\\${wsl[1]}`
const relative = target.slice(1).replace(/\//g, '\\')
return win32.resolve(distroRoot, relative)
}
const distroRoot = `\\\\wsl.localhost\\${match[1]}`
const relative = target.slice(1).replace(/\//g, '\\')
return win32.resolve(distroRoot, relative)
// A dsh-remote mirror: map the remote workspace path onto the local mirror
// root. Only paths inside the mirrored workspace are projected.
const mirror = REMOTE_MIRROR_ROOT.exec(normalizedCwd)
if (mirror !== null) {
const mirrorRoot = mirror[1]!
const remotePath = remotePathOf(mirrorRoot)
if (remotePath !== undefined) {
const relative = relativeUnderPosix(remotePath, target)
if (relative !== undefined) {
return relative === '' ? win32.resolve(mirrorRoot) : win32.resolve(mirrorRoot, relative.replace(/\//g, '\\'))
}
}
}
return target
}
+84 -1
View File
@@ -1,4 +1,7 @@
import { describe, expect, it } from 'vitest'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { resolveSessionPath } from '../src/session-path.ts'
const WSL_CWD = '\\\\wsl.localhost\\archlinux\\home\\zdaar\\project'
@@ -48,3 +51,83 @@ describe('resolveSessionPath', () => {
.toBe('\\\\wsl.localhost\\Ubuntu\\home\\me\\project\\a.ts')
})
})
/**
* dsh-remote mirror sessions: the session cwd is a LOCAL directory standing
* in for a remote POSIX workspace. A remote path must land inside the mirror,
* never on the current drive (the `ENOENT ... realpath 'C:\\...'` symptom).
*/
describe('resolveSessionPath (dsh-remote mirror)', () => {
let dshHome: string
let mirrorRoot: string
const REMOTE_PATH = '/Users/yangheng/Project/claude/CBI_CT/civiapp_main'
beforeAll(() => {
dshHome = mkdtempSync(join(tmpdir(), 'dsh-session-path-'))
mirrorRoot = join(dshHome, '.dsh', 'remote-workspaces', '192.168.8.6-yangheng-22', 'civiapp_main')
mkdirSync(mirrorRoot, { recursive: true })
writeFileSync(
join(mirrorRoot, '.dsh-remote-meta.json'),
JSON.stringify({ host: '192.168.8.6', port: 22, username: 'yangheng', remotePath: REMOTE_PATH }),
)
})
afterAll(() => {
rmSync(dshHome, { recursive: true, force: true })
})
it('maps a remote workspace file onto the local mirror', () => {
expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}/src/a.ts`, 'win32'))
.toBe(join(mirrorRoot, 'src', 'a.ts'))
})
it('maps the remote workspace root itself onto the mirror root', () => {
expect(resolveSessionPath(mirrorRoot, REMOTE_PATH, 'win32')).toBe(mirrorRoot)
})
it('maps for a session nested inside the mirror', () => {
const nested = join(mirrorRoot, 'packages', 'api')
expect(resolveSessionPath(nested, `${REMOTE_PATH}/src/a.ts`, 'win32'))
.toBe(join(mirrorRoot, 'src', 'a.ts'))
})
it('leaves a remote path OUTSIDE the mirrored workspace unprojected', () => {
// Deliberately NOT mapped: projecting it would invent an unrelated local
// file. It stays a slash-rooted path — downstream `resolve()` drive-roots
// it (`C:\etc\hosts`) and the request fails as a missing local file.
expect(resolveSessionPath(mirrorRoot, '/etc/hosts', 'win32')).toBe('/etc/hosts')
})
it('does not treat a workspace whose name merely prefixes another as inside it', () => {
expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}_backup/a.ts`, 'win32'))
.toBe(`${REMOTE_PATH}_backup/a.ts`)
})
it('normalizes dot segments without escaping the mirror root', () => {
expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}/src/../lib/a.ts`, 'win32'))
.toBe(join(mirrorRoot, 'lib', 'a.ts'))
})
it('preserves Windows drive paths in a mirror session', () => {
const target = 'C:\\Users\\yangheng\\file.md'
expect(resolveSessionPath(mirrorRoot, target, 'win32')).toBe(target)
})
it('leaves paths alone when the mirror has no metadata file', () => {
const bare = join(dshHome, '.dsh', 'remote-workspaces', 'host-key', 'no-meta')
mkdirSync(bare, { recursive: true })
expect(resolveSessionPath(bare, '/srv/app/a.ts', 'win32')).toBe('/srv/app/a.ts')
})
it('leaves paths alone when the metadata is malformed', () => {
const broken = join(dshHome, '.dsh', 'remote-workspaces', 'host-key', 'broken-meta')
mkdirSync(broken, { recursive: true })
writeFileSync(join(broken, '.dsh-remote-meta.json'), '{ not json')
expect(resolveSessionPath(broken, '/srv/app/a.ts', 'win32')).toBe('/srv/app/a.ts')
})
it('does not reinterpret paths for a mirror session on non-Windows hosts', () => {
expect(resolveSessionPath(mirrorRoot, `${REMOTE_PATH}/src/a.ts`, 'linux'))
.toBe(`${REMOTE_PATH}/src/a.ts`)
})
})