Skip to content
1 change: 1 addition & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.
const TerminalLayerLive = TerminalManager.layer.pipe(
Layer.provide(PtyAdapterLive),
Layer.provide(PortScannerLayerLive),
Layer.provide(ServerSettingsLayerLive),
);

const PreviewLayerLive = Layer.empty.pipe(
Expand Down
135 changes: 132 additions & 3 deletions apps/server/src/terminal/Manager.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import * as NodeOS from "node:os";

import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
DEFAULT_SERVER_SETTINGS,
DEFAULT_TERMINAL_ID,
type TerminalAttachStreamEvent,
type TerminalEvent,
Expand All @@ -20,14 +23,19 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vite-plus/test";

import * as ServerConfig from "../config.ts";
import * as PortScanner from "../preview/PortScanner.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as TerminalManager from "./Manager.ts";
import * as PtyAdapter from "./PtyAdapter.ts";

Expand Down Expand Up @@ -280,6 +288,48 @@ it.layer(
Layer.merge(NodeServices.layer, ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer))),
{ excludeTestServices: true },
)("TerminalManager", (it) => {
it.effect("subscribes to settings changes before reading the initial shell setting", () =>
Effect.gen(function* () {
const callOrder: string[] = [];
const settingsChanges = yield* PubSub.unbounded<typeof DEFAULT_SERVER_SETTINGS>();
const serverSettings = ServerSettings.ServerSettingsService.of({
start: Effect.void,
ready: Effect.void,
getSettings: Effect.sync(() => {
callOrder.push("getSettings");
return DEFAULT_SERVER_SETTINGS;
}),
updateSettings: () => Effect.die(new Error("unused in this test")),
streamChanges: Stream.empty,
subscribeChanges: PubSub.subscribe(settingsChanges).pipe(
Effect.tap(() =>
Effect.sync(() => {
callOrder.push("subscribeChanges");
}),
),
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
});
const ptyAdapter = new FakePtyAdapter();
const portDiscovery = PortScanner.PortDiscovery.of({
scan: () => Effect.succeed([]),
subscribe: () => Effect.void,
retain: Effect.void,
registerTerminalProcesses: () => Effect.void,
unregisterTerminal: () => Effect.void,
});

yield* TerminalManager.make().pipe(
Effect.provideService(PtyAdapter.PtyAdapter, ptyAdapter),
Effect.provideService(PortScanner.PortDiscovery, portDiscovery),
Effect.provideService(ServerSettings.ServerSettingsService, serverSettings),
Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-terminal-settings-" })),
);

expect(callOrder).toEqual(["subscribeChanges", "getSettings"]);
}),
);

it.effect("spawns lazily and reuses running terminal per thread", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
Expand Down Expand Up @@ -1401,10 +1451,10 @@ it.layer(
it.effect("retries with fallback shells when preferred shell spawn fails", () =>
Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const missingShell =
let configuredShell =
platform === "win32" ? "C:\\definitely\\missing-shell.exe" : "/definitely/missing-shell -l";
const { manager, ptyAdapter } = yield* createManager(5, {
shellResolver: () => missingShell,
shellResolver: () => configuredShell,
});
ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed."));

Expand All @@ -1413,7 +1463,7 @@ it.layer(
assert.equal(snapshot.status, "running");
expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2);
expect(ptyAdapter.spawnInputs[0]?.shell).toBe(
platform === "win32" ? missingShell : "/definitely/missing-shell",
platform === "win32" ? configuredShell : "/definitely/missing-shell",
);

if (platform === "win32") {
Expand All @@ -1431,10 +1481,29 @@ it.layer(
.slice(1)
.some((input) => input.shell !== "/definitely/missing-shell"),
).toBe(true);

configuredShell = '"/definitely/missing shell" -l';
yield* manager.open(openInput({ terminalId: "quoted-shell" }));
expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("/definitely/missing shell");
}
}),
);

it.effect("expands home-relative configured shell paths before spawning", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const { manager, ptyAdapter } = yield* createManager(5, {
shellResolver: () => "~/bin/test-shell",
}).pipe(Effect.provide(withHostPlatform("linux")));

yield* manager.open(openInput());

expect(ptyAdapter.spawnInputs[0]?.shell).toBe(
path.join(NodeOS.homedir(), "bin", "test-shell"),
);
}),
);

it.effect("prefers PowerShell over ComSpec for Windows terminals", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
Expand All @@ -1456,6 +1525,66 @@ it.layer(
}),
);

