Skip to content

Commit a6e9faf

Browse files
committed
fix(server): setup scripts follow terminal shell fallbacks
1 parent 8d3b061 commit a6e9faf

3 files changed

Lines changed: 162 additions & 22 deletions

File tree

‎apps/server/src/project/ProjectSetupScriptRunner.ts‎

Lines changed: 34 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { ProjectId, type ProjectScript } from "@t3tools/contracts";
2-
import * as HostProcess from "@t3tools/shared/HostProcess";
32
import {
43
projectScriptRuntimeEnv,
54
projectScriptTerminalInput,
@@ -99,9 +98,19 @@ export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<P
9998
}
10099
}
101100

101+
export class ProjectSetupScriptUnsupportedShellError extends Schema.TaggedError<ProjectSetupScriptUnsupportedShellError>()(
102+
"ProjectSetupScriptUnsupportedShellError",
103+
{ shell: Schema.String },
104+
) {
105+
override get message(): string {
106+
return "Project script completion is not supported in cmd.exe. Install PowerShell and retry.";
107+
}
108+
}
109+
102110
export const ProjectSetupScriptRunnerError = Schema.Union([
103111
ProjectSetupScriptOperationError,
104112
ProjectSetupScriptProjectNotFoundError,
113+
ProjectSetupScriptUnsupportedShellError,
105114
]);
106115
export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
107116

