Skip to content

Commit 719c33f

Browse files
committed
fix(server): hide background console windows on Windows
1 parent c2fa9fc commit 719c33f

8 files changed

Lines changed: 150 additions & 5 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - Executes the emitted Node launcher with a local spawn fixture.
2+
import * as NodeChildProcess from "node:child_process";
3+
import * as NodeServices from "@effect/platform-node/NodeServices";
4+
import { assert, it } from "@effect/vitest";
5+
import {
6+
HostProcessExecutablePath,
7+
HostProcessIsExecutable,
8+
HostProcessPlatform,
9+
} from "@t3tools/shared/hostProcess";
10+
import * as Effect from "effect/Effect";
11+
import * as FileSystem from "effect/FileSystem";
12+
import * as Path from "effect/Path";
13+
14+
import { ensureAgentDeviceShim } from "./AgentDeviceShim.ts";
15+
16+
it.effect(
17+
"sets windowsHide and forwards arguments and exit status in the emitted device launcher",
18+
() =>
19+
Effect.gen(function* () {
20+
const fs = yield* FileSystem.FileSystem;
21+
const path = yield* Path.Path;
22+
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-shim-" });
23+
const entryPath = path.join(root, "entry with spaces.mjs");
24+
const shimDir = yield* ensureAgentDeviceShim({ entryPath, stateDir: root });
25+
const preload = path.join(root, "spawn-fixture.cjs");
26+
yield* fs.writeFileString(
27+
preload,
28+
`
29+
const { EventEmitter } = require("node:events");
30+
require("node:child_process").spawn = (command, args, options) => {
31+
console.log(JSON.stringify({ command, args, windowsHide: options.windowsHide, stdio: options.stdio,
32+
inheritedConfig: options.env.AGENT_DEVICE_CONFIG }));
33+
const child = new EventEmitter();
34+
queueMicrotask(() => child.emit("exit", 23));
35+
return child;
36+
};
37+
require("node:module").syncBuiltinESMExports();
38+
`,
39+
);
40+
const result = NodeChildProcess.spawnSync(
41+
process.execPath,
42+
["--require", preload, path.join(shimDir, "agent-device-launcher.mjs"), "--help"],
43+
{
44+
encoding: "utf8",
45+
windowsHide: true,
46+
env: { ...process.env, AGENT_DEVICE_CONFIG: "fixture-config" },
47+
},
48+
);
49+
assert.isUndefined(result.error);
50+
assert.equal(result.status, 23);
51+
assert.deepEqual(JSON.parse(result.stdout), {
52+
command: process.execPath,
53+
args: [entryPath, "--help"],
54+
windowsHide: true,
55+
stdio: "inherit",
56+
});
57+
assert.include(
58+
yield* fs.readFileString(path.join(shimDir, "agent-device.cmd")),
59+
"agent-device-launcher.mjs",
60+
);
61+
}).pipe(
62+
Effect.scoped,
63+
Effect.provideService(HostProcessPlatform, "win32"),
64+
Effect.provideService(HostProcessExecutablePath, process.execPath),
65+
Effect.provideService(HostProcessIsExecutable, false),
66+
Effect.provide(NodeServices.layer),
67+
),
68+
);

