Skip to content
Merged
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
101 changes: 99 additions & 2 deletions apps/server/src/terminal/Manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
readonly killSignals: Array<string | undefined> = [];
readonly pid: number;
writeFailure: unknown | undefined;
resizeFailure: unknown | undefined;
private readonly dataListeners = new Set<(data: string) => void>();
private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
killed = false;
Expand All @@ -48,10 +50,16 @@ class FakePtyProcess implements PtyAdapter.PtyProcess {
}

write(data: string): void {
if (this.writeFailure !== undefined) {
throw this.writeFailure;
}
this.writes.push(data);
}

resize(cols: number, rows: number): void {
if (this.resizeFailure !== undefined) {
throw this.resizeFailure;
}
this.resizeCalls.push({ cols, rows });
}

Expand Down Expand Up @@ -435,6 +443,39 @@ it.layer(
fs.writeFileString(filePath, contents),
);

it.effect("reports a missing cwd without an artificial cause", () =>
Effect.gen(function* () {
const path = yield* Path.Path;

const { manager, baseDir } = yield* createManager();
const cwd = path.join(baseDir, "missing-cwd");
const error = yield* Effect.flip(manager.open(openInput({ cwd })));

expect(error).toMatchObject({
_tag: "TerminalCwdNotFoundError",
cwd,
});
expect("cause" in error).toBe(false);
}),
);

it.effect("reports a cwd that is not a directory", () =>
Effect.gen(function* () {
const path = yield* Path.Path;

const { manager, baseDir } = yield* createManager();
const cwd = path.join(baseDir, "cwd-file");
yield* writeFileString(cwd, "not a directory");
const error = yield* Effect.flip(manager.open(openInput({ cwd })));

expect(error).toMatchObject({
_tag: "TerminalCwdNotDirectoryError",
cwd,
});
expect("cause" in error).toBe(false);
}),
);

it.effect("preserves non-notFound cwd stat failures", () =>
Effect.gen(function* () {
if ((yield* HostProcessPlatform) === "win32") return;
Expand All @@ -452,9 +493,11 @@ it.layer(
);

expect(error).toMatchObject({
_tag: "TerminalCwdError",
_tag: "TerminalCwdStatError",
cwd: blockedCwd,
reason: "statFailed",
cause: {
_tag: "PlatformError",
},
});
}),
);
Expand Down Expand Up @@ -498,6 +541,60 @@ it.layer(
}),
);

it.effect("preserves structured context and causes for PTY I/O failures", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;

const writeCause = new Error("PTY input handle is unavailable");
process.writeFailure = writeCause;
const writeError = yield* Effect.flip(
manager.write({
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
data: "secret input that must not be attached to the error",
}),
);

expect(writeError).toMatchObject({
_tag: "TerminalWriteError",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
terminalPid: process.pid,
});
expect(writeError.cause).toBe(writeCause);
expect(writeError).not.toHaveProperty("data");

const resizeCause = new Error("PTY resize handle is unavailable");
process.resizeFailure = resizeCause;
const resizeError = yield* Effect.flip(
manager.resize({
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
cols: 132,
rows: 40,
}),
);

expect(resizeError).toMatchObject({
_tag: "TerminalResizeError",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
terminalPid: process.pid,
cols: 132,
rows: 40,
});
expect(resizeError.cause).toBe(resizeCause);

process.resizeFailure = undefined;
yield* manager.open(openInput({ cols: 132, rows: 40 }));
expect(process.resizeCalls).toEqual([{ cols: 132, rows: 40 }]);
}),
);