@@ -146,13 +155,9 @@ function stripTerminalControl(text: string): string {
146155

147156
type CompletionShell = "posix" | "fish" | "powershell";
148157

149-
function resolveCompletionShell(
150-
platform: NodeJS.Platform,
151-
env: NodeJS.ProcessEnv,
152-
): CompletionShell {
153-
if (platform === "win32") return "powershell";
154-
const shell = env.SHELL ?? "";
155-
const name = shell.split("/").at(-1) ?? shell;
158+
function resolveCompletionShell(shell: string): CompletionShell | null {
159+
const name = (shell.split(/[/\\]/).at(-1) ?? shell).toLowerCase().replace(/\.exe$/, "");
160+
if (name === "cmd") return null;
156161
if (name === "fish") return "fish";
157162
if (name === "pwsh" || name === "powershell") return "powershell";
158163
return "posix";
@@ -186,10 +191,6 @@ export const make = Effect.gen(function* () {
186191
const terminalManager = yield* TerminalManager.TerminalManager;
187192
const serverSettings = yield* ServerSettings.ServerSettingsService;
188193
const crypto = yield* Crypto.Crypto;
189-
const completionShell = resolveCompletionShell(
190-
yield* HostProcess.Platform,
191-
yield* HostProcess.Environment,
192-
);
193194

194195
const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
195196
function* (input: {
@@ -368,15 +369,6 @@ export const make = Effect.gen(function* () {
368369
const completionToken = observe
369370
? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "")
370371
: null;
371-
const commandLine =
372-
observe && completionToken
373-
? wrapCommandForCompletion(
374-
script.command,
375-
completionShell,
376-
completionSentinel(completionToken),
377-
)
378-
: script.command;
379-
380372
yield* terminalManager
381373
.open({
382374
threadId: input.threadId,
@@ -395,6 +387,27 @@ export const make = Effect.gen(function* () {
395387
}),
396388
),
397389
);
390+
let commandLine = script.command;
391+
if (observe && completionToken) {
392+
const shell = yield* terminalManager.getShell({ threadId: input.threadId, terminalId }).pipe(
393+
Effect.mapError(
394+
(cause) =>
395+
new ProjectSetupScriptOperationError({
396+
...errorContext,
397+
operation: "openTerminal",
398+
cause,
399+
}),
400+
),
401+
);
402+
const completionShell = resolveCompletionShell(shell);
403+
if (completionShell === null)
404+
return yield* new ProjectSetupScriptUnsupportedShellError({ shell });
405+
commandLine = wrapCommandForCompletion(
406+
script.command,
407+
completionShell,
408+
completionSentinel(completionToken),
409+
);
410+
}
398411
// Subscribe before writing so the sentinel cannot race past the listener.
399412
const observed =
400413
observe && completionToken

‎apps/server/src/terminal/Manager.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
type TerminalRestartInput,
99
ProviderDriverKind,
1010
ProviderInstanceId,
11+
ProjectId,
1112
TerminalProviderInstanceNotFoundError,
1213
} from "@t3tools/contracts";
1314
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -32,6 +33,8 @@ import * as ServerConfig from "../config.ts";
3233
import * as SqlitePersistence from "../persistence/Sqlite.ts";
3334
import * as ProcessRunner from "../processRunner.ts";
3435
import * as ServerSettings from "../serverSettings.ts";
36+
import * as ProjectService from "../project/ProjectService.ts";
37+
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
3538
import * as TerminalManager from "./Manager.ts";
3639
import { terminalOutputStream } from "./OutputProtocol.ts";
3740
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
@@ -925,6 +928,64 @@ it.layer(
925928
}),
926929
);
927930

931+
it.effect.each(["setup", "settle"] as const)(
932+
"observes %s completion in the fallback shell instead of the configured fish shell",
933+
(trigger) =>
934+
Effect.gen(function* () {
935+
const env = { SHELL: "/missing/fish" };
936+
const { manager, ptyAdapter, baseDir } = yield* createManager(5, { env }).pipe(
937+
Effect.provide(layerWithHostPlatform("linux")),
938+
);
939+
ptyAdapter.spawnFailures.push(new Error("spawn fish ENOENT"));
940+
const runner = yield* ProjectSetupScriptRunner.make.pipe(
941+
Effect.provide(
942+
Layer.mergeAll(
943+
Layer.succeed(TerminalManager.TerminalManager, manager),
944+
Layer.mock(ProjectService.ProjectService)({}),
945+
ServerSettings.layerTest(),
946+
Layer.succeed(HostProcess.Platform, "linux"),
947+
Layer.succeed(HostProcess.Environment, env),
948+
),
949+
),
950+
);
951+
const result = yield* runner.runForThread({
952+
threadId: "thread-setup-fallback",
953+
worktreePath: baseDir,
954+
trigger,
955+
project: {
956+
id: ProjectId.make("project-setup-fallback"),
957+
workspaceRoot: baseDir,
958+
scripts: [
959+
{
960+
id: "setup",
961+
name: "Setup",
962+
command: "echo setup-ready",
963+
icon: "play",
964+
runOnWorktreeCreate: true,
965+
runOnSettle: true,
966+
},
967+
],
968+
},
969+
observeCompletion: {},
970+
});
971+
expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual([
972+
"/missing/fish",
973+
"/bin/zsh",
974+
]);
975+
const process = ptyAdapter.processes[0]!;
976+
const command = process.writes[0]!;
977+
expect(command).toContain('"$?"');
978+
expect(command).not.toContain("$status");
979+
const sentinel = /__T3_SETUP_DONE__[a-zA-Z0-9_]+:/.exec(command)?.[0];
980+
assert.isDefined(sentinel);
981+
assert.equal(result.status, "started");
982+
if (result.status !== "started") return;
983+
assert.isDefined(result.completion);
984+
process.emitData(`setup-ready\r\n${sentinel}0\r\nprompt> `);
985+
expect((yield* result.completion!).exitCode).toBe(0);
986+
}),
987+
);
988+
928989
it.effect("preserves Windows Path casing when appending managed ACP binaries", () =>
929990
Effect.gen(function* () {
930991
const fileSystem = yield* FileSystem.FileSystem;
@@ -1015,6 +1076,55 @@ it.layer(
10151076
]);
10161077
expect(ptyAdapter.spawnInputs[1]?.args).toEqual(["-NoLogo"]);
10171078
expect(ptyAdapter.spawnInputs[2]?.args).toEqual(["-NoLogo"]);
1079+
expect(yield* manager.getShell(openInput())).toBe(
1080+
"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
1081+
);
1082+
}),
1083+
);
1084+
1085+
it.effect("rejects cmd fallback before writing an unsupported completion wrapper", () =>
1086+
Effect.gen(function* () {
1087+
const { manager, ptyAdapter, baseDir } = yield* createManager(5, {
1088+
env: { SystemRoot: "C:\\Windows" },
1089+
}).pipe(Effect.provide(layerWithHostPlatform("win32")));
1090+
ptyAdapter.spawnFailures.push(
1091+
new Error("spawn pwsh ENOENT"),
1092+
new Error("spawn WindowsPowerShell ENOENT"),
1093+
new Error("spawn powershell ENOENT"),
1094+
);
1095+
const runner = yield* ProjectSetupScriptRunner.make.pipe(
1096+
Effect.provide(
1097+
Layer.mergeAll(
1098+
Layer.succeed(TerminalManager.TerminalManager, manager),
1099+
Layer.mock(ProjectService.ProjectService)({}),
1100+
ServerSettings.layerTest(),
1101+
),
1102+
),
1103+
);
1104+
const error = yield* runner
1105+
.runForThread({
1106+
threadId: "thread-cmd-fallback",
1107+
worktreePath: baseDir,
1108+
project: {
1109+
id: ProjectId.make("project-cmd-fallback"),
1110+
workspaceRoot: baseDir,
1111+
scripts: [
1112+
{
1113+
id: "setup",
1114+
name: "Setup",
1115+
command: "echo setup-ready",
1116+
icon: "play",
1117+
runOnWorktreeCreate: true,
1118+
},
1119+
],
1120+
},
1121+
observeCompletion: {},
1122+
})
1123+
.pipe(Effect.flip);
1124+
1125+
expect(error._tag).toBe("ProjectSetupScriptUnsupportedShellError");
1126+
expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("C:\\Windows\\System32\\cmd.exe");
1127+
expect(ptyAdapter.processes[0]?.writes).toEqual([]);
10181128
}),
10191129
);
10201130

‎apps/server/src/terminal/Manager.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ export class TerminalManager extends Context.Service<
165165
input: TerminalOpenInput,
166166
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
167167

168+
readonly getShell: (input: TerminalObserveInput) => Effect.Effect<string, TerminalError>;
169+
168170
readonly attachStream: (
169171
input: TerminalAttachInput,
170172
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
@@ -278,6 +280,7 @@ interface TerminalSessionState {
278280
cols: number;
279281
rows: number;
280282
process: PtyAdapter.PtyProcess | null;
283+
shell: string | null;
281284
unsubscribeData: (() => void) | null;
282285
unsubscribeExit: (() => void) | null;
283286
hasRunningSubprocess: boolean;
@@ -2225,7 +2228,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
22252228
index = 0,
22262229
lastError: PtyAdapter.PtySpawnError | null = null,
22272230
): Effect.fn.Return<
2228-
{ process: PtyAdapter.PtyProcess; shellLabel: string },
2231+
{ process: PtyAdapter.PtyProcess; shell: string; shellLabel: string },
22292232
PtyAdapter.PtySpawnError
22302233
> {
22312234
if (index >= shellCandidates.length) {
@@ -2268,6 +2271,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
22682271
if (attempt._tag === "Success") {
22692272
return {
22702273
process: attempt.success,
2274+
shell: candidate.shell,
22712275
shellLabel: formatShellCandidate(candidate),
22722276
};
22732277
}
@@ -2296,6 +2300,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
22962300
const startingAt = yield* nowIso;
22972301
yield* modifyManagerState((state) => {
22982302
session.status = "starting";
2303+
session.shell = null;
22992304
session.cwd = input.cwd;
23002305
session.worktreePath = input.worktreePath ?? null;
23012306
session.cols = input.cols;
@@ -2372,6 +2377,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
23722377
};
23732378
yield* modifyManagerState((state) => {
23742379
session.process = ptyProcess;
2380+
session.shell = spawnResult.shell;
23752381
session.pid = processPid;
23762382
session.status = "running";
23772383
// onExit may replay an exit immediately; accept it before subscribing.
@@ -2756,6 +2762,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
27562762
cols,
27572763
rows,
27582764
process: null,
2765+
shell: null,
27592766
unsubscribeData: null,
27602767
unsubscribeExit: null,
27612768
hasRunningSubprocess: false,
@@ -2862,6 +2869,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
28622869
resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),
28632870
);
28642871

2872+
const getShell = Effect.fn("terminal.getShell")(function* (input: TerminalObserveInput) {
2873+
const session = yield* requireSession(input.threadId, input.terminalId);
2874+
if (session.status !== "running" || session.shell === null) {
2875+
return yield* new TerminalNotRunningError(input);
2876+
}
2877+
return session.shell;
2878+
});
2879+
28652880
const openOrAttachForStream = Effect.fnUntraced(function* (input: TerminalAttachInput) {
28662881
const terminalId = input.terminalId;
28672882
const existing = yield* getSession(input.threadId, terminalId);
@@ -3241,6 +3256,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
32413256
cols,
32423257
rows,
32433258
process: null,
3259+
shell: null,
32443260
unsubscribeData: null,
32453261
unsubscribeExit: null,
32463262
hasRunningSubprocess: false,
@@ -3365,6 +3381,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
33653381

33663382
return TerminalManager.of({
33673383
open,
3384+
getShell,
33683385
attachStream,
33693386
observeStream,
33703387
resyncStream,

0 commit comments

Comments
 (0)