‎apps/server/src/device/AgentDeviceShim.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ const env = { ...process.env };
3939
delete env.AGENT_DEVICE_DAEMON_BASE_URL;
4040
delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
4141
delete env.AGENT_DEVICE_CONFIG;
42-
const child = spawn(${JSON.stringify(node)}, [${JSON.stringify(entryPath)}, ...args], { stdio: "inherit", env });
42+
const child = spawn(${JSON.stringify(node)}, [${JSON.stringify(entryPath)}, ...args], { stdio: "inherit", env, windowsHide: true });
4343
child.on("error", error => { console.error(error.message); process.exitCode = 1; });
4444
child.on("exit", code => { process.exitCode = code ?? 1; });
4545
`,

‎apps/server/src/process/externalLauncher.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,31 @@ it.effect("launches the default browser through the platform command", () => {
121121
);
122122
});
123123

124+
it.effect("sets windowsHide for the Windows browser helper", () => {
125+
let spawned: ChildProcess.StandardCommand | undefined;
126+
return Effect.gen(function* () {
127+
const launcher = yield* ExternalLauncher.ExternalLauncher;
128+
yield* launcher.launchBrowser("https://example.com");
129+
assert.ok(spawned);
130+
assert.equal(spawned.options.windowsHide, true);
131+
assert.equal(spawned.options.detached, true);
132+
assert.equal(spawned.options.shell, false);
133+
assert.include(
134+
Buffer.from(spawned.args.at(-1) ?? "", "base64").toString("utf16le"),
135+
"https://example.com",
136+
);
137+
}).pipe(
138+
Effect.provide(
139+
testLayer({
140+
platform: "win32",
141+
onSpawn: (command) => {
142+
spawned = command;
143+
},
144+
}),
145+
),
146+
);
147+
});
148+
124149
it.effect("launches an installed editor with platform-safe arguments", () =>
125150
Effect.gen(function* () {
126151
const fileSystem = yield* FileSystem.FileSystem;
@@ -338,6 +363,7 @@ it.effect("reveals a file in File Explorer through PowerShell on Windows", () =>
338363
"$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + 'C:\\workspace with spaces\\media\\author''s clip.mp4' + '\"')",
339364
);
340365
assert.equal(spawned.options.shell, false);
366+
assert.equal(spawned.options.windowsHide, true);
341367
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
342368
);
343369

‎apps/server/src/process/externalLauncher.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ interface EditorLaunch {
5757
readonly target: string;
5858
readonly command: string;
5959
readonly args: ReadonlyArray<string>;
60+
readonly hideConsole?: true;
6061
}
6162

6263
interface ProcessLaunch {
@@ -215,6 +216,7 @@ function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLa
215216
args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
216217
options: {
217218
detached: true,
219+
windowsHide: true,
218220
shell: false,
219221
stdin: "ignore",
220222
stdout: "ignore",
@@ -599,6 +601,7 @@ function fileExplorerRevealLaunch(
599601
...POWERSHELL_ARGUMENTS_PREFIX,
600602
encodeUtf16LeBase64(buildFileExplorerRevealPowerShellSource("explorer.exe", explorerTarget)),
601603
],
604+
hideConsole: true,
602605
};
603606
}
604607

@@ -730,6 +733,7 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu
730733
options: {
731734
detached: true,
732735
shell: spawnCommand.shell,
736+
...(launch.hideConsole === true ? { windowsHide: true } : {}),
733737
stdin: "ignore",
734738
stdout: "ignore",
735739
stderr: "ignore",

‎packages/shared/src/legacyCliLauncher.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,50 @@ const hostPlatform = NodeOS.platform();
1313
// oxlint-disable-next-line t3code/no-global-process-runtime -- Match the real executable used by the subprocess.
1414
const hostArch = NodeOS.arch();
1515

16+
it("sets windowsHide and forwards arguments and exit status in the generated launcher", async () => {
17+
const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-legacy-launcher-"));
18+
try {
19+
const entry = NodePath.join(root, "node_modules/t3/dist/bin.mjs");
20+
const packageDir = NodePath.join(root, `node_modules/@t3code/t3-${hostPlatform}-${hostArch}`);
21+
const preload = NodePath.join(root, "spawn-fixture.cjs");
22+
await NodeFSP.mkdir(NodePath.dirname(entry), { recursive: true });
23+
await NodeFSP.mkdir(packageDir, { recursive: true });
24+
await NodeFSP.writeFile(NodePath.join(packageDir, "package.json"), "{}");
25+
await NodeFSP.writeFile(entry, legacyCliLauncherScript());
26+
await NodeFSP.writeFile(
27+
preload,
28+
`
29+
const { EventEmitter } = require("node:events");
30+
require("node:child_process").spawn = (command, args, options) => {
31+
const record = { command, args, options };
32+
const child = new EventEmitter();
33+
console.log(JSON.stringify(record));
34+
queueMicrotask(() => child.emit("exit", 23));
35+
return child;
36+
};
37+
require("node:module").syncBuiltinESMExports();
38+
`,
39+
);
40+
const result = NodeChildProcess.spawnSync(
41+
process.execPath,
42+
["--require", preload, entry, "serve", "a path with spaces"],
43+
{
44+
encoding: "utf8",
45+
windowsHide: true,
46+
},
47+
);
48+
expect(result.error).toBeUndefined();
49+
expect(result.status).toBe(23);
50+
expect(JSON.parse(result.stdout)).toEqual({
51+
command: NodePath.join(packageDir, hostPlatform === "win32" ? "t3.exe" : "t3"),
52+
args: ["serve", "a path with spaces"],
53+
options: { stdio: "inherit", windowsHide: true },
54+
});
55+
} finally {
56+
await NodeFSP.rm(root, { recursive: true, force: true });
57+
}
58+
});
59+
1660
// The fixture executable uses a POSIX shebang. The wrapper itself also runs on Windows.
1761
it.skipIf(hostPlatform === "win32")(
1862
"keeps service IPC, arguments, and termination connected",

‎packages/shared/src/legacyCliLauncher.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const executable = join(dirname(require.resolve("@t3code/t3-" + process.platform
2121
const ipc = process.send !== undefined;
2222
const child = spawn(executable, process.argv.slice(2), {
2323
stdio: ipc ? ["inherit", "inherit", "inherit", "ipc"] : "inherit",
24+
windowsHide: true,
2425
});
2526
const fail = (error) => {
2627
if (!error) return;

‎packages/shared/src/shell.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ describe("readEnvironmentFromWindowsShell", () => {
216216
expect(execFile).toHaveBeenCalledWith(
217217
"pwsh.exe",
218218
expect.arrayContaining(["-NoLogo", "-NoProfile", "-NonInteractive", "-Command"]),
219-
{ encoding: "utf8", timeout: 5000 },
219+
{ encoding: "utf8", timeout: 5000, windowsHide: true },
220220
);
221221
});
222222

@@ -252,7 +252,7 @@ describe("readEnvironmentFromWindowsShell", () => {
252252
expect(execFile).toHaveBeenCalledWith(
253253
"pwsh.exe",
254254
expect.arrayContaining(["-NoLogo", "-NonInteractive", "-Command"]),
255-
{ encoding: "utf8", timeout: 5000 },
255+
{ encoding: "utf8", timeout: 5000, windowsHide: true },
256256
);
257257
expect(execFile.mock.calls[0]?.[1]).not.toContain("-NoProfile");
258258
});
@@ -277,10 +277,12 @@ describe("readEnvironmentFromWindowsShell", () => {
277277
expect(execFile).toHaveBeenNthCalledWith(1, "pwsh.exe", expect.any(Array), {
278278
encoding: "utf8",
279279
timeout: 5000,
280+
windowsHide: true,
280281
});
281282
expect(execFile).toHaveBeenNthCalledWith(2, "powershell.exe", expect.any(Array), {
282283
encoding: "utf8",
283284
timeout: 5000,
285+
windowsHide: true,
284286
});
285287
});
286288
});

‎packages/shared/src/shell.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
2121
type ExecFileSyncLike = (
2222
file: string,
2323
args: ReadonlyArray<string>,
24-
options: { encoding: "utf8"; timeout: number },
24+
options: { encoding: "utf8"; timeout: number; windowsHide?: true },
2525
) => string;
2626

2727
function canExecuteFile(filePath: string): boolean {
@@ -370,7 +370,7 @@ export function readEnvironmentFromWindowsShell(
370370
];
371371
for (const shell of WINDOWS_SHELL_CANDIDATES) {
372372
try {
373-
const output = execFile(shell, args, { encoding: "utf8", timeout: 5000 });
373+
const output = execFile(shell, args, { encoding: "utf8", timeout: 5000, windowsHide: true });
374374

375375
const environment: Partial<Record<string, string>> = {};
376376
for (const name of names) {

0 commit comments

Comments
 (0)