it.effect("adds no-logo when a configured Windows PowerShell alias is unresolved", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
shellResolver: () => "pwsh",
env: { SystemRoot: "C:\\Windows" },
}).pipe(Effect.provide(withHostPlatform("win32")));

yield* manager.open(openInput());

expect(ptyAdapter.spawnInputs[0]).toEqual(
expect.objectContaining({
shell: "pwsh",
args: ["-NoLogo"],
}),
);
}),
);

it.effect("resolves configured Windows shells against the effective environment", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseBinDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code terminal base shell ",
});
const runtimeBinDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-terminal-runtime-shell-",
});
const baseShellPath = path.join(baseBinDir, "test-shell.EXE");
const runtimeShellPath = path.join(runtimeBinDir, "test-shell.EXE");
yield* fileSystem.writeFileString(baseShellPath, "MZ");
yield* fileSystem.writeFileString(runtimeShellPath, "MZ");

let configuredShell = "test-shell";
const { manager, ptyAdapter } = yield* createManager(5, {
shellResolver: () => configuredShell,
env: {
PATH: baseBinDir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
SystemRoot: "C:\\Windows",
},
}).pipe(Effect.provide(withHostPlatform("win32")));

yield* manager.open(openInput());
configuredShell = baseShellPath;
yield* manager.open(openInput({ terminalId: "unquoted-shell" }));
configuredShell = `"${baseShellPath}"`;
yield* manager.open(openInput({ terminalId: "quoted-shell" }));
configuredShell = "test-shell";
yield* manager.open(openInput({ terminalId: "runtime-shell", env: { PATH: runtimeBinDir } }));

expect(ptyAdapter.spawnInputs.map(({ shell }) => shell)).toEqual([
baseShellPath,
baseShellPath,
baseShellPath,
runtimeShellPath,
]);
}),
);