it.effect("ignores delayed resize requests after a terminal closes", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
Expand Down
122 changes: 87 additions & 35 deletions apps/server/src/terminal/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@
import {
DEFAULT_TERMINAL_ID,
TerminalCwdError,
TerminalCwdNotDirectoryError,
TerminalCwdNotFoundError,
TerminalCwdStatError,
TerminalError,
TerminalHistoryError,
TerminalNotRunningError,
TerminalResizeError,
TerminalSessionLookupError,
TerminalWriteError,
type TerminalAttachInput,
type TerminalAttachStreamEvent,
type TerminalClearInput,
Expand Down Expand Up @@ -58,10 +63,15 @@ import * as PtyAdapter from "./PtyAdapter.ts";

export {
TerminalCwdError,
TerminalCwdNotDirectoryError,
TerminalCwdNotFoundError,
TerminalCwdStatError,
TerminalError,
TerminalHistoryError,
TerminalNotRunningError,
TerminalResizeError,
TerminalSessionLookupError,
TerminalWriteError,
};

const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
Expand Down Expand Up @@ -190,6 +200,25 @@ interface TerminalSubprocessInspector {
): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError>;
}

const resizePtyProcess = (
session: TerminalSessionState,
process: PtyAdapter.PtyProcess,
cols: number,
rows: number,
) =>
Effect.try({
try: () => process.resize(cols, rows),
catch: (cause) =>
new TerminalResizeError({
threadId: session.threadId,
terminalId: session.terminalId,
terminalPid: process.pid,
cols,
rows,
cause,
}),
});

export interface ShellCandidate {
shell: string;
args?: string[];
Expand Down Expand Up @@ -1157,16 +1186,6 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const legacyHistoryPath = (threadId: string) =>
path.join(logsDir, `${legacySafeThreadId(threadId)}.log`);

const toTerminalHistoryError =
(operation: "read" | "truncate" | "migrate", threadId: string, terminalId: string) =>
(cause: unknown) =>
new TerminalHistoryError({
operation,
threadId,
terminalId,
cause,
});

const readManagerState = SynchronizedRef.get(managerStateRef);

const modifyManagerState = <A>(
Expand Down Expand Up @@ -1250,7 +1269,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
threadId,
terminalId,
signal: "SIGTERM",
error: error.message,
cause: error,
}).pipe(Effect.as(false)),
),
);
Expand All @@ -1274,7 +1293,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
threadId,
terminalId,
signal: "SIGKILL",
error: error.message,
cause: error,
}),
),
);
Expand Down Expand Up @@ -1372,16 +1391,29 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
if (
yield* fileSystem
.exists(nextPath)
.pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId)))
.pipe(
Effect.mapError(
(cause) => new TerminalHistoryError({ operation: "read", threadId, terminalId, cause }),
),
)
) {
const raw = yield* fileSystem
.readFileString(nextPath)
.pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId)));
.pipe(
Effect.mapError(
(cause) => new TerminalHistoryError({ operation: "read", threadId, terminalId, cause }),
),
);
const capped = capHistory(raw, historyLineLimit);
if (capped !== raw) {
yield* fileSystem
.writeFileString(nextPath, capped)
.pipe(Effect.mapError(toTerminalHistoryError("truncate", threadId, terminalId)));
.pipe(
Effect.mapError(
(cause) =>
new TerminalHistoryError({ operation: "truncate", threadId, terminalId, cause }),
),
);
}
return capped;
}
Expand All @@ -1394,18 +1426,33 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
if (
!(yield* fileSystem
.exists(legacyPath)
.pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))))
.pipe(
Effect.mapError(
(cause) =>
new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),
),
))
) {
return "";
}

const raw = yield* fileSystem
.readFileString(legacyPath)
.pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId)));
.pipe(
Effect.mapError(
(cause) =>
new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),
),
);
const capped = capHistory(raw, historyLineLimit);
yield* fileSystem
.writeFileString(nextPath, capped)
.pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId)));
.pipe(
Effect.mapError(
(cause) =>
new TerminalHistoryError({ operation: "migrate", threadId, terminalId, cause }),
),
);
yield* fileSystem.remove(legacyPath, { force: true }).pipe(
Effect.catch((cleanupError) =>
Effect.logWarning("failed to remove legacy terminal history", {
Expand Down Expand Up @@ -1472,20 +1519,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func

const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) {
const stats = yield* fileSystem.stat(cwd).pipe(
Effect.mapError(
(cause) =>
new TerminalCwdError({
cwd,
reason: cause.reason._tag === "NotFound" ? "notFound" : "statFailed",
cause,
}),
),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? new TerminalCwdNotFoundError({ cwd })
: new TerminalCwdStatError({ cwd, cause }),
}),
);
if (stats.type !== "Directory") {
return yield* new TerminalCwdError({
cwd,
reason: "notDirectory",
});
return yield* new TerminalCwdNotDirectoryError({ cwd });
}
});

Expand Down Expand Up @@ -1881,7 +1923,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
yield* Effect.logError("failed to start terminal", {
threadId: session.threadId,
terminalId: session.terminalId,
error: message,
cause: error,
...(startedShell ? { shell: startedShell } : {}),
});
}
Expand Down Expand Up @@ -2168,10 +2210,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}

if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
yield* resizePtyProcess(liveSession, liveSession.process, targetCols, targetRows);
liveSession.cols = targetCols;
liveSession.rows = targetRows;
liveSession.updatedAt = yield* nowIso;
liveSession.process.resize(targetCols, targetRows);
}

return snapshot(liveSession);
Expand Down Expand Up @@ -2219,10 +2261,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
session.status === "running" &&
(session.cols !== targetCols || session.rows !== targetRows)
) {
const process = session.process;
yield* resizePtyProcess(session, process, targetCols, targetRows);
session.cols = targetCols;
session.rows = targetRows;
session.updatedAt = yield* nowIso;
yield* Effect.sync(() => session.process?.resize(targetCols, targetRows));
}

return snapshot(session);
Expand Down Expand Up @@ -2409,7 +2452,16 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
terminalId,
});
}
yield* Effect.sync(() => process.write(input.data));
yield* Effect.try({
try: () => process.write(input.data),
catch: (cause) =>
new TerminalWriteError({
threadId: input.threadId,
terminalId,
terminalPid: process.pid,
cause,
}),
});
});

const resizeLocked = Effect.fn("terminal.resize")(function* (input: TerminalResizeInput) {
Expand All @@ -2422,10 +2474,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
if (!process || session.value.status !== "running") {
return;
}
yield* resizePtyProcess(session.value, process, input.cols, input.rows);
session.value.cols = input.cols;
session.value.rows = input.rows;
session.value.updatedAt = yield* nowIso;
yield* Effect.sync(() => process.resize(input.cols, input.rows));
});

const resize: TerminalManager["Service"]["resize"] = (input) =>
Expand Down
Loading
Loading