Skip to content

Commit 2f4e5d2

Browse files
committed
fix(terminal): fix Windows CI test timing and improve coverage
1 parent e42946b commit 2f4e5d2

4 files changed

Lines changed: 319 additions & 9 deletions

File tree

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

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,50 @@ describe("TerminalProcess", () => {
8888
}
8989
})
9090

91+
it("runs command after shell integration activates via onDidChangeTerminalShellIntegration event", async () => {
92+
// Cover Terminal.runCommand's waitForShellIntegration resolve path: shell
93+
// integration is initially absent but arrives via the VSCode event before timeout.
94+
let shellIntegrationHandler: ((e: any) => void) | undefined
95+
vi.spyOn(vscode.window, "onDidChangeTerminalShellIntegration" as any).mockImplementation((handler: any) => {
96+
shellIntegrationHandler = handler
97+
return { dispose: vi.fn() }
98+
})
99+
100+
mockTerminal.shellIntegration = undefined
101+
const runPromise = mockTerminalInfo.runCommand("test command", {
102+
onLine: vi.fn(),
103+
onCompleted: vi.fn(),
104+
onShellExecutionStarted: vi.fn(),
105+
onShellExecutionComplete: vi.fn(),
106+
})
107+
108+
// Fire the shell integration activation event — simulates VSCode telling us the
109+
// shell is ready. waitForShellIntegration should resolve, then process.run() fires.
110+
expect(shellIntegrationHandler).toBeDefined()
111+
mockTerminal.shellIntegration = {
112+
executeCommand: vi.fn().mockReturnValue({ read: vi.fn().mockReturnValue((async function* () {})()) }),
113+
}
114+
shellIntegrationHandler!({ terminal: mockTerminal })
115+
116+
// Give the .then() callback a chance to run process.run()
117+
await Promise.resolve()
118+
await Promise.resolve()
119+
120+
// process.run() should have been called (shell integration is now present, so
121+
// run() won't take the !isShellIntegrationAvailable path)
122+
await Promise.resolve()
123+
terminalProcess.emit(
124+
"stream_available",
125+
(async function* () {
126+
yield "\x1b]633;C\x07"
127+
yield "\x1b]633;D\x07"
128+
})(),
129+
)
130+
setTimeout(() => terminalProcess.emit("shell_execution_complete", { exitCode: 0 }), 0)
131+
132+
await runPromise
133+
})
134+
91135
it("handles shell integration commands correctly", async () => {
92136
let lines: string[] = []
93137

@@ -338,6 +382,46 @@ describe("TerminalProcess", () => {
338382
consoleWarnSpy.mockRestore()
339383
})
340384

385+
it("emits no_shell_integration with commandSubmitted=true when stream never arrives after command submission", async () => {
386+
vi.useFakeTimers()
387+
const prevTimeout = Terminal.getShellIntegrationTimeout()
388+
Terminal.setShellIntegrationTimeout(50)
389+
390+
try {
391+
let commandSubmitted: boolean | undefined
392+
let completedOutput: string | undefined
393+
394+
const done = Promise.all([
395+
new Promise<void>((resolve) =>
396+
terminalProcess.once("no_shell_integration", (details) => {
397+
commandSubmitted = details.commandSubmitted
398+
resolve()
399+
}),
400+
),
401+
new Promise<void>((resolve) =>
402+
terminalProcess.once("completed", (output?: string) => {
403+
completedOutput = output
404+
resolve()
405+
}),
406+
),
407+
new Promise<void>((resolve) => terminalProcess.once("continue", resolve)),
408+
])
409+
410+
// run() submits the command (shell integration IS present) but stream_available
411+
// is never emitted, so the streamAvailable timeout fires.
412+
const runPromise = terminalProcess.run("test command")
413+
await vi.advanceTimersByTimeAsync(100)
414+
await runPromise
415+
await done
416+
417+
expect(commandSubmitted).toBe(true)
418+
expect(completedOutput).toContain("stream did not start")
419+
} finally {
420+
Terminal.setShellIntegrationTimeout(prevTimeout)
421+
vi.useRealTimers()
422+
}
423+
})
424+
341425
it("completes without warning when the execution stream is empty after submission", async () => {
342426
const noShellIntegrationSpy = vi.fn()
343427
let completedOutput: string | undefined
@@ -454,6 +538,102 @@ describe("TerminalProcess", () => {
454538
await completePromise
455539
expect(terminalProcess.isHot).toBe(false)
456540
})
541+
542+
it("resolves waitForShellIntegration immediately when shell integration is already active", async () => {
543+
// Cover waitForShellIntegration fast path: shellIntegration already present → resolves synchronously.
544+
// Access the private method via bracket notation so we can call it directly.
545+
mockTerminal.shellIntegration = { executeCommand: vi.fn() }
546+
const result = (mockTerminalInfo as any).waitForShellIntegration(5000)
547+
// Should resolve immediately (synchronously resolved Promise) without touching timers.
548+
await expect(result).resolves.toBeUndefined()
549+
})
550+
551+
it("handles executeCommand throwing by propagating the error", async () => {
552+
mockTerminal.shellIntegration.executeCommand.mockImplementation(() => {
553+
throw new Error("execution failed")
554+
})
555+
556+
await expect(terminalProcess.run("bad command")).rejects.toThrow("execution failed")
557+
})
558+
559+
it("self-finalizes via idle timeout when no stream data arrives and no event fires", async () => {
560+
vi.useFakeTimers()
561+
const prevTimeout = Terminal.getShellIntegrationTimeout()
562+
Terminal.setShellIntegrationTimeout(50)
563+
564+
try {
565+
const events: string[] = []
566+
const done = Promise.all([
567+
new Promise<void>((resolve) =>
568+
terminalProcess.once("completed", () => {
569+
events.push("completed")
570+
resolve()
571+
}),
572+
),
573+
new Promise<void>((resolve) =>
574+
terminalProcess.once("continue", () => {
575+
events.push("continue")
576+
resolve()
577+
}),
578+
),
579+
])
580+
581+
// An empty stream that never yields anything and never closes.
582+
// shellExecutionComplete never fires either — simulates a completely
583+
// silent command with no events (the idle-timeout self-finalize path).
584+
const neverEndingStream: AsyncIterable<string> = {
585+
[Symbol.asyncIterator]() {
586+
return {
587+
next(): Promise<IteratorResult<string>> {
588+
return new Promise(() => {}) // hangs forever
589+
},
590+
}
591+
},
592+
}
593+
594+
const runPromise = terminalProcess.run("silent command")
595+
terminalProcess.emit("stream_available", neverEndingStream)
596+
// Let the first idle timeout (3s) fire without shellExecutionStarted.
597+
// That keeps looping. Advance past getShellIntegrationTimeout (50ms) so
598+
// the "shell init timeout exceeded" branch fires and we fall through to break.
599+
await vi.advanceTimersByTimeAsync(3100)
600+
601+
await runPromise
602+
await done
603+
604+
expect(events).toContain("completed")
605+
} finally {
606+
Terminal.setShellIntegrationTimeout(prevTimeout)
607+
vi.useRealTimers()
608+
}
609+
})
610+
611+
it("passes a temp-script invocation to executeCommand for multiline POSIX commands when profile shell is set", async () => {
612+
vi.spyOn(Terminal, "getProfileShell").mockReturnValue({
613+
shellPath: "/bin/bash",
614+
shellArgs: undefined,
615+
})
616+
617+
const command = "echo a\necho b"
618+
const runPromise = terminalProcess.run(command)
619+
terminalProcess.emit(
620+
"stream_available",
621+
(async function* () {
622+
yield "\x1b]633;C\x07"
623+
yield "a\n"
624+
yield "b\n"
625+
yield "\x1b]633;D\x07"
626+
})(),
627+
)
628+
setTimeout(() => terminalProcess.emit("shell_execution_complete", { exitCode: 0 }), 0)
629+
630+
await runPromise
631+
632+
// executeCommand should be called with a shell + temp-script invocation, not the
633+
// raw multiline command string.
634+
const calledWith = mockTerminal.shellIntegration.executeCommand.mock.calls[0][0] as string
635+
expect(calledWith).toMatch(/^"\/bin\/bash" ".*roo-cmd-.*\.sh"$/)
636+
})
457637
})
458638

459639
describe("continue", () => {
@@ -594,6 +774,15 @@ describe("TerminalProcess", () => {
594774

595775
expect(terminalProcess["lastRetrievedIndex"]).toBe(terminalProcess["fullOutput"].length - "previous".length)
596776
})
777+
778+
it("trims at OSC 133;D when only a 133 end marker is present (no 633 marker)", () => {
779+
// Line 598: endIndex = index133 branch — only the 133 end marker exists.
780+
terminalProcess["fullOutput"] = "hello\x1b]133;D\x07world"
781+
terminalProcess["lastRetrievedIndex"] = 0
782+
783+
const unretrieved = terminalProcess.getUnretrievedOutput()
784+
expect(unretrieved).toBe("hello")
785+
})
597786
})
598787

599788
describe("interpretExitCode", () => {

‎src/integrations/terminal/__tests__/TerminalProcessExec.cmd.spec.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -185,13 +185,20 @@ async function testCmdCommand(
185185
}, 500)
186186
})
187187

188-
// Then trigger the end event, referencing the SAME execution object as above.
188+
// Trigger the end event after microtask-based stream consumption completes.
189+
// The stream yields chunks as microtasks (async generator); setTimeout(0)
190+
// fires after all pending microtasks, so all chunks (including the D marker)
191+
// will be consumed before this fires. Firing synchronously would let
192+
// DONE_SENTINEL win the Promise.race and skip unconsumed chunks.
189193
if (eventHandlers.endTerminalShellExecution) {
190-
eventHandlers.endTerminalShellExecution({
191-
terminal: mockTerminal,
192-
execution: mockExecution,
193-
exitCode: exitCode,
194-
})
194+
const _exitCode = exitCode
195+
setTimeout(() => {
196+
eventHandlers.endTerminalShellExecution({
197+
terminal: mockTerminal,
198+
execution: mockExecution,
199+
exitCode: _exitCode,
200+
})
201+
}, 0)
195202
}
196203

197204
// Store exit details for return

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

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,73 @@ describe("Terminal VS Code terminal profile (#277)", () => {
367367
expect(Terminal.isActiveShellPowerShell("win32")).toBe(true)
368368
})
369369
})
370+
371+
describe("isActiveShellFish", () => {
372+
it("returns false when a custom profile resolves to a non-fish shell", () => {
373+
stubProfiles({ linux: { "My Bash": { path: "/bin/bash" } } })
374+
Terminal.setTerminalProfile("My Bash")
375+
expect(Terminal.isActiveShellFish("linux")).toBe(false)
376+
})
377+
378+
it("returns true when a custom profile resolves to fish", () => {
379+
stubProfiles({ linux: { "Fish Shell": { path: "/usr/bin/fish" } } })
380+
Terminal.setTerminalProfile("Fish Shell")
381+
expect(Terminal.isActiveShellFish("linux")).toBe(true)
382+
})
383+
384+
it("returns false when no override and no default profile name is configured", () => {
385+
Terminal.setTerminalProfile(undefined)
386+
getConfigurationSpy = vi.spyOn(vscode.workspace, "getConfiguration").mockReturnValue({
387+
get: (_key: string, defaultValue?: unknown) => defaultValue,
388+
inspect: () => undefined,
389+
} as any)
390+
expect(Terminal.isActiveShellFish("linux")).toBe(false)
391+
})
392+
393+
it("returns false when the default profile entry is null", () => {
394+
Terminal.setTerminalProfile(undefined)
395+
getConfigurationSpy = vi
396+
.spyOn(vscode.workspace, "getConfiguration")
397+
.mockImplementation((section?: string) => {
398+
if (section === "terminal.integrated.profiles") {
399+
return {
400+
inspect: (_key: string) => ({ defaultValue: { "Fish Shell": null } }),
401+
} as any
402+
}
403+
if (section === "terminal.integrated") {
404+
return {
405+
inspect: (key: string) =>
406+
key === "defaultProfile.linux" ? { defaultValue: "Fish Shell" } : undefined,
407+
} as any
408+
}
409+
return { get: (_key: string, defaultValue?: unknown) => defaultValue } as any
410+
})
411+
expect(Terminal.isActiveShellFish("linux")).toBe(false)
412+
})
413+
414+
it("returns true when the default profile resolves to fish", () => {
415+
Terminal.setTerminalProfile(undefined)
416+
getConfigurationSpy = vi
417+
.spyOn(vscode.workspace, "getConfiguration")
418+
.mockImplementation((section?: string) => {
419+
if (section === "terminal.integrated.profiles") {
420+
return {
421+
inspect: (_key: string) => ({
422+
defaultValue: { "Fish Shell": { path: "/usr/local/bin/fish" } },
423+
}),
424+
} as any
425+
}
426+
if (section === "terminal.integrated") {
427+
return {
428+
inspect: (key: string) =>
429+
key === "defaultProfile.linux" ? { defaultValue: "Fish Shell" } : undefined,
430+
} as any
431+
}
432+
return { get: (_key: string, defaultValue?: unknown) => defaultValue } as any
433+
})
434+
expect(Terminal.isActiveShellFish("linux")).toBe(true)
435+
})
436+
})
370437
})
371438