it.effect("falls back to built-in PowerShell by absolute path on Windows", () =>
Effect.gen(function* () {
const ptyAdapter = new FakePtyAdapter();
Expand Down
73 changes: 60 additions & 13 deletions apps/server/src/terminal/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
} from "@t3tools/contracts";
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { resolveCommandPath } from "@t3tools/shared/shell";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as DateTime from "effect/DateTime";
import * as Context from "effect/Context";
Expand All @@ -49,16 +50,19 @@ import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";

import * as ServerConfig from "../config.ts";
import { expandHomePath } from "../pathExpansion.ts";
import {
increment,
terminalRestartsTotal,
terminalSessionsTotal,
} from "../observability/Metrics.ts";
import * as ProcessRunner from "../processRunner.ts";
import * as PortScanner from "../preview/PortScanner.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as PtyAdapter from "./PtyAdapter.ts";

export {
Expand Down Expand Up @@ -460,13 +464,14 @@ function normalizeShellCommand(
const trimmed = value.trim();
if (trimmed.length === 0) return null;

if (platform === "win32") {
return trimmed;
}
const quotedExecutable = trimmed.match(/^(["'])(.*?)\1(?:\s|$)/u)?.[2];
if (quotedExecutable) return expandHomePath(quotedExecutable);

if (platform === "win32") return expandHomePath(trimmed);

const firstToken = trimmed.split(/\s+/g)[0]?.trim();
if (!firstToken) return null;
return firstToken.replace(/^['"]|['"]$/g, "");
return expandHomePath(firstToken.replace(/^['"]|['"]$/g, ""));
}

function basenameForPlatform(command: string, platform: NodeJS.Platform): string {
Expand Down Expand Up @@ -494,7 +499,13 @@ function shellCandidateFromCommand(
): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = basenameForPlatform(command, platform).toLowerCase();
if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
if (
platform === "win32" &&
(shellName === "pwsh" ||
shellName === "pwsh.exe" ||
shellName === "powershell" ||
shellName === "powershell.exe")
) {
return { shell: command, args: ["-NoLogo"] };
}
if (platform !== "win32" && shellName === "zsh") {
Expand Down Expand Up @@ -539,15 +550,32 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
return ordered;
}

function resolveShellCandidates(
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(function* (
shellResolver: () => string,
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): ShellCandidate[] {
const requested = shellCandidateFromCommand(
normalizeShellCommand(shellResolver(), platform),
platform,
);
): Effect.fn.Return<ShellCandidate[], never, FileSystem.FileSystem | Path.Path> {
const requestedCommand = normalizeShellCommand(shellResolver(), platform);
// `resolveCommandPath` checks explicit paths relative to the server process,
// while PTY spawns resolve them relative to the session cwd. Only resolve
// bare command names through PATH so a relative configured path keeps its
// normal PTY semantics.
const isPathLikeCommand =
requestedCommand?.includes("/") === true ||
requestedCommand?.includes("\\") === true ||
requestedCommand?.includes(":") === true ||
/\s/u.test(requestedCommand ?? "");
const canResolveFromPath =
platform === "win32" && requestedCommand !== null && !isPathLikeCommand;
const resolvedRequestedCommand = canResolveFromPath
? yield* resolveCommandPath(requestedCommand, { env }).pipe(
Effect.provideService(HostProcessPlatform, platform),
Effect.catchTags({
CommandResolutionError: () => Effect.succeed(requestedCommand),
}),
)
: requestedCommand;
const requested = shellCandidateFromCommand(resolvedRequestedCommand, platform);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

if (platform === "win32") {
return uniqueShellCandidates([
Expand All @@ -571,7 +599,7 @@ function resolveShellCandidates(
shellCandidateFromCommand("bash", platform),
shellCandidateFromCommand("sh", platform),
]);
}
});

function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
const queue: unknown[] = [error];
Expand Down Expand Up @@ -1133,9 +1161,21 @@ export const make = Effect.fn("TerminalManager.make")(function* () {
const { terminalLogsDir } = yield* ServerConfig.ServerConfig;
const ptyAdapter = yield* PtyAdapter.PtyAdapter;
const portDiscovery = yield* PortScanner.PortDiscovery;
const settingsService = yield* ServerSettings.ServerSettingsService;
const settingsChanges = yield* settingsService.subscribeChanges;
let configuredShell = (yield* settingsService.getSettings).defaultTerminalShell;
yield* settingsChanges.pipe(
Stream.runForEach((settings) =>
Effect.sync(() => {
configuredShell = settings.defaultTerminalShell;
}),
),
Effect.forkScoped({ startImmediately: true }),
);
return yield* makeWithOptions({
logsDir: terminalLogsDir,
ptyAdapter,
shellResolver: () => configuredShell,
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
registerTerminalProcesses: portDiscovery.registerTerminalProcesses,
unregisterTerminal: portDiscovery.unregisterTerminal,
});
Expand Down Expand Up @@ -1867,8 +1907,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(
Effect.andThen(
Effect.gen(function* () {
const shellCandidates = resolveShellCandidates(shellResolver, platform, baseEnv);
const terminalEnv = createTerminalSpawnEnv(baseEnv, session.runtimeEnv);
const shellCandidates = yield* resolveShellCandidates(
shellResolver,
platform,
terminalEnv,
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
startedShell = spawnResult.shellLabel;
Expand Down
Loading
Loading