Skip to content

Commit 35ef0a6

Browse files
committed
fix(terminal): harden abort guard, add WSL UNC path conversion, and improve test coverage (#321)
- Guard sendText("\x03") inside aborting gate in TerminalProcess.ts to prevent overlapping retry loops when abort() is called repeatedly - Add 3-tier WSL path conversion and execaShellPath override in ExecaTerminalProcess.ts (drive-letter → WSL UNC strip → wslpath fallback), with POSIX early-return guard to avoid unnecessary wslpath call for already-POSIX paths - Add 14 tests for Terminal constructor and streamAvailable timeout test in Terminal.spec.ts / TerminalProcess.spec.ts; add 4 tests for WSL UNC path conversion and execaShellPath override in ExecaTerminalProcess.spec.ts; extract console.error spy to describe-level beforeEach/afterEach in TerminalProcess.spec.ts
1 parent b871106 commit 35ef0a6

5 files changed

Lines changed: 504 additions & 37 deletions

File tree

‎src/integrations/terminal/ExecaTerminalProcess.ts‎

Lines changed: 51 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,48 @@ import { BaseTerminal } from "./BaseTerminal"
77
import { BaseTerminalProcess } from "./BaseTerminalProcess"
88
import { getShell, WSL_EXE_PATH } from "../../utils/shell"
99

10+
// Matches \\wsl$\Distro\... and \\wsl.localhost\Distro\...
11+
const WSL_UNC_PREFIX = /^\/\/wsl(?:\$|\.localhost)\/([^\/]+)\/?(.*)$/i
12+
13+
async function convertWindowsPathToWsl(windowsPath: string): Promise<string | null> {
14+
const forward = windowsPath.replace(/\\/g, "/")
15+
16+
// Already a POSIX/WSL path — no Windows-to-WSL conversion needed.
17+
// This guard avoids an unnecessary wsl.exe wslpath call (≤5 s timeout)
18+
// for paths that don't need conversion. In production,
19+
// getCurrentWorkingDirectory() always returns Windows-style paths when
20+
// isWslShell is true, so this is a defensive measure for future callers.
21+
if (forward.startsWith("/") && !forward.startsWith("//")) {
22+
return forward
23+
}
24+
25+
// Tier 1: Drive-letter → /mnt/<drive>/
26+
const driveMatch = forward.match(/^([A-Za-z]):\/(.*)/)
27+
if (driveMatch) {
28+
return `/mnt/${driveMatch[1].toLowerCase()}/${driveMatch[2]}`
29+
}
30+
31+
// Tier 2: WSL UNC → strip prefix
32+
const uncMatch = forward.match(WSL_UNC_PREFIX)
33+
if (uncMatch) {
34+
const subPath = uncMatch[2] || ""
35+
return subPath.startsWith("/") ? subPath : `/${subPath}`
36+
}
37+
38+
// Tier 3: Arbitrary UNC → wslpath fallback
39+
try {
40+
const { stdout } = await execa(WSL_EXE_PATH, ["wslpath", windowsPath], {
41+
timeout: 5_000,
42+
stdin: "ignore",
43+
})
44+
const wslPath = stdout.trim()
45+
return wslPath || null
46+
} catch {
47+
console.warn(`[ExecaTerminalProcess] wslpath failed for "${windowsPath}"`)
48+
return null
49+
}
50+
}
51+
1052
export class ExecaTerminalProcess extends BaseTerminalProcess {
1153
private terminalRef: WeakRef<RooTerminal>
1254
private aborted = false
@@ -40,26 +82,21 @@ export class ExecaTerminalProcess extends BaseTerminalProcess {
4082
try {
4183
this.isHot = true
4284

43-
const resolvedShell = BaseTerminal.getExecaShellPath() || getShell()
44-
const isWslShell = resolvedShell === WSL_EXE_PATH
85+
const execaShellPath = BaseTerminal.getExecaShellPath()
86+
const resolvedShell = execaShellPath || getShell()
4587

46-
let effectiveShell: string | boolean = resolvedShell
47-
let effectiveCommand = command
88+
// WSL detection only applies when the user has NOT set an explicit execa shell.
89+
const isWslShell = execaShellPath ? false : resolvedShell === WSL_EXE_PATH
4890

4991
if (isWslShell) {
5092
// Spawn wsl.exe directly (not through cmd.exe) to avoid nested-quoting issues.
5193
// execa(file, args, options) passes args as an array — no shell interpretation.
5294
const windowsCwd = this.terminal.getCurrentWorkingDirectory()
53-
const forwardSlashedCwd = windowsCwd.replace(/\\/g, "/")
54-
const wslCwd = forwardSlashedCwd.replace(
55-
/^([A-Za-z]):\//,
56-
(_, drive: string) => `/mnt/${drive.toLowerCase()}/`,
57-
)
95+
const wslCwd = await convertWindowsPathToWsl(windowsCwd)
5896

5997
const wslArgs = ["--", "bash", "-c", command]
6098

61-
if (wslCwd !== forwardSlashedCwd) {
62-
// Drive path successfully converted — use --cd to set WSL working directory
99+
if (wslCwd) {
63100
wslArgs.unshift("--cd", wslCwd)
64101
}
65102

@@ -75,7 +112,7 @@ export class ExecaTerminalProcess extends BaseTerminalProcess {
75112
})
76113
} else {
77114
this.subprocess = execa({
78-
shell: effectiveShell,
115+
shell: resolvedShell,
79116
cwd: this.terminal.getCurrentWorkingDirectory(),
80117
all: true,
81118
stdin: "ignore",
@@ -84,7 +121,7 @@ export class ExecaTerminalProcess extends BaseTerminalProcess {
84121
LANG: "en_US.UTF-8",
85122
LC_ALL: "en_US.UTF-8",
86123
},
87-
})`${effectiveCommand}`
124+
})`${command}`
88125
}
89126

90127
this.pid = this.subprocess.pid
@@ -145,7 +182,7 @@ export class ExecaTerminalProcess extends BaseTerminalProcess {
145182
timeoutId = setTimeout(() => {
146183
try {
147184
this.subprocess?.kill("SIGKILL")
148-
} catch (e) { }
185+
} catch (e) {}
149186

150187
resolve()
151188
}, 5_000)

‎src/integrations/terminal/TerminalProcess.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@ import { Terminal } from "./Terminal"
55
export class TerminalProcess extends BaseTerminalProcess {
66
// #266: Some processes (interactive tools, programs that trap SIGINT and
77
// prompt for confirmation) need more than one Ctrl+C to actually exit. We
8-
// send Ctrl+C up to this many times in TOTAL — the immediate send in abort()
9-
// plus retries — checking between sends whether the process has exited, before
10-
// giving up and letting dispose() proceed.
8+
// send Ctrl+C up to this many times in TOTAL. We check between sends whether
9+
// the process has exited, before giving up and letting dispose() proceed.
1110
private static readonly CTRL_C_SEND_LIMIT = 3
1211
// Delay between Ctrl+C re-sends. Kept short so cancel stays responsive; the
1312
// retry window is bounded by (CTRL_C_SEND_LIMIT - 1) * ABORT_RETRY_DELAY_MS.
@@ -251,17 +250,15 @@ export class TerminalProcess extends BaseTerminalProcess {
251250
return
252251
}
253252

254-
// Send SIGINT using CTRL+C.
255-
this.terminal.terminal.sendText("\x03")
256-
257253
// #266: A single Ctrl+C isn't always enough — some processes trap SIGINT
258254
// and keep running. Kick off a bounded retry that re-sends Ctrl+C a few
259-
// times, verifying between attempts whether the process actually exited
260-
// (terminal.busy flips to false on completion). This is intentionally
261-
// fire-and-forget so it never blocks the synchronous cancel path; the
262-
// total retry window is bounded so dispose() is never delayed for long.
255+
// times, verifying between attempts whether the process actually exited.
256+
// The aborting guard prevents duplicate Ctrl+C sends and overlapping retry
257+
// loops from concurrent abort() calls — JS single-thread guarantees the
258+
// check + set below are atomic (no await between them).
263259
if (!this.aborting) {
264260
this.aborting = true
261+
this.terminal.terminal.sendText("\x03")
265262
void this.retryAbort()
266263
.finally(() => {
267264
this.aborting = false

‎src/integrations/terminal/__tests__/ExecaTerminalProcess.spec.ts‎

Lines changed: 111 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ vitest.mock("execa", () => {
1818
}
1919
return (_template: TemplateStringsArray, ..._tArgs: any[]) => makeResult()
2020
})
21-
return { execa, ExecaError: class extends Error { } }
21+
return { execa, ExecaError: class extends Error {} }
2222
})
2323

2424
vitest.mock("ps-tree", () => ({
@@ -144,6 +144,112 @@ describe("ExecaTerminalProcess", () => {
144144
}),
145145
)
146146
})
147+
148+
// Fix 3: execaShellPath should override WSL shell detection
149+
it("should use execaShellPath instead of WSL when both are set", async () => {
150+
BaseTerminal.setExecaShellPath("/bin/git-bash")
151+
vitest.mocked(shellUtils.getShell).mockReturnValue(WSL_EXE_PATH)
152+
vitest.mocked(mockTerminal.getCurrentWorkingDirectory).mockReturnValue("C:/test/cwd")
153+
154+
await terminalProcess.run("echo test")
155+
156+
const execaMock = vitest.mocked(execa)
157+
expect(execaMock).toHaveBeenCalledWith(
158+
expect.objectContaining({
159+
shell: "/bin/git-bash",
160+
cwd: "C:/test/cwd",
161+
}),
162+
)
163+
})
164+
165+
// Fix 1: WSL UNC path stripping (\\wsl$\Distro\path → /path)
166+
it("should convert \\\\wsl$\\ UNC path to WSL internal path", async () => {
167+
vitest.mocked(shellUtils.getShell).mockReturnValue(WSL_EXE_PATH)
168+
BaseTerminal.setExecaShellPath(undefined)
169+
vitest.mocked(mockTerminal.getCurrentWorkingDirectory).mockReturnValue("\\\\wsl$\\Ubuntu\\home\\project")
170+
171+
await terminalProcess.run("echo test")
172+
173+
const execaMock = vitest.mocked(execa)
174+
expect(execaMock).toHaveBeenCalledWith(
175+
WSL_EXE_PATH,
176+
["--cd", "/home/project", "--", "bash", "-c", "echo test"],
177+
expect.any(Object),
178+
)
179+
})
180+
181+
// Fix 1: wslpath fallback for non-WSL UNC paths
182+
it("should use wslpath fallback for non-WSL UNC paths", async () => {
183+
vitest.mocked(shellUtils.getShell).mockReturnValue(WSL_EXE_PATH)
184+
BaseTerminal.setExecaShellPath(undefined)
185+
vitest.mocked(mockTerminal.getCurrentWorkingDirectory).mockReturnValue("\\\\fileserver\\share\\project")
186+
187+
const mockKill = vitest.fn()
188+
const mockIterable = (_opts: any) =>
189+
(async function* () {
190+
yield "test output\n"
191+
})()
192+
vitest.mocked(execa).mockReset()
193+
vitest
194+
.mocked(execa)
195+
.mockReturnValueOnce({
196+
pid: mockPid,
197+
stdout: "/mnt/share/project\n",
198+
iterable: mockIterable,
199+
kill: mockKill,
200+
} as any)
201+
.mockReturnValueOnce({
202+
pid: mockPid + 1,
203+
iterable: mockIterable,
204+
kill: mockKill,
205+
} as any)
206+
207+
await terminalProcess.run("echo test")
208+
209+
const execaMock = vitest.mocked(execa)
210+
expect(execaMock).toHaveBeenNthCalledWith(
211+
1,
212+
WSL_EXE_PATH,
213+
["wslpath", "\\\\fileserver\\share\\project"],
214+
expect.objectContaining({ timeout: 5_000 }),
215+
)
216+
expect(execaMock).toHaveBeenNthCalledWith(
217+
2,
218+
WSL_EXE_PATH,
219+
["--cd", "/mnt/share/project", "--", "bash", "-c", "echo test"],
220+
expect.any(Object),
221+
)
222+
})
223+
224+
// Fix 1: skip --cd when wslpath fails
225+
it("should skip --cd when wslpath fails", async () => {
226+
vitest.mocked(shellUtils.getShell).mockReturnValue(WSL_EXE_PATH)
227+
BaseTerminal.setExecaShellPath(undefined)
228+
vitest.mocked(mockTerminal.getCurrentWorkingDirectory).mockReturnValue("\\\\fileserver\\share\\project")
229+
230+
vitest.mocked(execa).mockReset()
231+
vitest
232+
.mocked(execa)
233+
.mockRejectedValueOnce(new Error("wslpath failed"))
234+
.mockReturnValueOnce({
235+
pid: mockPid,
236+
iterable: (_opts: any) =>
237+
(async function* () {
238+
yield "test output\n"
239+
})(),
240+
kill: vitest.fn(),
241+
} as any)
242+
243+
await terminalProcess.run("echo test")
244+
245+
const execaMock = vitest.mocked(execa)
246+
expect(execaMock).toHaveBeenNthCalledWith(
247+
2,
248+
WSL_EXE_PATH,
249+
["--", "bash", "-c", "echo test"],
250+
expect.any(Object),
251+
)
252+
})
147253
})
148254

149255
describe("basic functionality", () => {
@@ -177,7 +283,7 @@ describe("ExecaTerminalProcess", () => {
177283
it("clears buffer when all output has been retrieved", () => {
178284
terminalProcess["fullOutput"] = "test output data"
179285
terminalProcess["lastRetrievedIndex"] = 16
180-
; (terminalProcess as any).trimRetrievedOutput()
286+
;(terminalProcess as any).trimRetrievedOutput()
181287

182288
expect(terminalProcess["fullOutput"]).toBe("")
183289
expect(terminalProcess["lastRetrievedIndex"]).toBe(0)
@@ -186,7 +292,7 @@ describe("ExecaTerminalProcess", () => {
186292
it("does not clear buffer when there is unretrieved output", () => {
187293
terminalProcess["fullOutput"] = "test output data"
188294
terminalProcess["lastRetrievedIndex"] = 5
189-
; (terminalProcess as any).trimRetrievedOutput()
295+
;(terminalProcess as any).trimRetrievedOutput()
190296

191297
expect(terminalProcess["fullOutput"]).toBe("test output data")
192298
expect(terminalProcess["lastRetrievedIndex"]).toBe(5)
@@ -195,7 +301,7 @@ describe("ExecaTerminalProcess", () => {
195301
it("does nothing when buffer is already empty", () => {
196302
terminalProcess["fullOutput"] = ""
197303
terminalProcess["lastRetrievedIndex"] = 0
198-
; (terminalProcess as any).trimRetrievedOutput()
304+
;(terminalProcess as any).trimRetrievedOutput()
199305

200306
expect(terminalProcess["fullOutput"]).toBe("")
201307
expect(terminalProcess["lastRetrievedIndex"]).toBe(0)
@@ -204,7 +310,7 @@ describe("ExecaTerminalProcess", () => {
204310
it("clears buffer when lastRetrievedIndex exceeds fullOutput length", () => {
205311
terminalProcess["fullOutput"] = "short"
206312
terminalProcess["lastRetrievedIndex"] = 100
207-
; (terminalProcess as any).trimRetrievedOutput()
313+
;(terminalProcess as any).trimRetrievedOutput()
208314

209315
expect(terminalProcess["fullOutput"]).toBe("")
210316
expect(terminalProcess["lastRetrievedIndex"]).toBe(0)

0 commit comments

Comments
 (0)