@devries-cameron20 / t3code Mirror · read-only / commits / f46f838bf2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 12:00 UTC

fix(server): setup scripts follow terminal shell fallbacks (#23576)

Co-authored-by: maria-rcks <maria@kuuro.net>

Afonso Ferreira committed Oct 30, 2026 at 20:53 UTC f46f838bf22460be5061d378723ff1c15f6d9417
4 files changed +252 -73
apps/server/src/project/ProjectSetupScriptRunner.test.ts
+41 -13
@@ -1,7 +1,11 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 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";
9 import * as Deferred from "effect/Deferred";
10 import * as Effect from "effect/Effect";
11 import * as Fiber from "effect/Fiber";
@@ -36,6 +40,7 @@ const openSnapshot = (history: string): TerminalSessionSnapshot => ({
40 const makeHarness = Effect.fn(function* (options: {
41 readonly history?: string;
42 readonly opening?: Deferred.Deferred<void>;
43 + readonly shell?: string | null;
44 }) {
45 const listeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();
46 const writes = yield* Queue.unbounded<string>();
@@ -46,6 +51,10 @@ const makeHarness = Effect.fn(function* (options: {
51 ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never))
52 : Effect.void
53 ).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"),
58 subscribe: (listener) =>
59 Effect.sync(() => {
60 listeners.add(listener);
@@ -66,8 +75,6 @@ const makeHarness = Effect.fn(function* (options: {
75 NodeCrypto.layer,
76 ),
77 ),
69 - Effect.provideService(HostProcess.Platform, "darwin"),
70 - Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }),
78 );
79 const start = runner.runForThread({
80 threadId,
@@ -92,7 +99,12 @@ const makeHarness = Effect.fn(function* (options: {
99 return { start, listeners, writes, outputLines, emit };
100 });
101
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 +) {
108 const harness = yield* makeHarness(options);
109 const result = yield* harness.start;
110 const completion = result.status === "started" ? result.completion : undefined;
@@ -101,6 +113,15 @@ const setup = Effect.fn(function* (options: { readonly history?: string } = {})
113 });
114
115 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 +
125 it.effect("shows a startup prompt and types only once the line editor starts", () =>
126 Effect.gen(function* () {
127 const { result, writes, outputLines, emit } = yield* setup();
@@ -160,13 +181,20 @@ describe("ProjectSetupScriptRunner", () => {
181 }),
182 );
183
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 + }),
199 );
200 });
apps/server/src/project/ProjectSetupScriptRunner.ts
+79 -59
@@ -1,5 +1,4 @@
1 import { linkOriginIsFenced, ProjectId, type ProjectScript, ThreadId } from "@t3tools/contracts";
2 -import * as HostProcess from "@t3tools/shared/HostProcess";
2 import {
3 projectScriptRuntimeEnv,
4 projectScriptTerminalInput,
@@ -107,9 +106,19 @@ export class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedError<P
106 }
107 }
108
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 +
118 export const ProjectSetupScriptRunnerError = Schema.Union([
119 ProjectSetupScriptOperationError,
120 ProjectSetupScriptProjectNotFoundError,
121 + ProjectSetupScriptUnsupportedShellError,
122 ]);
123 export type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;
124
@@ -159,13 +168,9 @@ function lineEditorReading(text: string, previous: boolean): boolean {
168
169 type CompletionShell = "posix" | "fish" | "powershell";
170
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;
174 if (name === "fish") return "fish";
175 if (name === "pwsh" || name === "powershell") return "powershell";
176 return "posix";
@@ -196,10 +201,6 @@ export const make = Effect.gen(function* () {
201 const serverSettings = yield* ServerSettings.ServerSettingsService;
202 const crypto = yield* Crypto.Crypto;
203 const serviceScope = yield* Effect.scope;
199 - const completionShell = resolveCompletionShell(
200 - yield* HostProcess.Platform,
201 - yield* HostProcess.Environment,
202 - );
204
205 const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")(
206 function* (input: {
@@ -444,15 +445,7 @@ export const make = Effect.gen(function* () {
445 const completionToken = observe
446 ? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)).replaceAll("-", "")
447 : 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[] = [];
449 // Subscribe before opening so neither startup activity nor the sentinel can race the listeners.
450 const observed =
451 observe && completionToken
@@ -461,49 +454,76 @@ export const make = Effect.gen(function* () {
454 terminalId,
455 sentinel: completionSentinel(completionToken),
456 sentinelPattern: completionSentinelPattern(completionToken),
464 - echoedWrapperLines: commandLine.split("\r").filter((line) => line.length > 0),
457 + echoedWrapperLines,
458 onOutputLine: observe.onOutputLine,
459 })
460 : 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 + );
517
518 // 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(
525 Effect.flatMap((shell) =>
506 - shell === "exited"
526 + shell === "exited" || commandLine === null
527 ? Effect.void
528 : terminalManager.write({
529 threadId: input.threadId,
@@ -518,7 +538,7 @@ export const make = Effect.gen(function* () {
538 cause,
539 }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)),
540 ),
521 - Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())),
541 + Effect.ensuring(Effect.sync(() => readiness.unsubscribe())),
542 Effect.forkIn(serviceScope),
543 );
544
apps/server/src/terminal/Manager.test.ts
+115
@@ -7,6 +7,7 @@ import {
7 type TerminalOpenInput,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 + ProjectId,
11 TerminalProviderInstanceNotFoundError,
12 } from "@t3tools/contracts";
13 import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -31,8 +32,11 @@ import * as SynchronizedRef from "effect/SynchronizedRef";
32 import * as TestClock from "effect/testing/TestClock";
33 import { expect, vi } from "vite-plus/test";
34
35 +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
36 import * as ProcessRunner from "../processRunner.ts";
37 import * as ServerSettings from "../serverSettings.ts";
38 +import * as ProjectService from "../project/ProjectService.ts";
39 +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
40 import * as TerminalManager from "./Manager.ts";
41 import { terminalOutputStream } from "./OutputProtocol.ts";
42 import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
@@ -1441,6 +1445,61 @@ it.layer(
1445 }),
1446 );
1447
1448 + it.effect(
1449 + "writes completion syntax for the fallback shell instead of the configured fish shell",
1450 + () =>
1451 + Effect.gen(function* () {
1452 + const env = { SHELL: "/missing/fish" };
1453 + const { manager, ptyAdapter, baseDir } = yield* createManager(5, { env }).pipe(
1454 + Effect.provide(layerWithHostPlatform("linux")),
1455 + );
1456 + ptyAdapter.spawnFailures.push(new Error("spawn fish ENOENT"));
1457 + const written = yield* Deferred.make<void>();
1458 + const terminals = TerminalManager.TerminalManager.of({
1459 + ...manager,
1460 + write: (input) =>
1461 + manager.write(input).pipe(Effect.tap(() => Deferred.succeed(written, undefined))),
1462 + });
1463 + const runner = yield* ProjectSetupScriptRunner.make.pipe(
1464 + Effect.provide(
1465 + Layer.mergeAll(
1466 + Layer.succeed(TerminalManager.TerminalManager, terminals),
1467 + Layer.mock(ProjectService.ProjectService)({}),
1468 + Layer.mock(ProjectionStore.ProjectionStoreV2)({
1469 + getThreadShell: () => Effect.succeed(null),
1470 + }),
1471 + ServerSettings.layerTest(),
1472 + Layer.succeed(HostProcess.Platform, "linux"),
1473 + Layer.succeed(HostProcess.Environment, env),
1474 + ),
1475 + ),
1476 + );
1477 + yield* runner.runForThread({
1478 + threadId: "thread-setup-fallback",
1479 + worktreePath: baseDir,
1480 + project: {
1481 + id: ProjectId.make("project-setup-fallback"),
1482 + workspaceRoot: baseDir,
1483 + scripts: [
1484 + {
1485 + id: "setup",
1486 + name: "Setup",
1487 + command: "echo setup-ready",
1488 + icon: "play",
1489 + runOnWorktreeCreate: true,
1490 + },
1491 + ],
1492 + },
1493 + observeCompletion: {},
1494 + });
1495 + const process = ptyAdapter.processes[0]!;
1496 + process.emitData("\x1b[?2004h");
1497 + yield* Deferred.await(written);
1498 + const command = process.writes[0]!;
1499 + expect(command).toContain('"$?"');
1500 + }),
1501 + );
1502 +
1503 it.effect("preserves Windows Path casing when appending managed ACP binaries", () =>
1504 Effect.gen(function* () {
1505 const fileSystem = yield* FileSystem.FileSystem;
@@ -1534,6 +1593,62 @@ it.layer(
1593 }),
1594 );
1595
1596 + it.effect("closes an idle cmd fallback before rejecting its completion wrapper", () =>
1597 + Effect.gen(function* () {
1598 + const { manager, ptyAdapter, baseDir } = yield* createManager(5, {
1599 + env: { SystemRoot: "C:\\Windows" },
1600 + subprocessInspector: () =>
1601 + Effect.succeed({
1602 + hasRunningSubprocess: false,
1603 + childCommand: null,
1604 + processIds: [],
1605 + }),
1606 + }).pipe(Effect.provide(layerWithHostPlatform("win32")));
1607 + ptyAdapter.spawnFailures.push(
1608 + new Error("spawn pwsh ENOENT"),
1609 + new Error("spawn WindowsPowerShell ENOENT"),
1610 + new Error("spawn powershell ENOENT"),
1611 + );
1612 + const runner = yield* ProjectSetupScriptRunner.make.pipe(
1613 + Effect.provide(
1614 + Layer.mergeAll(
1615 + Layer.succeed(TerminalManager.TerminalManager, manager),
1616 + Layer.mock(ProjectService.ProjectService)({}),
1617 + Layer.mock(ProjectionStore.ProjectionStoreV2)({
1618 + getThreadShell: () => Effect.succeed(null),
1619 + }),
1620 + ServerSettings.layerTest(),
1621 + ),
1622 + ),
1623 + );
1624 + const error = yield* runner
1625 + .runForThread({
1626 + threadId: "thread-cmd-fallback",
1627 + worktreePath: baseDir,
1628 + project: {
1629 + id: ProjectId.make("project-cmd-fallback"),
1630 + workspaceRoot: baseDir,
1631 + scripts: [
1632 + {
1633 + id: "setup",
1634 + name: "Setup",
1635 + command: "echo setup-ready",
1636 + icon: "play",
1637 + runOnWorktreeCreate: true,
1638 + },
1639 + ],
1640 + },
1641 + observeCompletion: {},
1642 + })
1643 + .pipe(Effect.flip);
1644 +
1645 + expect(error._tag).toBe("ProjectSetupScriptUnsupportedShellError");
1646 + expect(ptyAdapter.spawnInputs.at(-1)?.shell).toBe("C:\\Windows\\System32\\cmd.exe");
1647 + expect(ptyAdapter.processes[0]?.writes).toEqual([]);
1648 + expect(ptyAdapter.processes[0]?.killed).toBe(true);
1649 + }),
1650 + );
1651 +
1652 it.effect("turns off fish terminal queries unless the user chose query-term", () =>
1653 Effect.gen(function* () {
1654 for (const [platform, env, runtimeEnv, expected] of [
apps/server/src/terminal/Manager.ts
+17 -1
@@ -172,6 +172,8 @@ export class TerminalManager extends Context.Service<
172 input: TerminalOpenInput,
173 ) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
174
175 + readonly getShell: (input: TerminalObserveInput) => Effect.Effect<string, TerminalError>;
176 +
177 /**
178 * Attached viewers share one PTY sized to the smallest of them, so a narrow client
179 * still sees the whole TUI. Streams and resizes with the same `viewerId` (one client
@@ -296,6 +298,7 @@ interface TerminalSessionState {
298 cols: number;
299 rows: number;
300 process: PtyAdapter.PtyProcess | null;
301 + shell: string | null;
302 unsubscribeData: (() => void) | null;
303 unsubscribeExit: (() => void) | null;
304 hasRunningSubprocess: boolean;
@@ -2370,7 +2373,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2373 index = 0,
2374 lastError: PtyAdapter.PtySpawnError | null = null,
2375 ): Effect.fn.Return<
2373 - { process: PtyAdapter.PtyProcess; shellLabel: string },
2376 + { process: PtyAdapter.PtyProcess; shell: string; shellLabel: string },
2377 PtyAdapter.PtySpawnError
2378 > {
2379 if (index >= shellCandidates.length) {
@@ -2413,6 +2416,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2416 if (attempt._tag === "Success") {
2417 return {
2418 process: attempt.success,
2419 + shell: candidate.shell,
2420 shellLabel: formatShellCandidate(candidate),
2421 };
2422 }
@@ -2441,6 +2445,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2445 const startingAt = yield* nowIso;
2446 yield* modifyManagerState((state) => {
2447 session.status = "starting";
2448 + session.shell = null;
2449 session.cwd = input.cwd;
2450 session.worktreePath = input.worktreePath ?? null;
2451 session.cols = input.cols;
@@ -2515,6 +2520,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2520 };
2521 yield* modifyManagerState((state) => {
2522 session.process = ptyProcess;
2523 + session.shell = spawnResult.shell;
2524 session.pid = processPid;
2525 session.status = "running";
2526 // onExit may replay an exit immediately; accept it before subscribing.
@@ -2891,6 +2897,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2897 cols,
2898 rows,
2899 process: null,
2900 + shell: null,
2901 unsubscribeData: null,
2902 unsubscribeExit: null,
2903 hasRunningSubprocess: false,
@@ -2988,6 +2995,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2995 resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),
2996 );
2997
2998 + const getShell = Effect.fn("terminal.getShell")(function* (input: TerminalObserveInput) {
2999 + const session = yield* requireSession(input.threadId, input.terminalId);
3000 + if (session.status !== "running" || session.shell === null) {
3001 + return yield* new TerminalNotRunningError(input);
3002 + }
3003 + return session.shell;
3004 + });
3005 +
3006 const openOrAttachForStream = Effect.fnUntraced(function* (requestedInput: TerminalAttachInput) {
3007 const terminalId = requestedInput.terminalId;
3008 const input = withSharedGrid(toSessionKey(requestedInput.threadId, terminalId), requestedInput);
@@ -3472,6 +3487,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3487
3488 return TerminalManager.of({
3489 open,
3490 + getShell,
3491 attachStream,
3492 attachOutputStream,
3493 observeStream,