fix: support WSL explorer and spaced markdown links

This commit is contained in:
t3-code[bot] committed 2026-08-15 02:51:33 +00:00
1 parent be23cedeb9
commit 31f5484bc3
5 files changed
+143 -29

No files matched your search

@@ -457,6 +457,48 @@ it.effect("does not advertise a file manager on headless Linux", () =>
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("uses Windows Explorer from WSL without WSLg", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-wsl-explorer-" });
const commandPath = path.join(binDir, "explorer.exe");
const targetPath = path.join(binDir, "project with spaces", "src", "index.ts");
yield* fileSystem.writeFileString(commandPath, "#!/bin/sh\n");
yield* fileSystem.chmod(commandPath, 0o755);
yield* fileSystem.makeDirectory(path.dirname(targetPath), { recursive: true });
yield* fileSystem.writeFileString(targetPath, "");
let spawned: ChildProcess.StandardCommand | undefined;
const env = { PATH: binDir, WSL_DISTRO_NAME: "Ubuntu-22.04" };
const editors = yield* Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const availableEditors = yield* launcher.resolveAvailableEditors();
yield* launcher.revealInFileManager({ path: targetPath });
return availableEditors;
}).pipe(
Effect.provide(
testLayer({
platform: "linux",
env,
onSpawn: (command) => {
spawned = command;
},
}),
),
);
assert.equal(editors.includes("file-manager"), true);
assert.ok(spawned);
assert.equal(spawned.command, "explorer.exe");
assert.deepEqual(spawned.args, [
"/select,",
`\\\\wsl.localhost\\Ubuntu-22.04${targetPath.replaceAll("/", "\\")}`,
]);
assert.equal(spawned.options.shell, false);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("advertises a file manager in a Linux graphical session", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
+56 -12
View File
@@ -67,6 +67,7 @@ interface TargetPathAndPosition {
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
const WSL_DISTRO_NAME_PATTERN = /^\w(?:[\w .-]*\w)?$/;
const POWERSHELL_ARGUMENTS_PREFIX = [
"-NoProfile",
"-NonInteractive",
@@ -109,9 +110,12 @@ const CommandLookupEnvConfig = Config.all({
PATHEXT: Config.string("PATHEXT").pipe(Config.option),
DISPLAY: Config.string("DISPLAY").pipe(Config.option),
WAYLAND_DISPLAY: Config.string("WAYLAND_DISPLAY").pipe(Config.option),
WSL_DISTRO_NAME: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
WSL_INTEROP: Config.string("WSL_INTEROP").pipe(Config.option),
SSH_CONNECTION: Config.string("SSH_CONNECTION").pipe(Config.option),
SSH_TTY: Config.string("SSH_TTY").pipe(Config.option),
SESSIONNAME: Config.string("SESSIONNAME").pipe(Config.option),
container: Config.string("container").pipe(Config.option),
}).pipe(Config.map(compactEnv));
const readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));
@@ -229,11 +233,29 @@ function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLa
};
}
function resolveWslDistroName(env: NodeJS.ProcessEnv): string | undefined {
const distroName = env.WSL_DISTRO_NAME?.trim();
return distroName && WSL_DISTRO_NAME_PATTERN.test(distroName) ? distroName : undefined;
}
function shouldUseWindowsFileManagerFromWsl(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): boolean {
return (
shouldUseWindowsBrowserFromWsl(platform, env) &&
!env.DISPLAY?.trim() &&
!env.WAYLAND_DISPLAY?.trim() &&
resolveWslDistroName(env) !== undefined
);
}
function hasGraphicalFileManagerSession(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): boolean {
if (env.SSH_CONNECTION?.trim() || env.SSH_TTY?.trim()) return false;
if (shouldUseWindowsFileManagerFromWsl(platform, env)) return true;
if (platform === "linux") {
return Boolean(env.DISPLAY?.trim() || env.WAYLAND_DISPLAY?.trim());
}
@@ -247,6 +269,12 @@ function normalizeWindowsFileManagerPath(target: string): string {
return target.replaceAll("/", "\\");
}
function resolveWslFileManagerPath(target: string, env: NodeJS.ProcessEnv): string {
const distroName = resolveWslDistroName(env);
if (!distroName) return target;
return `\\\\wsl.localhost\\${distroName}${normalizeWindowsFileManagerPath(target)}`;
}
function fileManagerFolderPath(platform: NodeJS.Platform, target: string, path: Path.Path): string {
if (platform !== "win32") return path.dirname(target);
@@ -262,14 +290,21 @@ function fileManagerRevealArgs(
target: string,
targetExists: boolean,
path: Path.Path,
env: NodeJS.ProcessEnv,
): ReadonlyArray<string> {
if (shouldUseWindowsFileManagerFromWsl(platform, env)) {
const revealTarget = targetExists ? target : fileManagerFolderPath(platform, target, path);
const windowsTarget = resolveWslFileManagerPath(revealTarget, env);
return targetExists ? ["/select,", windowsTarget] : [windowsTarget];
}
if (!targetExists) return [fileManagerFolderPath(platform, target, path)];
if (platform === "darwin") return ["-R", target];
if (platform === "win32") return ["/select,", normalizeWindowsFileManagerPath(target)];
return [fileManagerFolderPath(platform, target, path)];
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
function fileManagerCommandForPlatform(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string {
if (shouldUseWindowsFileManagerFromWsl(platform, env)) return "explorer.exe";
switch (platform) {
case "darwin":
return "open";
@@ -317,7 +352,7 @@ const buildAvailableEditors = Effect.fn("externalLauncher.buildAvailableEditors"
for (const editor of EDITORS) {
if (editor.commands === null) {
if (!hasGraphicalFileManagerSession(platform, env)) continue;
const command = fileManagerCommandForPlatform(platform);
const command = fileManagerCommandForPlatform(platform, env);
if (yield* isCommandAvailable(command, { env })) {
available.push(editor.id);
}
@@ -427,11 +462,19 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });
}
const path = yield* Path.Path;
const target = shouldUseWindowsFileManagerFromWsl(platform, env)
? path.resolve(input.cwd)
: input.cwd;
return {
editor: editorDef.id,
target: input.cwd,
command: fileManagerCommandForPlatform(platform),
args: [input.cwd],
target,
command: fileManagerCommandForPlatform(platform, env),
args: [
shouldUseWindowsFileManagerFromWsl(platform, env)
? resolveWslFileManagerPath(target, env)
: target,
],
};
});
@@ -446,20 +489,21 @@ const resolveFileManagerRevealLaunch = Effect.fn("externalLauncher.resolveFileMa
}
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const targetExists = yield* fileSystem
.exists(input.path)
.pipe(Effect.orElseSucceed(() => false));
const args = fileManagerRevealArgs(platform, input.path, targetExists, path);
const target = shouldUseWindowsFileManagerFromWsl(platform, env)
? path.resolve(input.path)
: input.path;
const targetExists = yield* fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false));
const args = fileManagerRevealArgs(platform, target, targetExists, path, env);
yield* Effect.annotateCurrentSpan({
"externalLauncher.target": input.path,
"externalLauncher.target": target,
"externalLauncher.platform": platform,
});
return {
editor: "file-manager",
target: input.path,
command: fileManagerCommandForPlatform(platform),
target,
command: fileManagerCommandForPlatform(platform, env),
args,
};
},
+2 -17
View File
@@ -79,7 +79,8 @@ import {
} from "../markdown-clipboard";
import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation";
import {
normalizeMarkdownLinkDestination,
extractMarkdownLinkHrefs,
normalizeMarkdownLinkHrefKey,
resolveInlineCodeFileLinkMeta,
resolveMarkdownFileLinkMeta,
rewriteMarkdownFileUriHref,
@@ -805,7 +806,6 @@ interface MarkdownFileLinkProps {
className?: string | undefined;
}
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
const MARKDOWN_FILE_LINK_CLASS_NAME =
"chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70";
@@ -884,21 +884,6 @@ function extractInlineCodeSpans(text: string): string[] {
return spans;
}
function extractMarkdownLinkHrefs(text: string): string[] {
const hrefs: string[] = [];
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
const href = match[1]?.trim();
if (!href) continue;
hrefs.push(href);
}
return hrefs;
}
function normalizeMarkdownLinkHrefKey(href: string): string {
const normalizedHref = normalizeMarkdownLinkDestination(href);
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
}
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
+23
View File
@@ -1,12 +1,35 @@
import { describe, expect, it } from "vite-plus/test";
import {
extractMarkdownLinkHrefs,
normalizeMarkdownLinkDestination,
normalizeMarkdownLinkHrefKey,
resolveInlineCodeFileLinkMeta,
resolveMarkdownFileLinkMeta,
resolveMarkdownFileLinkTarget,
rewriteMarkdownFileUriHref,
} from "./markdown-links";
describe("extractMarkdownLinkHrefs", () => {
it("extracts angle-bracketed destinations containing spaces", () => {
const [href] = extractMarkdownLinkHrefs('[file](<src/file name.ts> "source")');
expect(href).toBe("<src/file name.ts>");
expect(normalizeMarkdownLinkHrefKey(href ?? "")).toBe(
normalizeMarkdownLinkHrefKey("src/file%20name.ts"),
);
expect(
resolveMarkdownFileLinkMeta(normalizeMarkdownLinkDestination(href ?? ""), "/repo/project"),
).toMatchObject({
filePath: "/repo/project/src/file name.ts",
});
});
it("continues to extract regular markdown destinations", () => {
expect(extractMarkdownLinkHrefs("[file](src/file%20name.ts)")).toEqual(["src/file%20name.ts"]);
});
});
describe("rewriteMarkdownFileUriHref", () => {
it("rewrites file uri hrefs into direct path hrefs", () => {
expect(rewriteMarkdownFileUriHref("file:///Users/julius/project/src/main.ts#L42")).toBe(
+20
View File
@@ -9,6 +9,7 @@ const RELATIVE_FILE_PATH_PATTERN = /^[A-Za-z0-9._ -]+(?:\/[A-Za-z0-9._ -]+)+(?::
const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._ -]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(\s*(<[^>\n]+>|[^)\s]+)(?:\s+["'][^"']*["'])?\s*\)/g;
// Standard OS and dev-container roots; deliberately excludes app-route-ish
// prefixes like /app/ or /chat/ so SPA routes never read as files.
const POSIX_FILE_ROOT_PREFIXES = [
@@ -64,6 +65,15 @@ export function normalizeMarkdownLinkDestination(value: string): string {
return unwrapMarkdownLinkDestination(value.trim());
}
export function extractMarkdownLinkHrefs(text: string): string[] {
const hrefs: string[] = [];
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
const href = match[1]?.trim();
if (href) hrefs.push(href);
}
return hrefs;
}
function stripSearchAndHash(value: string): { path: string; hash: string } {
const hashIndex = value.indexOf("#");
const pathWithSearch = hashIndex >= 0 ? value.slice(0, hashIndex) : value;
@@ -108,6 +118,16 @@ export function rewriteMarkdownFileUriHref(href: string | undefined): string | n
return `${target.path}${target.hash}`;
}
export function normalizeMarkdownLinkHrefKey(href: string): string {
const normalizedHref = normalizeMarkdownLinkDestination(href);
const rewrittenHref = rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
try {
return encodeURI(rewrittenHref).replace(/%25(?=[0-9A-Fa-f]{2})/g, "%");
} catch {
return rewrittenHref;
}
}
function looksLikePosixFilesystemPath(path: string): boolean {
if (!path.startsWith("/")) return false;
if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;