Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/server/src/project/ProjectSetupScriptRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ const makeTerminalManagerLayer = (
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
resolveAvailableShells: () => Effect.succeed([]),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
subscribeMetadata: () => Effect.succeed(() => undefined),
Expand Down
16 changes: 12 additions & 4 deletions apps/server/src/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ const collectQueueUntil = Effect.fn("TransferBudget.collectQueueUntil")(function
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as ServerConfig from "./config.ts";
import { makeRoutesLayer } from "./server.ts";
import { isThreadDetailEvent, resolveAvailableEditorsForConfig } from "./ws.ts";
import { isThreadDetailEvent, resolveAvailableCapabilitiesForConfig } from "./ws.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as GitManager from "./git/GitManager.ts";
import * as Keybindings from "./keybindings.ts";
Expand Down Expand Up @@ -736,6 +736,7 @@ const buildAppUnderTest = (options?: {
),
Layer.provide(
Layer.mock(TerminalManager.TerminalManager)({
resolveAvailableShells: () => Effect.succeed([]),
...options?.layers?.terminalManager,
}),
),
Expand Down Expand Up @@ -3989,7 +3990,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {

it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
yield* buildAppUnderTest({
layers: {
terminalManager: {
resolveAvailableShells: () => Effect.succeed(["zsh", "fish"]),
},
},
});

const { response: bootstrapResponse, cookie } = yield* bootstrapBrowserSession();

Expand All @@ -4006,15 +4013,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => {

assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId);
assert.equal(response.auth.policy, "desktop-managed-local");
assert.deepEqual(response.availableTerminalShells, ["zsh", "fish"]);
assert.equal(response.shellResumeCompletionMarker, true);
assert.equal(response.threadResumeCompletionMarker, true);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);

it.effect("does not block server config when editor discovery never resolves", () =>
it.effect("does not block server config when capability discovery never resolves", () =>
Effect.gen(function* () {
const discoveryInterrupted = yield* Deferred.make<void>();
const responseFiber = yield* resolveAvailableEditorsForConfig(
const responseFiber = yield* resolveAvailableCapabilitiesForConfig(
Effect.never.pipe(
Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)),
),
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,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
38 changes: 38 additions & 0 deletions apps/server/src/terminal/Manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ const multiTerminalHistoryLogPath = (

interface CreateManagerOptions {
shellResolver?: () => string;
terminalShellResolver?: () => Effect.Effect<"system" | "zsh" | "bash" | "fish">;
env?: NodeJS.ProcessEnv;
subprocessInspector?: (terminalPid: number) => Effect.Effect<{
readonly hasRunningSubprocess: boolean;
Expand Down Expand Up @@ -243,6 +244,9 @@ const createManager = (
historyLineLimit,
ptyAdapter,
...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}),
...(options.terminalShellResolver !== undefined
? { terminalShellResolver: options.terminalShellResolver }
: {}),
...(options.env !== undefined ? { env: options.env } : {}),
...(options.subprocessInspector !== undefined
? { subprocessInspector: options.subprocessInspector }
Expand Down Expand Up @@ -1490,6 +1494,40 @@ it.layer(
}),
);

it.effect("uses the configured shell for each new terminal", () =>
Effect.gen(function* () {
if ((yield* HostProcessPlatform) === "win32") return;
let terminalShell: "bash" | "fish" = "bash";
const { manager, ptyAdapter } = yield* createManager(5, {
env: { SHELL: "/bin/zsh" },
terminalShellResolver: () => Effect.succeed(terminalShell),
});

yield* manager.open(openInput({ terminalId: "term-1" }));
terminalShell = "fish";
yield* manager.open(openInput({ terminalId: "term-2" }));

expect(ptyAdapter.spawnInputs.map((input) => input.shell)).toEqual(["bash", "fish"]);
}),
);

it.effect("discovers only installed selectable shells", () =>
Effect.gen(function* () {
if ((yield* HostProcessPlatform) === "win32") return;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-shells-" });
for (const shell of ["bash", "fish"] as const) {
const executable = path.join(binDir, shell);
yield* writeFileString(executable, "#!/bin/sh\n");
yield* chmod(executable, 0o755);
}
const { manager } = yield* createManager(5, { env: { PATH: binDir } });

expect(yield* manager.resolveAvailableShells()).toEqual(["bash", "fish"]);
}),
);

it.effect("bridges PTY callbacks back into Effect-managed event streaming", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents } = yield* createManager(5, {
Expand Down
64 changes: 60 additions & 4 deletions apps/server/src/terminal/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
*/
import {
DEFAULT_TERMINAL_ID,
INSTALLED_TERMINAL_SHELLS,
type InstalledTerminalShell,
TerminalCwdError,
TerminalCwdNotDirectoryError,
TerminalCwdNotFoundError,
Expand All @@ -18,6 +20,7 @@ import {
TerminalResizeError,
TerminalSessionLookupError,
TerminalWriteError,
type TerminalShell,
type TerminalAttachInput,
type TerminalAttachStreamEvent,
type TerminalClearInput,
Expand All @@ -34,6 +37,7 @@ import {
} from "@t3tools/contracts";
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isCommandAvailable } from "@t3tools/shared/shell";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as DateTime from "effect/DateTime";
import * as Context from "effect/Context";
Expand All @@ -52,6 +56,7 @@ import * as Semaphore from "effect/Semaphore";
import * as SynchronizedRef from "effect/SynchronizedRef";

import * as ServerConfig from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import {
increment,
terminalRestartsTotal,
Expand Down Expand Up @@ -161,6 +166,9 @@ export class TerminalManager extends Context.Service<
input: TerminalRestartInput,
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;

/** Discover selectable shells installed on this environment. */
readonly resolveAvailableShells: () => Effect.Effect<ReadonlyArray<InstalledTerminalShell>>;

/**
* Close an active terminal session.
*
Expand Down Expand Up @@ -531,12 +539,12 @@ function uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellC
}

function resolveShellCandidates(
shellResolver: () => string,
requestedShell: string,
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): ShellCandidate[] {
const requested = shellCandidateFromCommand(
normalizeShellCommand(shellResolver(), platform),
normalizeShellCommand(requestedShell, platform),
platform,
);

Expand All @@ -557,13 +565,26 @@ function resolveShellCandidates(
shellCandidateFromCommand(normalizeShellCommand(env.SHELL, platform), platform),
shellCandidateFromCommand("/bin/zsh", platform),
shellCandidateFromCommand("/bin/bash", platform),
shellCandidateFromCommand("/usr/bin/fish", platform),
shellCandidateFromCommand("/bin/sh", platform),
shellCandidateFromCommand("zsh", platform),
shellCandidateFromCommand("bash", platform),
shellCandidateFromCommand("fish", platform),
shellCandidateFromCommand("sh", platform),
]);
}

function configuredShellCommand(
preference: TerminalShell,
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
): string {
if (preference === "system") {
return defaultShellResolver(platform, env);
}
return preference;
}

function isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {
const queue: unknown[] = [error];
const seen = new Set<unknown>();
Expand Down Expand Up @@ -1181,6 +1202,7 @@ interface TerminalManagerOptions {
historyLineLimit?: number;
ptyAdapter: PtyAdapter.PtyAdapter["Service"];
shellResolver?: () => string;
terminalShellResolver?: () => Effect.Effect<TerminalShell>;
env?: NodeJS.ProcessEnv;
subprocessInspector?: TerminalSubprocessInspector;
subprocessPollIntervalMs?: number;
Expand All @@ -1199,11 +1221,21 @@ interface TerminalManagerOptions {

export const make = Effect.fn("TerminalManager.make")(function* () {
const { terminalLogsDir } = yield* ServerConfig.ServerConfig;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const ptyAdapter = yield* PtyAdapter.PtyAdapter;
const portDiscovery = yield* PortScanner.PortDiscovery;
return yield* makeWithOptions({
logsDir: terminalLogsDir,
ptyAdapter,
terminalShellResolver: () =>
serverSettings.getSettings.pipe(
Effect.map((settings) => settings.terminalShell),
Effect.catch((error) =>
Effect.logWarning("failed to read terminal shell setting; using the system shell", {
cause: error,
}).pipe(Effect.as("system" as const)),
),
),
registerTerminalProcesses: portDiscovery.registerTerminalProcesses,
unregisterTerminal: portDiscovery.unregisterTerminal,
});
Expand All @@ -1225,7 +1257,16 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
// things like PSModulePath, DISPLAY, proxies, and toolchain variables.
// `options.env` is the test seam.
const baseEnv = options.env ?? process.env;
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
const shellResolver = options.shellResolver;
const terminalShellResolver = options.terminalShellResolver;
const resolveRequestedShell = shellResolver
? () => Effect.sync(shellResolver)
: terminalShellResolver
? () =>
terminalShellResolver().pipe(
Effect.map((preference) => configuredShellCommand(preference, platform, baseEnv)),
)
: () => Effect.succeed(defaultShellResolver(platform, baseEnv));
const processRunner = yield* ProcessRunner.ProcessRunner;
const subprocessInspector =
options.subprocessInspector ??
Expand All @@ -1241,6 +1282,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const registerTerminalProcesses = options.registerTerminalProcesses ?? (() => Effect.void);
const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void);

const resolveAvailableShells = Effect.fn("terminal.resolveAvailableShells")(function* () {
const available: InstalledTerminalShell[] = [];
for (const shell of INSTALLED_TERMINAL_SHELLS) {
const installed = yield* isCommandAvailable(shell, { env: baseEnv }).pipe(
Effect.provideService(HostProcessPlatform, platform),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
if (installed) available.push(shell);
}
return available;
});

yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);

const managerStateRef = yield* SynchronizedRef.make<TerminalManagerState>({
Expand Down Expand Up @@ -1920,7 +1974,8 @@ 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 requestedShell = yield* resolveRequestedShell();
const shellCandidates = resolveShellCandidates(requestedShell, platform, baseEnv);
const terminalEnv = createTerminalSpawnEnv(baseEnv, session.runtimeEnv);
const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);
ptyProcess = spawnResult.process;
Expand Down Expand Up @@ -2698,6 +2753,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
resize,
clear,
restart,
resolveAvailableShells,
close,
subscribe,
subscribeMetadata,
Expand Down
18 changes: 12 additions & 6 deletions apps/server/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,13 @@ import * as RelayClient from "@t3tools/shared/relayClient";
const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);

const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);
const SYSTEM_CAPABILITY_DISCOVERY_TIMEOUT = Duration.seconds(5);

export const resolveAvailableEditorsForConfig = <A, E, R>(
export const resolveAvailableCapabilitiesForConfig = <A, E, R>(
discovery: Effect.Effect<ReadonlyArray<A>, E, R>,
) =>
discovery.pipe(
Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT),
Effect.timeoutOption(SYSTEM_CAPABILITY_DISCOVERY_TIMEOUT),
Effect.map(Option.getOrElse(() => [])),
);

Expand Down Expand Up @@ -998,6 +998,13 @@ const makeWsRpcLayer = (
);
const environment = yield* serverEnvironment.getDescriptor;
const auth = yield* serverAuth.getDescriptor();
const [availableEditors, availableTerminalShells] = yield* Effect.all(
[
resolveAvailableCapabilitiesForConfig(externalLauncher.resolveAvailableEditors()),
resolveAvailableCapabilitiesForConfig(terminalManager.resolveAvailableShells()),
],
{ concurrency: "unbounded" },
);

return {
environment,
Expand All @@ -1007,9 +1014,8 @@ const makeWsRpcLayer = (
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers,
availableEditors: yield* resolveAvailableEditorsForConfig(
externalLauncher.resolveAvailableEditors(),
),
availableEditors,
availableTerminalShells,
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
Expand Down
21 changes: 21 additions & 0 deletions apps/web/src/components/settings/SettingsPanels.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
isProjectGroupingEnabled,
projectGroupingModeFromToggle,
resolveBackgroundActivityProfileOption,
resolveTerminalShellOptions,
} from "./SettingsPanels.logic";

describe("typography settings restore", () => {
Expand All @@ -32,6 +33,26 @@ describe("typography settings restore", () => {
});
});

describe("terminal shell options", () => {
it("shows only shells installed on the connected environment", () => {
expect(
resolveTerminalShellOptions({ installed: ["bash", "fish"], selected: "system" }),
).toEqual([
{ value: "system", installed: true },
{ value: "bash", installed: true },
{ value: "fish", installed: true },
]);
});

it("keeps an unavailable current selection visible but disabled", () => {
expect(resolveTerminalShellOptions({ installed: ["bash"], selected: "fish" })).toEqual([
{ value: "system", installed: true },
{ value: "bash", installed: true },
{ value: "fish", installed: false },
]);
});
});

describe("background activity settings restore", () => {
it("detects legacy interval values even when the structured setting is at its default", () => {
expect(
Expand Down
Loading
Loading