372439
describe("getProfileShell", () => {

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

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ describe("TerminalRegistry", () => {
207207
})
208208

209209
describe("onDidEndTerminalShellExecution race condition (#489, #622)", () => {
210+
let startHandler: (e: any) => Promise<void>
210211
let endHandler: (e: any) => Promise<void>
211212

212213
beforeEach(() => {
@@ -218,9 +219,10 @@ describe("TerminalRegistry", () => {
218219
;(vscode.window as any).onDidStartTerminalShellExecution ??= () => ({ dispose: () => {} })
219220
;(vscode.window as any).onDidEndTerminalShellExecution ??= () => ({ dispose: () => {} })
220221

221-
vi.spyOn(vscode.window, "onDidStartTerminalShellExecution" as any).mockImplementation((_handler: any) => ({
222-
dispose: vi.fn(),
223-
}))
222+
vi.spyOn(vscode.window, "onDidStartTerminalShellExecution" as any).mockImplementation((handler: any) => {
223+
startHandler = handler
224+
return { dispose: vi.fn() }
225+
})
224226

225227
vi.spyOn(vscode.window, "onDidEndTerminalShellExecution" as any).mockImplementation((handler: any) => {
226228
endHandler = handler
@@ -338,6 +340,51 @@ describe("TerminalRegistry", () => {
338340
expect(emitB).toHaveBeenCalledWith("shell_execution_complete", expect.objectContaining({ exitCode: 0 }))
339341
},
340342
)
343+
344+
it("ignores a start event for a different (stale) execution and does not overwrite the stream", async () => {
345+
const terminal = TerminalRegistry.createTerminal("/test/path", "vscode") as Terminal
346+
347+
// processA owns executionA — this is the current, live command.
348+
const processA = new TerminalProcess(terminal)
349+
const executionA = { commandLine: { value: "command A" }, read: vi.fn() } as any
350+
processA.ownExecution = executionA
351+
terminal.process = processA
352+
const setStreamSpy = vi.spyOn(terminal, "setActiveStream")
353+
354+
// A stale start event arrives referencing a *different* execution (executionB).
355+
// This can happen when VSCode fires a delayed start event for a prior terminal
356+
// session on the same reused terminal object.
357+
const executionB = { commandLine: { value: "stale command" }, read: vi.fn() } as any
358+
await startHandler({
359+
terminal: terminal.terminal,
360+
execution: executionB,
361+
})
362+
363+
// The stale event must be ignored: read() must not be called on it and the
364+
// terminal's active stream must not be replaced.
365+
expect(executionB.read).not.toHaveBeenCalled()
366+
expect(setStreamSpy).not.toHaveBeenCalled()
367+
})
368+
369+
it("sets the stream when the start event matches the process's own execution", async () => {
370+
const terminal = TerminalRegistry.createTerminal("/test/path", "vscode") as Terminal
371+
372+
const process = new TerminalProcess(terminal)
373+
const mockStream = (async function* () {})()
374+
const execution = { commandLine: { value: "echo hi" }, read: vi.fn().mockReturnValue(mockStream) } as any
375+
process.ownExecution = execution
376+
terminal.process = process
377+
const setStreamSpy = vi.spyOn(terminal, "setActiveStream")
378+
379+
await startHandler({
380+
terminal: terminal.terminal,
381+
execution,
382+
})
383+
384+
expect(execution.read).toHaveBeenCalledTimes(1)
385+
expect(setStreamSpy).toHaveBeenCalledWith(mockStream)
386+
expect(terminal.busy).toBe(true)
387+
})
341388
})
342389

343390
describe("releaseTerminalsForTask", () => {

0 commit comments

Comments
 (0)