diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index fd40f24d5a908..0628030b8f91c 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -5,6 +5,7 @@ import { ProjectId, TerminalNotRunningError, type TerminalEvent, + type TerminalOpenInput, type TerminalSessionSnapshot, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -48,14 +49,19 @@ const makeHarness = Effect.fn(function* (options: { readonly shell?: string | null; }) { const listeners = new Set<(event: TerminalEvent) => Effect.Effect>(); + const opens: TerminalOpenInput[] = []; const writes = yield* Queue.unbounded(); const outputLines = yield* Queue.unbounded(); const terminals = Layer.mock(TerminalManager.TerminalManager)({ - open: () => - (options.opening - ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never)) - : Effect.void - ).pipe(Effect.as(openSnapshot(options.history ?? ""))), + open: (input) => + Effect.sync(() => opens.push(input)).pipe( + Effect.andThen( + options.opening + ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never)) + : Effect.void, + ), + Effect.as(openSnapshot(options.history ?? "")), + ), getShell: () => options.shell === null ? Effect.fail(new TerminalNotRunningError({ threadId, terminalId })) @@ -102,7 +108,7 @@ const makeHarness = Effect.fn(function* (options: { }); const emit = (terminalEvent: TerminalEvent) => Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true }); - return { start, listeners, writes, outputLines, emit }; + return { start, listeners, writes, outputLines, emit, opens }; }); const setup = Effect.fn(function* ( @@ -120,6 +126,13 @@ const setup = Effect.fn(function* ( }); describe("ProjectSetupScriptRunner", () => { + it.effect("keeps setup scripts independent of the interactive shell preference", () => + Effect.gen(function* () { + const { opens } = yield* setup(); + expect(opens[0]?.env?.T3CODE_TERMINAL_SHELL).toBe(""); + }), + ); + it.effect("writes immediately when the spawned fallback is PowerShell", () => Effect.gen(function* () { const { writes } = yield* setup({ diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index 60084f648a182..0f2e58d121402 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -503,6 +503,8 @@ export const make = Effect.gen(function* () { }), // Before client attachment, truecolor probes wait for terminal replies nobody can send. COLORTERM: "", + // Project scripts keep the default shell; the preference is for interactive terminals only. + T3CODE_TERMINAL_SHELL: "", }; const observe = input.observeCompletion; const completionToken = observe ? (yield* random.uuidV4()).replaceAll("-", "") : null; diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 8499197acb765..a7d292e274033 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -18,6 +18,8 @@ import { TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { SpawnExecutableResolution } from "@t3tools/shared/shell"; +import * as NodePtyAdapter from "./NodePtyAdapter.ts"; import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -321,7 +323,7 @@ const createManager = ( managedBinaryCacheDir: options.managedBinaryCacheDir, managedBinaryToolsDir: options.managedBinaryToolsDir, }), - }); + }).pipe(Effect.provideService(SpawnExecutableResolution, (command) => command)); const eventsRef = yield* Ref.make>([]); const unsubscribe = yield* manager.subscribe((event) => Ref.update(eventsRef, (events) => [...events, event]), @@ -2213,6 +2215,91 @@ it.layer( }), ); + it.effect.each([ + { platform: "win32", shell: String.raw`C:\Program Files\Git\bin\bash.exe` }, + { platform: "linux", shell: "/opt/custom shell/bin/bash" }, + ] as const)("prefers the configured terminal shell on $platform: $shell", ({ platform, shell }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + env: { T3CODE_TERMINAL_SHELL: ` ${shell} `, SHELL: "/bin/zsh" }, + }).pipe(Effect.provide(layerWithHostPlatform(platform))); + + yield* manager.open(openInput()); + + expect(ptyAdapter.spawnInputs[0]?.shell).toBe(shell); + }), + ); + + it.effect("lets script terminals keep the default shell without changing other terminals", () => + Effect.gen(function* () { + const gitBash = String.raw`C:\Program Files\Git\bin\bash.exe`; + const { manager, ptyAdapter } = yield* createManager(5, { + env: { T3CODE_TERMINAL_SHELL: gitBash }, + }).pipe(Effect.provide(layerWithHostPlatform("win32"))); + + yield* manager.open(openInput({ env: { T3CODE_TERMINAL_SHELL: "" } })); + yield* manager.open(openInput({ terminalId: "interactive" })); + + expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual(["pwsh.exe", gitBash]); + }), + ); + + // POSIX exec failures are asynchronous in node-pty; ConPTY has a separate readiness protocol. + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "resolves configured shells and falls back from invalid paths with the real PTY adapter", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-real-shell-" }); + const nonExecutable = path.join(baseDir, "not-executable"); + yield* fs.writeFileString(nonExecutable, "#!/bin/sh\nexit 0\n"); + yield* fs.chmod(nonExecutable, 0o644); + const ptyAdapter = yield* PtyAdapter.PtyAdapter.pipe(Effect.provide(NodePtyAdapter.layer)); + const toolsDir = path.join(baseDir, "tools"); + const customShell = path.join(toolsDir, "custom-shell"); + yield* fs.makeDirectory(toolsDir); + yield* fs.writeFileString(customShell, "#!/bin/sh\nexec /bin/sh\n"); + yield* fs.chmod(customShell, 0o755); + const spacedDir = path.join(baseDir, "shells "); + const spacedShell = path.join(spacedDir, "custom-shell"); + yield* fs.makeDirectory(spacedDir); + yield* fs.writeFileString(spacedShell, "#!/bin/sh\nexec /bin/sh\n"); + yield* fs.chmod(spacedShell, 0o755); + for (const { shell, searchPath, cwd, expectedShell } of [ + { shell: path.join(baseDir, "missing"), searchPath: "/bin", expectedShell: "/bin/sh" }, + { shell: nonExecutable, searchPath: "/bin", expectedShell: "/bin/sh" }, + { shell: "custom-shell", searchPath: "./tools", expectedShell: customShell }, + { shell: "custom-shell", searchPath: toolsDir, expectedShell: customShell }, + { shell: "custom-shell", searchPath: '"./tools"', expectedShell: customShell }, + { shell: "custom-shell", searchPath: ":/bin", cwd: toolsDir, expectedShell: customShell }, + { shell: "custom-shell", searchPath: `${spacedDir}:/bin`, expectedShell: spacedShell }, + ] as ReadonlyArray<{ + shell: string; + searchPath: string; + cwd?: string; + expectedShell: string; + }>) { + const spawnedShells: string[] = []; + const manager = yield* TerminalManager.makeWithOptions({ + logsDir: path.join(baseDir, "logs"), + ptyAdapter: { + spawn: (input) => { + spawnedShells.push(input.shell); + return ptyAdapter.spawn(input); + }, + }, + shellResolver: () => "/bin/sh", + env: { ...process.env, T3CODE_TERMINAL_SHELL: shell, PATH: searchPath }, + }); + const snapshot = yield* manager.open(openInput({ cwd: cwd ?? baseDir })); + expect(spawnedShells).toEqual([expectedShell]); + expect(snapshot.status).toBe("running"); + yield* manager.close({ threadId: "thread-1" }); + } + }), + ); + it.effect("preserves Windows Path casing when appending managed ACP binaries", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -2282,8 +2369,8 @@ it.layer( const ptyAdapter = new FakePtyAdapter(); const { manager } = yield* createManager(5, { ptyAdapter, - shellResolver: () => "C:\\missing\\custom-shell.exe", env: { + T3CODE_TERMINAL_SHELL: "C:\\missing\\custom-shell.exe", ComSpec: "C:\\Windows\\System32\\cmd.exe", PATH: "C:\\Windows\\System32", SystemRoot: "C:\\Windows", @@ -2730,13 +2817,13 @@ it.layer( }), ); - it.effect("starts bash as a login shell on macOS only", () => + it.effect("starts bash as a login shell on macOS and Windows", () => Effect.gen(function* () { for (const [platform, shell, args] of [ ["darwin", "/bin/bash", ["-l"]], ["darwin", "/opt/homebrew/bin/bash", ["-l"]], ["linux", "/bin/bash", undefined], - ["win32", "C:\\Program Files\\Git\\bin\\bash.exe", undefined], + ["win32", "C:\\Program Files\\Git\\bin\\bash.exe", ["--login", "-i"]], ["darwin", "/bin/zsh", ["-o", "nopromptsp"]], ["linux", "/bin/zsh", ["-o", "nopromptsp"]], ["win32", "pwsh.exe", POWERSHELL_ARGS], diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index d7fff551faaf8..504bb2c3b5fdc 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -43,7 +43,7 @@ import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { mergePathEntries } from "@t3tools/shared/shell"; +import { SpawnExecutableResolution, mergePathEntries } from "@t3tools/shared/shell"; import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server"; import { getTerminalLabel } from "@t3tools/shared/terminalLabels"; @@ -601,6 +601,9 @@ function shellCandidateFromCommand( if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) { return { shell: command, args: ["-NoLogo", "-NoExit", "-Command", POWERSHELL_UTF8_SETUP] }; } + if (platform === "win32" && (shellName === "bash.exe" || shellName === "bash")) { + return { shell: command, args: ["--login", "-i"] }; + } if (platform !== "win32" && shellName === "zsh") { return { shell: command, args: ["-o", "nopromptsp"] }; } @@ -651,7 +654,10 @@ const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(func shellResolver: () => string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, + terminalShell: string | undefined, ) { + // This is an executable path, not a command line; spaces belong to the path. + const configured = shellCandidateFromCommand(terminalShell?.trim() || null, platform); const requested = shellCandidateFromCommand( yield* normalizeShellCommand(shellResolver(), platform), platform, @@ -659,6 +665,7 @@ const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(func if (platform === "win32") { return uniqueShellCandidates([ + configured, requested, shellCandidateFromCommand("pwsh.exe", platform), shellCandidateFromCommand(windowsPowerShellPath(env), platform), @@ -670,6 +677,7 @@ const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(func } return uniqueShellCandidates([ + configured, requested, shellCandidateFromCommand(yield* normalizeShellCommand(env.SHELL, platform), platform), shellCandidateFromCommand("/bin/zsh", platform), @@ -1781,6 +1789,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const agentScope = yield* AgentScope; + const resolveExecutable = yield* SpawnExecutableResolution; // Inherit the full environment minus createTerminalSpawnEnv's blocklist; allowlists silently drop user tooling variables. const baseEnv = options.env ?? process.env; const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv)); @@ -2728,8 +2737,41 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); } + // PATH lookup must use the child's working directory, not the server's. + const lookupEnv = + platform === "win32" + ? spawnEnv + : { + ...spawnEnv, + PATH: (spawnEnv.PATH ?? spawnEnv.Path ?? spawnEnv.path ?? "") + .split(":") + // An empty entry means the working directory, which resolve("") yields. + .map((entry) => path.resolve(session.cwd, entry.replace(/^"+|"+$/g, ""))) + .join(":"), + }; + // POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate. + const executable = + platform !== "win32" + ? resolveExecutable( + candidate.shell.includes("/") + ? path.resolve(session.cwd, candidate.shell) + : candidate.shell, + platform, + lookupEnv, + ) + : candidate.shell; + if (executable === undefined) { + return yield* trySpawn( + shellCandidates, + spawnEnv, + session, + index + 1, + new PtyAdapter.PtySpawnError({ adapter: "terminal-manager", shell: candidate.shell }), + ); + } + const launch = yield* agentScope.wrap({ - command: candidate.shell, + command: executable, args: candidate.args ?? [], name: "terminal", env: spawnEnv, @@ -2806,6 +2848,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func shellResolver, platform, baseEnv, + session.runtimeEnv?.T3CODE_TERMINAL_SHELL ?? baseEnv.T3CODE_TERMINAL_SHELL, ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem)); const terminalEnv = createTerminalSpawnEnv( baseEnv, diff --git a/docs/user/terminal.md b/docs/user/terminal.md index dd921eb9a9650..a92ddc1ab6458 100644 --- a/docs/user/terminal.md +++ b/docs/user/terminal.md @@ -1,4 +1,33 @@ -# Terminal history +# Terminal + +## Choose a shell + +Set `T3CODE_TERMINAL_SHELL` in the environment that launches the T3 Code server +to choose the executable used for new terminals. Use an executable name or its +full path, without surrounding quotes or command-line arguments. An unset or +blank value keeps the platform default. If the executable cannot be started, +T3 Code tries its usual fallback shells. + +On Windows, to use Git Bash from a standard Git for Windows installation, run +this in PowerShell: + +```powershell +[Environment]::SetEnvironmentVariable('T3CODE_TERMINAL_SHELL', 'C:\Program Files\Git\bin\bash.exe', 'User') +``` + +Fully quit T3 Code, then reopen it from the Start menu and create a new terminal. +If the app still inherits the old environment, sign out of Windows and sign in +again. Git Bash starts as an interactive login shell. Use `bin\bash.exe`, not +`git-bash.exe`, which launches a separate terminal window. + +To restore the default, remove the variable with the same command using `$null` +as its second argument, then restart T3 Code. + +This setting belongs to the machine hosting the server, including when you +connect from another device. It does not change provider-run commands or the +shell used by automatic project setup and settle scripts. + +## Terminal history Each terminal keeps up to 5,000 lines and 8 MiB of scrollback on its environment server. T3 Code removes the oldest output when either limit is reached. A long