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
22 changes: 22 additions & 0 deletions apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,7 @@ interface HarnessOptions {
input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput,
) => Effect.Effect<void>;
readonly onCloseIdle?: () => Effect.Effect<void>;
readonly hasActiveSubprocess?: (input: { readonly threadId: string }) => Effect.Effect<boolean>;
readonly currentThreads?: ReadonlyArray<OrchestrationV2AppThread>;
readonly projections?: ProjectionStore.ProjectionStoreV2Shape;
}
Expand Down Expand Up @@ -721,6 +722,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options:
Layer.mock(TerminalManager.TerminalManager)({
closeOnSettle: (input) =>
Queue.offer(closedIdle, input).pipe(Effect.andThen(options.onCloseIdle?.() ?? Effect.void)),
hasActiveSubprocess: (input) => options.hasActiveSubprocess?.(input) ?? Effect.succeed(false),
}),
Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({
runForThread: (input) =>
Expand Down Expand Up @@ -939,6 +941,26 @@ describe("ThreadSettlementServiceV2 worker", () => {
}),
);

it.effect("does not auto-settle a thread whose terminal has an active subprocess", () =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const thread = makeThread("active-terminal");
const fixture = yield* makeHarness({
snapshot: makeSnapshot([thread]),
settings: {
...DEFAULT_SERVER_SETTINGS,
sidebarAutoSettleAfterDays: 3,
},
hasActiveSubprocess: ({ threadId }) => Effect.succeed(threadId === thread.id),
});
yield* Effect.gen(function* () {
const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
yield* startHarness(service, fixture.activation, fixture.snapshotReads);
expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([]);
}).pipe(Effect.provide(fixture.layer));
}),
);

it.effect("settles only the project opted in while environment settlement is disabled", () =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/orchestration-v2/ThreadSettlementService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ export const make = Effect.gen(function* () {
const settleThread = Effect.fnUntraced(
function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) {
if (thread.lineage.relationshipToParent === "subagent") {
if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) return null;
// The store returns a subagent only once its parent is done, so it
// settles with the parent and never runs its own lookup.
const uuid = yield* random.uuidV4();
Expand All @@ -396,6 +397,8 @@ export const make = Effect.gen(function* () {
autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests,
});
if (settledAt === null) return thread;
// A terminal still running a program keeps its thread open; a later sweep settles it.
if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) return null;
const uuid = yield* random.uuidV4();
yield* orchestrator.dispatch({
type: "thread.auto-settle",
Expand Down
19 changes: 19 additions & 0 deletions apps/server/src/terminal/Manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,25 @@ it.layer(
}),
);

it.effect("reports whether any terminal session for a thread has an active subprocess", () =>
Effect.gen(function* () {
const { manager } = yield* createManager(5, {
processTable: Effect.succeed([
{ pid: 9000, ppid: 1, name: "zsh" },
{ pid: 100, ppid: 9000, name: "zsh" },
{ pid: 9001, ppid: 1, name: "zsh" },
{ pid: 200, ppid: 9001, name: "node" },
]),
}).pipe(Effect.provide(layerWithHostPlatform("linux")));
yield* manager.open(openInput({ terminalId: "idle", threadId: "thread-idle" }));
yield* manager.open(openInput({ terminalId: "dev-server", threadId: "thread-active" }));

expect(yield* manager.hasActiveSubprocess({ threadId: "thread-none" })).toBe(false);
expect(yield* manager.hasActiveSubprocess({ threadId: "thread-idle" })).toBe(false);
expect(yield* manager.hasActiveSubprocess({ threadId: "thread-active" })).toBe(true);
}),
);

it.effect.each([
["linux", ["SIGHUP", "SIGTERM"]],
["win32", ["SIGTERM"]],
Expand Down
25 changes: 25 additions & 0 deletions apps/server/src/terminal/Manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,8 @@ export class TerminalManager extends Context.Service<
readonly terminalId?: string;
}) => Effect.Effect<void>;

readonly hasActiveSubprocess: (input: { readonly threadId: string }) => Effect.Effect<boolean>;

readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect<void>,
registerCleanup?: (stop: () => void) => void,
Expand Down Expand Up @@ -3938,6 +3940,28 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
yield* closeIdle(input);
});

const hasActiveSubprocess = Effect.fn("terminal.hasActiveSubprocess")(function* (input: {
readonly threadId: string;
}) {
const running = (yield* sessionsForThread(input.threadId)).filter(
Comment thread
gek0v marked this conversation as resolved.
Resolved
(session): session is TerminalSessionState & { pid: number } =>
session.status === "running" && Number.isInteger(session.pid),
);
if (running.length === 0) return false;
const { inspector } = yield* acquireSubprocessInspector(
platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix,
);
// A failed process query falls back to the last poll's answer.
const isActive = (session: (typeof running)[number]) =>
Result.isFailure(inspector)
? Effect.succeed(session.hasRunningSubprocess)
: inspector.success(session.pid, session.shell).pipe(
Effect.map((result) => result.hasRunningSubprocess),
Effect.orElseSucceed(() => session.hasRunningSubprocess),
);
return Option.isSome(yield* Effect.findFirst(running, isActive));
});

return TerminalManager.of({
open,
getShell,
Expand All @@ -3951,6 +3975,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
close,
closeIdle,
closeOnSettle,
hasActiveSubprocess,
subscribe,
subscribeMetadata,
});
Expand Down
Loading