Skip to content

Commit f46f838

Browse files
Afornomaria-rcks
andauthored
fix(server): setup scripts follow terminal shell fallbacks (#23576)
Co-authored-by: maria-rcks <[email protected]>
1 parent 3702273 commit f46f838

4 files changed

Lines changed: 252 additions & 73 deletions

File tree

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

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
22
import { describe, expect, it } from "@effect/vitest";
3-
import { ProjectId, type TerminalEvent, type TerminalSessionSnapshot } from "@t3tools/contracts";
4-
import * as HostProcess from "@t3tools/shared/HostProcess";
3+
import {
4+
ProjectId,
5+
TerminalNotRunningError,
6+
type TerminalEvent,
7+
type TerminalSessionSnapshot,
8+
} from "@t3tools/contracts";
59
import * as Deferred from "effect/Deferred";
610
import * as Effect from "effect/Effect";
711
import * as Fiber from "effect/Fiber";
@@ -36,6 +40,7 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({
3640
const makeHarness = Effect.fn(function* (options: {
3741
readonly history?: string;
3842
readonly opening?: Deferred.Deferred<void>;
43+
readonly shell?: string | null;
3944
}) {
4045
const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
4146
const writes = yield* Queue.unbounded<string>();
@@ -46,6 +51,10 @@ const makeHarness = Effect.fn(function* (options: {
4651
? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
4752
: Effect.void
4853
).pipe(Effect.as(openSnapshot(options.history ?? ""))),
54+
getShell: () =>
55+
options.shell === null
56+
? Effect.fail(new TerminalNotRunningError({ threadId, terminalId }))
57+
: Effect.succeed(options.shell ?? "/bin/zsh"),
4958
subscribe: (listener) =>
5059
Effect.sync(() => {
5160
listeners.add(listener);
@@ -66,8 +75,6 @@ const makeHarness = Effect.fn(function* (options: {
6675
NodeCrypto.layer,
6776
),
6877
),
69-
Effect.provideService(HostProcess.Platform, "darwin"),
70-
Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }),
7178
);
7279
const start = runner.runForThread({
7380
threadId,
@@ -92,7 +99,12 @@ const makeHarness = Effect.fn(function* (options: {
9299
return { start, listeners, writes, outputLines, emit };
93100
});
94101

95-
const setup = Effect.fn(function* (options: { readonly history?: string } = {}) {
102+
const setup = Effect.fn(function* (
103+
options: {
104+
readonly history?: string;
105+
readonly shell?: string | null;
106+
} = {},
107+
) {
96108
const harness = yield* makeHarness(options);
97109
const result = yield* harness.start;
98110
const completion = result.status === "started" ? result.completion : undefined;
@@ -101,6 +113,15 @@ const setup = Effect.fn(function* (options: { readonly history?: string } = {})
101113
});
102114

103115
describe("ProjectSetupScriptRunner", () => {
116+
it.effect("writes immediately when the spawned fallback is PowerShell", () =>
117+
Effect.gen(function* () {
118+
const { writes } = yield* setup({
119+
shell: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
120+
});
121+
expect(yield* Queue.take(writes)).toContain("$global:LASTEXITCODE");
122+
}),
123+
);
124+
104125
it.effect("shows a startup prompt and types only once the line editor starts", () =>
105126
Effect.gen(function* () {
106127
const { result, writes, outputLines, emit } = yield* setup();
@@ -160,13 +181,20 @@ describe("ProjectSetupScriptRunner", () => {
160181
}),
161182
);
162183

163-
it.effect("does not type into a shell that exits during startup", () =>
164-
Effect.gen(function* () {
165-
const { completion, writes, emit } = yield* setup();
166-
yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
167-
expect(yield* completion).toMatchObject({ exitCode: null });
168-
yield* TestClock.adjust("1 minute");
169-
expect(yield* Queue.size(writes)).toBe(0);
170-
}),
184+
it.effect.each([false, true])(
185+
"does not type into a shell that exits during startup (before shell lookup: %s)",
186+
(beforeShellLookup) =>
187+
Effect.gen(function* () {
188+
const { completion, writes, emit, listeners } = yield* setup(
189+
beforeShellLookup ? { shell: null } : {},
190+
);
191+
if (!beforeShellLookup) {
192+
yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null });
193+
}
194+
expect(yield* completion).toMatchObject({ exitCode: null });
195+
yield* TestClock.adjust("1 minute");
196+
expect(yield* Queue.size(writes)).toBe(0);
197+
expect(listeners.size).toBe(0);
198+
}),
171199
);
172200
});

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

Lines changed: 79 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts";
2-
import * as HostProcess from "@t3tools/shared/HostProcess";
32
import {
43
projectScriptRuntimeEnv,
54
projectScriptTerminalInput,
@@ -107,9 +106,19 @@ export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<P
107106
}
108107
}
109108

109+
export class ProjectSetupScriptUnsupportedShellError extends Schema.TaggedError<ProjectSetupScriptUnsupportedShellError>()(
110+
"ProjectSetupScriptUnsupportedShellError",
111+
{ shell: Schema.String },
112+
) {
113+
override get message(): string {
114+
return "Project script completion is not supported in cmd.exe. Install PowerShell and retry.";
115+
}
116+
}
117+
110118
export const ProjectSetupScriptRunnerError = Schema.Union([
111119
ProjectSetupScriptOperationError,
112120
ProjectSetupScriptProjectNotFoundError,
121+
ProjectSetupScriptUnsupportedShellError,
113122
]);
114123
export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
115124

@@ -159,13 +168,9 @@ function lineEditorReading(text: string, previous: boolean): boolean {
159168

160169
type CompletionShell = "posix" | "fish" | "powershell";
161170

162-
function resolveCompletionShell(
163-
platform: NodeJS.Platform,
164-
env: NodeJS.ProcessEnv,
165-
): CompletionShell {
166-
if (platform === "win32") return "powershell";
167-
const shell = env.SHELL ?? "";
168-
const name = shell.split("/").at(-1) ?? shell;
171+
function resolveCompletionShell(shell: string): CompletionShell | null {
172+
const name = (shell.split(/[/\\]/).at(-1) ?? shell).toLowerCase().replace(/\.exe$/, "");
173+
if (name === "cmd") return null;
169174
if (name === "fish") return "fish";
170175
if (name === "pwsh" || name === "powershell") return "powershell";
171176
return "posix";
@@ -196,10 +201,6 @@ export const make = Effect.gen(function* () {
196201
const serverSettings = yield* ServerSettings.ServerSettingsService;
197202
const crypto = yield* Crypto.Crypto;
198203
const serviceScope = yield* Effect.scope;
199-
const completionShell = resolveCompletionShell(
200-
yield* HostProcess.Platform,
201-
yield* HostProcess.Environment,
202-
);
203204

204205
const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
205206
function* (input: {
@@ -444,15 +445,7 @@ export const make = Effect.gen(function* () {
444445
const completionToken = observe
445446
? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "")
446447
: null;
447-
const commandLine =
448-
observe && completionToken
449-
? wrapCommandForCompletion(
450-
script.command,
451-
completionShell,
452-
completionSentinel(completionToken),
453-
)
454-
: script.command;
455-
448+
const echoedWrapperLines: string[] = [];
456449
// Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
457450
const observed =
458451
observe && completionToken
@@ -461,49 +454,76 @@ export const make = Effect.gen(function* () {
461454
terminalId,
462455
sentinel: completionSentinel(completionToken),
463456
sentinelPattern: completionSentinelPattern(completionToken),
464-
echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
457+
echoedWrapperLines,
465458
onOutputLine: observe.onOutputLine,
466459
})
467460
: undefined;
468-
// PowerShell has no line-editor signal; keep its immediate write.
469-
const readiness =
470-
completionShell === "powershell"
471-
? undefined
472-
: yield* watchShellReadiness({
473-
threadId: input.threadId,
474-
terminalId,
475-
onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
476-
});
477-
478-
yield* terminalManager
479-
.open({
480-
threadId: input.threadId,
481-
terminalId,
482-
cwd,
483-
worktreePath: input.worktreePath,
484-
env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
485-
})
486-
.pipe(
487-
Effect.mapError(
488-
(cause) =>
489-
new ProjectSetupScriptOperationError({
490-
...errorContext,
491-
operation: "openTerminal",
492-
cause,
493-
}),
494-
),
495-
Effect.onError(() =>
496-
Effect.sync(() => {
497-
observed?.unsubscribe();
498-
readiness?.unsubscribe();
499-
}),
500-
),
501-
);
461+
const readiness = yield* watchShellReadiness({
462+
threadId: input.threadId,
463+
terminalId,
464+
onStartupPrompt: observed?.flushPartialLine ?? Effect.void,
465+
});
466+
const { completionShell, commandLine } = yield* Effect.gen(function* () {
467+
const shell = yield* terminalManager
468+
.open({
469+
threadId: input.threadId,
470+
terminalId,
471+
cwd,
472+
worktreePath: input.worktreePath,
473+
env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" },
474+
})
475+
.pipe(
476+
Effect.andThen(() =>
477+
terminalManager
478+
.getShell({ threadId: input.threadId, terminalId })
479+
.pipe(Effect.catchTags({ TerminalNotRunningError: () => Effect.succeed(null) })),
480+
),
481+
Effect.mapError(
482+
(cause) =>
483+
new ProjectSetupScriptOperationError({
484+
...errorContext,
485+
operation: "openTerminal",
486+
cause,
487+
}),
488+
),
489+
);
490+
if (shell === null) {
491+
yield* observed?.abandon ?? Effect.void;
492+
return { completionShell: null, commandLine: null };
493+
}
494+
const completionShell = resolveCompletionShell(shell);
495+
let commandLine = script.command;
496+
if (observe && completionToken) {
497+
if (completionShell === null) {
498+
yield* terminalManager.closeIdle({ threadId: input.threadId, terminalId });
499+
return yield* new ProjectSetupScriptUnsupportedShellError({ shell });
500+
}
501+
commandLine = wrapCommandForCompletion(
502+
script.command,
503+
completionShell,
504+
completionSentinel(completionToken),
505+
);
506+
}
507+
echoedWrapperLines.push(...commandLine.split("\r").filter((line) => line.length > 0));
508+
return { completionShell, commandLine };
509+
}).pipe(
510+
Effect.onError(() =>
511+
Effect.sync(() => {
512+
observed?.unsubscribe();
513+
readiness.unsubscribe();
514+
}),
515+
),
516+
);
502517

503518
// Return once the terminal exists so callers can show it while a startup prompt waits.
504-
yield* (readiness?.wait ?? Effect.succeed("ready" as const)).pipe(
519+
// PowerShell and cmd have no line-editor signal.
520+
yield* (
521+
completionShell === "posix" || completionShell === "fish"
522+
? readiness.wait
523+
: Effect.succeed("ready" as const)
524+
).pipe(
505525
Effect.flatMap((shell) =>
506-
shell === "exited"
526+
shell === "exited" || commandLine === null
507527
? Effect.void
508528
: terminalManager.write({
509529
threadId: input.threadId,
@@ -518,7 +538,7 @@ export const make = Effect.gen(function* () {
518538
cause,
519539
}).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
520540
),
521-
Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())),
541+
Effect.ensuring(Effect.sync(() => readiness.unsubscribe())),
522542
Effect.forkIn(serviceScope),
523543
);
524544

0 commit comments

Comments
 (0)