fix(terminal): settling a thread closes its idle shells (#13673)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-09-25 13:09:30 -07:00
1 parent fd996d15e2
commit 1a0c915c41
9 files changed
+318 -11

No files matched your search

@@ -26,6 +26,7 @@ import * as Tracer from "effect/Tracer";
import * as CheckpointStore from "../src/checkpointing/CheckpointStore.ts";
import { TextGeneration } from "../src/textGeneration/TextGeneration.ts";
import * as TerminalManager from "../src/terminal/Manager.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
@@ -340,6 +341,7 @@ export const makeOrchestrationIntegrationHarness = (
tryHandlePromptCommand: () => Effect.succeed(false),
}),
),
Layer.provide(Layer.mock(TerminalManager.TerminalManager)({ closeIdle: () => Effect.void })),
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitWorkflowLayer),
Layer.provideMerge(textGenerationLayer),
@@ -55,6 +55,7 @@ import {
import { ProviderAuthService } from "../../provider/Services/ProviderAuthService.ts";
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { TerminalManager } from "../../terminal/Manager.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -307,6 +308,7 @@ describe("ProviderCommandReactor", () => {
}),
);
const pruneWorktrees = vi.fn((_: { readonly cwd: string }) => Effect.void);
const closeIdleTerminals = vi.fn((_: { readonly threadId: string }) => Effect.void);
const createWorktree = vi.fn(
(input: { readonly refName: string; readonly path: string | null }) =>
Effect.succeed({ worktree: { path: input.path ?? "", refName: input.refName } }),
@@ -490,6 +492,7 @@ describe("ProviderCommandReactor", () => {
generateThreadTitle,
}),
),
Layer.provideMerge(Layer.mock(TerminalManager)({ closeIdle: closeIdleTerminals })),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
@@ -621,6 +624,7 @@ describe("ProviderCommandReactor", () => {
renameBranch,
pruneWorktrees,
createWorktree,
closeIdleTerminals,
refreshStatus,
generateBranchName,
generateThreadTitle,
@@ -4339,6 +4343,77 @@ describe("ProviderCommandReactor", () => {
expect(thread?.settledOverride).toBe("settled");
expect(thread?.session?.status).toBe("stopped");
expect(thread?.session?.providerInstanceId).toBe(ProviderInstanceId.make("codex_work"));
expect(harness.closeIdleTerminals).toHaveBeenCalledWith({
threadId: ThreadId.make("thread-1"),
});
}),
);
effectIt.effect("closes idle terminals when a thread without a session settles", () =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const terminalsClosed = yield* Deferred.make<void>();
harness.closeIdleTerminals.mockImplementation(() =>
Deferred.succeed(terminalsClosed, undefined).pipe(Effect.asVoid),
);
yield* harness.engine.dispatch({
type: "thread.settle",
commandId: CommandId.make("cmd-settle-without-session"),
threadId: ThreadId.make("thread-1"),
});
yield* Deferred.await(terminalsClosed);
yield* Effect.promise(() => harness.drain());
expect(harness.closeIdleTerminals).toHaveBeenCalledWith({
threadId: ThreadId.make("thread-1"),
});
expect(harness.stopSession).not.toHaveBeenCalled();
}),
);
effectIt.effect(
"keeps terminals when the thread is un-settled before its settle event runs",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const threadId = ThreadId.make("thread-1");
const firstCloseStarted = yield* Deferred.make<void>();
const releaseFirstClose = yield* Deferred.make<void>();
harness.closeIdleTerminals.mockImplementationOnce(() =>
Deferred.succeed(firstCloseStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseFirstClose)),
),
);
yield* harness.engine.dispatch({
type: "thread.settle",
commandId: CommandId.make("cmd-settle-first"),
threadId,
});
// The reactor is busy with the first settle while the user changes their mind.
yield* Deferred.await(firstCloseStarted);
yield* harness.engine.dispatch({
type: "thread.unsettle",
commandId: CommandId.make("cmd-unsettle-first"),
threadId,
reason: "user",
});
yield* harness.engine.dispatch({
type: "thread.settle",
commandId: CommandId.make("cmd-settle-second"),
threadId,
});
yield* harness.engine.dispatch({
type: "thread.unsettle",
commandId: CommandId.make("cmd-unsettle-second"),
threadId,
reason: "user",
});
yield* Deferred.succeed(releaseFirstClose, undefined);
yield* Effect.promise(() => harness.drain());
expect(harness.closeIdleTerminals).toHaveBeenCalledTimes(1);
}),
);
});
@@ -65,6 +65,7 @@ import {
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
import * as TerminalManager from "../../terminal/Manager.ts";
const isProviderAdapterProcessError = Schema.is(ProviderAdapterProcessError);
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
const isProviderAdapterValidationError = Schema.is(ProviderAdapterValidationError);
@@ -222,6 +223,7 @@ const make = Effect.gen(function* () {
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const terminalManager = yield* TerminalManager.TerminalManager;
/** Environment settings with the thread's project overrides applied. */
const projectSettingsForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const settings = yield* serverSettingsService.getSettings;
@@ -1822,11 +1824,14 @@ const make = Effect.gen(function* () {
return;
case "thread.settled": {
const thread = yield* projectionSnapshotQuery.getThreadShellById(event.payload.threadId);
if (
Option.isNone(thread) ||
thread.value.session == null ||
thread.value.session.status === "stopped"
) {
// A thread re-engaged before this event ran keeps its shells and session.
if (Option.isNone(thread) || thread.value.settledOverride !== "settled") {
return;
}
// Idle shells close so they stop holding the worktree. A terminal that
// runs a command (a dev server, an editor) stays for the user to close.
yield* terminalManager.closeIdle({ threadId: event.payload.threadId });
if (thread.value.session == null || thread.value.session.status === "stopped") {
return;
}
yield* orchestrationEngine.dispatch({
@@ -56,6 +56,7 @@ import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistr
import { ServerSettingsService } from "../serverSettings.ts";
import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
import { TextGeneration } from "../textGeneration/TextGeneration.ts";
import { TerminalManager } from "../terminal/Manager.ts";
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts";
import { importRecentAgentThreads } from "./AgentSessionImporter.ts";
@@ -931,6 +932,7 @@ it.layer(integrationLayer)("AgentSessionImporter integration", (it) => {
Layer.provide(Layer.mock(GitWorkflowService)({})),
Layer.provide(Layer.mock(VcsStatusBroadcaster)({})),
Layer.provide(Layer.mock(TextGeneration)({})),
Layer.provide(Layer.mock(TerminalManager)({ closeIdle: () => Effect.void })),
Layer.provide(ServerSettingsService.layerTest()),
);
@@ -58,7 +58,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
});
type TerminalOverrides = Pick<TerminalManager.TerminalManager["Service"], "open" | "write"> &
Partial<Pick<TerminalManager.TerminalManager["Service"], "subscribe">>;
Partial<Pick<TerminalManager.TerminalManager["Service"], "subscribe" | "closeIdle">>;
const makeTerminalManagerLayer = (overrides: TerminalOverrides) =>
Layer.succeed(TerminalManager.TerminalManager, {
@@ -67,6 +67,7 @@ const makeTerminalManagerLayer = (overrides: TerminalOverrides) =>
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
closeIdle: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
subscribeMetadata: () => Effect.succeed(() => undefined),
...overrides,
@@ -262,6 +263,7 @@ describe("ProjectSetupScriptRunner", () => {
listener = null;
});
});
const closeIdle = vi.fn(() => Effect.void);
const project = makeProject([
{
id: "setup",
@@ -329,14 +331,82 @@ describe("ProjectSetupScriptRunner", () => {
]);
// The subscription is torn down once the sentinel arrives.
expect(listener).toBeNull();
// A failed run keeps its shell open for a look.
expect(closeIdle).not.toHaveBeenCalled();
}).pipe(
Effect.provide(testLayer(project, { open, write, subscribe })),
Effect.provide(testLayer(project, { open, write, subscribe, closeIdle })),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
);
},
);
it.effect("closes the idle setup shell after a clean exit", () => {
const open = vi.fn(() =>
Effect.succeed({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
label: "setup-setup",
updatedAt: "2026-01-01T00:00:00.000Z",
}),
);
let written = "";
const write = vi.fn((input: { data: string }) =>
Effect.sync(() => void (written = input.data)),
);
let listener: ((event: TerminalEvent) => Effect.Effect<void>) | null = null;
const subscribe = vi.fn((next: (event: TerminalEvent) => Effect.Effect<void>) => {
listener = next;
return Effect.succeed(() => {
listener = null;
});
});
const closeIdle = vi.fn(() => Effect.void);
const project = makeProject([
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]);
return Effect.gen(function* () {
const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
const result = yield* runner.runForThread({
threadId: "thread-1",
projectCwd: "/repo/project",
worktreePath: "/repo/worktrees/a",
observeCompletion: {},
});
if (result.status !== "started" || !result.completion) {
return yield* Effect.die("expected an observed setup run");
}
const sentinel = /__T3_SETUP_DONE___[0-9a-f]{32}:/.exec(written)?.[0];
yield* listener!({
threadId: "thread-1",
terminalId: "setup-setup",
type: "output",
data: `${sentinel}0\r\n`,
});
expect((yield* result.completion).exitCode).toBe(0);
expect(closeIdle).toHaveBeenCalledWith({ threadId: "thread-1", terminalId: "setup-setup" });
}).pipe(
Effect.provide(testLayer(project, { open, write, subscribe, closeIdle })),
Effect.provideService(HostProcessPlatform, "linux"),
Effect.provideService(HostProcessEnvironment, { SHELL: "/bin/zsh" }),
);
});
it.effect("unsubscribes from terminal output when the command cannot be written", () => {
const open = vi.fn(() =>
Effect.succeed({
@@ -36,6 +36,7 @@ export interface ProjectSetupScriptRunnerResultStarted {
* Resolves when the script's shell prints the completion sentinel. The
* exit code is null when the terminal exited or was closed before the
* sentinel arrived. Only present when `observeCompletion` was requested.
* An exit code of 0 closes the setup shell if it has nothing left running.
*/
readonly completion?: Effect.Effect<ProjectSetupScriptCompletion>;
}
@@ -412,6 +413,16 @@ export const make = Effect.gen(function* () {
Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())),
);
// A clean run leaves only an idle prompt behind; its output stays in the
// terminal history. A failed run keeps its shell open for a look.
const completion = observed?.completion.pipe(
Effect.tap(({ exitCode }) =>
exitCode === 0
? terminalManager.closeIdle({ threadId: input.threadId, terminalId })
: Effect.void,
),
);
return {
status: "started",
scriptId: script.id,
@@ -420,7 +431,7 @@ export const make = Effect.gen(function* () {
terminalId,
cwd,
async: script.async !== false,
...(observed ? { completion: observed.completion } : {}),
...(completion ? { completion } : {}),
} as const;
});
+67
View File
@@ -1230,6 +1230,73 @@ it.layer(
}),
);
it.effect("closes only a thread's idle shells, ignoring a helper forked from the shell", () =>
Effect.gen(function* () {
// FakePtyAdapter assigns pids from 9000 in open order.
const { manager, ptyAdapter } = yield* createManager(5, {
processTable: Effect.succeed([
{ pid: 9000, ppid: 1, name: "zsh" },
// An async prompt worker: a copy of the shell with no children.
{ pid: 100, ppid: 9000, name: "zsh" },
{ pid: 9001, ppid: 1, name: "zsh" },
{ pid: 200, ppid: 9001, name: "node" },
{ pid: 9002, ppid: 1, name: "zsh" },
// A subshell with a child is real work.
{ pid: 300, ppid: 9002, name: "zsh" },
{ pid: 301, ppid: 300, name: "sleep" },
{ pid: 9003, ppid: 1, name: "zsh" },
]),
}).pipe(Effect.provide(withHostPlatform("linux")));
yield* manager.open(openInput({ terminalId: "idle" }));
yield* manager.open(openInput({ terminalId: "dev-server" }));
yield* manager.open(openInput({ terminalId: "subshell" }));
yield* manager.open(openInput({ threadId: "thread-2" }));
yield* manager.closeIdle({ threadId: "thread-1" });
expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([
true,
false,
false,
false,
]);
}),
);
it.effect("keeps terminals that get input or output while closeIdle checks them", () =>
Effect.gen(function* () {
const ptyAdapter = new FakePtyAdapter();
// The typed command's process misses the snapshot, but its input or echo lands.
let duringCheck: (pid: number) => Effect.Effect<void> = () => Effect.void;
const { manager, getEvents } = yield* createManager(5, {
ptyAdapter,
subprocessPollIntervalMs: 60_000,
subprocessInspector: (pid) =>
duringCheck(pid).pipe(
Effect.as({ hasRunningSubprocess: false, childCommand: null, processIds: [] }),
),
});
yield* manager.open(openInput({ terminalId: "typed" }));
yield* manager.open(openInput({ terminalId: "echoed" }));
const [typed, echoed] = ptyAdapter.processes;
duringCheck = (pid) =>
pid === typed!.pid
? manager
.write({ threadId: "thread-1", terminalId: "typed", data: "make build\r" })
.pipe(Effect.orDie)
: Effect.gen(function* () {
echoed!.emitData("make build\r\n");
yield* waitFor(
Effect.map(getEvents, (events) => events.some((event) => event.type === "output")),
);
}).pipe(Effect.orDie);
yield* manager.closeIdle({ threadId: "thread-1" });
expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([false, false]);
}),
);
it.effect("backs off the spawned fallback when the resource monitor snapshot fails", () =>
Effect.gen(function* () {
const fallbackCalls: Array<number> = [];
+75 -2
View File
@@ -198,6 +198,17 @@ export class TerminalManager extends Context.Service<
*/
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
/**
* Close a thread's terminals that wait at an idle shell prompt. A terminal
* that runs a command stays open. When `terminalId` is set, only that
* terminal is considered. Used when a thread settles and when a setup
* script finishes.
*/
readonly closeIdle: (input: {
readonly threadId: string;
readonly terminalId?: string;
}) => Effect.Effect<void>;
/**
* Subscribe to terminal runtime events with a direct callback.
*
@@ -275,6 +286,8 @@ interface TerminalSessionState {
exitSignal: number | null;
updatedAt: string;
eventSequence: number;
/** Counts writes, so closeIdle can see input that has not echoed yet. */
inputCount: number;
cols: number;
rows: number;
process: PtyAdapter.PtyProcess | null;
@@ -692,7 +705,17 @@ function deriveSubprocessInspectResult(
terminalPid: number,
platform: NodeJS.Platform,
): TerminalSubprocessInspectResult {
const childPid = (snapshot.childrenByParent.get(terminalPid) ?? [])[0];
const commandName = (pid: number) =>
normalizeChildCommandName(snapshot.commandById.get(pid) ?? "", platform);
const shellName = commandName(terminalPid);
// Async prompt themes fork the shell into a helper that waits with no
// children of its own. That copy is not a command the user started.
const childPid = (snapshot.childrenByParent.get(terminalPid) ?? []).find(
(pid) =>
shellName === null ||
commandName(pid) !== shellName ||
(snapshot.childrenByParent.get(pid)?.length ?? 0) > 0,
);
if (childPid === undefined) {
return { hasRunningSubprocess: false, childCommand: null, processIds: [] };
}
@@ -707,7 +730,7 @@ function deriveSubprocessInspectResult(
pending.push(pid);
}
}
const normalized = normalizeChildCommandName(snapshot.commandById.get(childPid) ?? "", platform);
const normalized = commandName(childPid);
return {
hasRunningSubprocess: true,
childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,
@@ -2537,6 +2560,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
exitSignal: null,
updatedAt: yield* nowIso,
eventSequence: 0,
inputCount: 0,
cols,
rows,
process: null,
@@ -2877,6 +2901,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
terminalId,
});
}
session.inputCount += 1;
yield* Effect.try({
try: () => process.write(input.data),
catch: (cause) =>
@@ -2958,6 +2983,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
exitSignal: null,
updatedAt: yield* nowIso,
eventSequence: 0,
inputCount: 0,
cols,
rows,
process: null,
@@ -3042,6 +3068,52 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}),
);
const closeIdle: TerminalManager["Service"]["closeIdle"] = (input) =>
withThreadLock(
input.threadId,
Effect.gen(function* () {
const running = (yield* sessionsForThread(input.threadId)).filter(
(session): session is TerminalSessionState & { pid: number } =>
session.status === "running" &&
Number.isInteger(session.pid) &&
(input.terminalId === undefined || session.terminalId === input.terminalId),
);
if (running.length === 0) return;
// A command started during the process check can miss the snapshot,
// but its input or echo still lands. Both counters only grow, so the
// sum changes when either one does.
const activityMark = (session: TerminalSessionState) =>
session.eventSequence + session.inputCount;
const marks = new Map(
running.map((session) => [session.terminalId, activityMark(session)]),
);
// Inspect now instead of trusting the last poll, so a command started
// since then keeps its terminal.
const { inspector } = yield* acquireSubprocessInspector;
yield* Effect.forEach(
running,
(session) =>
inspector(session.pid).pipe(
Effect.flatMap((result) =>
result.hasRunningSubprocess ||
activityMark(session) !== marks.get(session.terminalId)
? Effect.void
: closeSession(input.threadId, session.terminalId, false),
),
),
{ discard: true },
);
}),
).pipe(
// The process check failed, so every terminal stays open.
Effect.catch((error) =>
Effect.logWarning("failed to close idle terminals", {
threadId: input.threadId,
error: error.message,
}),
),
);
return TerminalManager.of({
open,
attachStream,
@@ -3050,6 +3122,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
clear,
restart,
close,
closeIdle,
subscribe,
subscribeMetadata,
});
+3 -1
View File
@@ -90,7 +90,9 @@ Choose **Settle thread** from its menu to move finished work out of the active l
without deleting the conversation. **Un-settle thread** restores it to active work
and prevents automatic settlement until new activity resumes the usual rules.
Manually settling an idle thread dismisses unanswered async questions without
sending an answer or restarting the agent.
sending an answer or restarting the agent. Settling also closes the thread's
terminals that wait at an idle prompt, and keeps their output. A terminal that
runs a command, such as a dev server, stays open.
By default, environments settle inactive threads after three days and settle
threads whose pull request merged. A closed pull request can also settle an idle