Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Runs before the Effect runtime starts, on raw file descriptors.
2import * as NodeFS from "node:fs";
3import * as NodeTty from "node:tty";
4
5import * as HostProcess from "@t3tools/shared/HostProcess";
6
7/**
8 * Whether this process is the desktop app's `t3.cmd` running the CLI in a
9 * terminal with no stdin. The launcher runs the app's executable with
10 * `ELECTRON_RUN_AS_NODE`, and Electron's Windows executable is a GUI program:
11 * on start it points stdout and stderr at the parent's console but leaves
12 * stdin unset, so prompts see no terminal and children such as the agent
13 * `t3 triage` starts inherit nothing to read from. Input the user piped or
14 * redirected is a valid descriptor and is left alone, as is any run whose
15 * output is not a console (the desktop backend, scripts).
16 */
17function needsConsoleStdin(input: {
18 readonly platform: NodeJS.Platform;
19 readonly env: NodeJS.ProcessEnv;
20 readonly stdinOpen: boolean;
21 readonly stdoutIsConsole: boolean;
22}): boolean {
23 return (
24 input.platform === "win32" &&
25 // Set only by the launcher (DesktopCliShim), never for the desktop backend.
26 input.env.T3CODE_DESKTOP_CLI_LAUNCHER === "1" &&
27 !input.stdinOpen &&
28 input.stdoutIsConsole
29 );
30}
31
32const isOpen = (fd: number) => {
33 try {
34 NodeFS.fstatSync(fd);
35 return true;
36 } catch {
37 return false;
38 }
39};
40
41/**
42 * Reopens the console's input as `process.stdin` when {@link needsConsoleStdin}
43 * holds, and returns its descriptor so interactive children can be given the
44 * same console. Returns undefined, changing nothing, everywhere else.
45 * Call before anything reads `process.stdin`.
46 */
47export function attachConsoleStdin(): number | undefined {
48 const needed = needsConsoleStdin({
49 platform: HostProcess.Platform.defaultValue(),
50 env: process.env,
51 stdinOpen: isOpen(0),
52 stdoutIsConsole: NodeTty.isatty(1),
53 });
54 // The marker describes this process's own start; a server started here
55 // must not pass it on to the shells and `t3` runs it spawns.
56 delete process.env.T3CODE_DESKTOP_CLI_LAUNCHER;
57 if (!needed) return undefined;
58 let fd: number;
59 try {
60 fd = NodeFS.openSync("\\\\.\\CONIN$", "r+");
61 } catch {
62 return undefined;
63 }
64 if (!NodeTty.isatty(fd)) {
65 NodeFS.closeSync(fd);
66 return undefined;
67 }
68 const stdin = new NodeTty.ReadStream(fd);
69 Object.defineProperty(process, "stdin", { value: stdin, configurable: true, enumerable: true });
70 consoleStdinFd = fd;
71 return fd;
72}
73
74let consoleStdinFd: number | undefined;
75
76/** The stdin to hand an interactive child: the reopened console, or the inherited one. */
77export const interactiveStdin = (): number | "inherit" => consoleStdinFd ?? "inherit";