From 7b4119b009826d8ab37ffc5ff5fdd52cab9c6978 Mon Sep 17 00:00:00 2001 From: angrojo Date: Fri, 20 Nov 2026 19:15:16 +0100 Subject: [PATCH 1/4] fix(server): prevent auto-settle while terminal has active subprocess Fixes #39745 by checking whether any terminal in the thread has an active subprocess before dispatching automatic settlement. --- .../ThreadSettlementService.test.ts | 22 ++++++++++ .../ThreadSettlementService.ts | 6 +++ apps/server/src/terminal/Manager.test.ts | 19 +++++++++ apps/server/src/terminal/Manager.ts | 42 +++++++++++++++++++ 4 files changed, 89 insertions(+) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index a17dde47c20b3..b20feef64eadd 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -588,6 +588,7 @@ interface HarnessOptions { input: ProjectSetupScriptRunner.ProjectSetupScriptRunnerInput, ) => Effect.Effect; readonly onCloseIdle?: () => Effect.Effect; + readonly hasActiveSubprocess?: (input: { readonly threadId: string }) => Effect.Effect; readonly currentThreads?: ReadonlyArray; readonly projections?: ProjectionStore.ProjectionStoreV2Shape; } @@ -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) => @@ -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)); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 7f6c1af1bd316..fd4b245244b8c 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -370,6 +370,9 @@ 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 thread; + } // 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(); @@ -396,6 +399,9 @@ export const make = Effect.gen(function* () { autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests, }); if (settledAt === null) return thread; + if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) { + return thread; + } const uuid = yield* random.uuidV4(); yield* orchestrator.dispatch({ type: "thread.auto-settle", diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 154dd4a445d34..dea7d3f31a3f0 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -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"]], diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index a294ba7f1afe2..feef0c9413063 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -242,6 +242,8 @@ export class TerminalManager extends Context.Service< readonly terminalId?: string; }) => Effect.Effect; + readonly hasActiveSubprocess: (input: { readonly threadId: string }) => Effect.Effect; + readonly subscribe: ( listener: (event: TerminalEvent) => Effect.Effect, registerCleanup?: (stop: () => void) => void, @@ -3938,6 +3940,45 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* closeIdle(input); }); + const hasActiveSubprocess: TerminalManager["Service"]["hasActiveSubprocess"] = (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), + ); + if (running.length === 0) return false; + const marks = new Map( + running.map((session) => [session.terminalId, terminalActivityMark(session)]), + ); + const { inspector: inspectorResult } = yield* acquireSubprocessInspector( + platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix, + ); + if (Result.isFailure(inspectorResult)) { + return running.some((session) => session.hasRunningSubprocess); + } + const inspector = inspectorResult.success; + for (const session of running) { + const result = yield* inspector(session.pid, session.shell); + if ( + result.hasRunningSubprocess || + terminalActivityMark(session) !== marks.get(session.terminalId) + ) { + return true; + } + } + return false; + }), + ).pipe( + Effect.catch((error) => + Effect.logWarning("failed to check active terminal subprocess", { + threadId: input.threadId, + error: error.message, + }).pipe(Effect.as(false)), + ), + ); + return TerminalManager.of({ open, getShell, @@ -3951,6 +3992,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func close, closeIdle, closeOnSettle, + hasActiveSubprocess, subscribe, subscribeMetadata, }); From 8ef51669474eb0686ad64f290b3fe67d7dce8dd7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 18:29:37 +0000 Subject: [PATCH 2/4] fix(server): skip settling a thread with a busy terminal for the sweep Read sessions without the thread lock, fall back to the last poll's answer when the process query fails instead of settling, and return null so a skipped thread does not go on to a pull request lookup. Co-Authored-By: Claude Opus 5.5 --- .../ThreadSettlementService.ts | 9 +-- apps/server/src/terminal/Manager.ts | 57 +++++++------------ 2 files changed, 23 insertions(+), 43 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index fd4b245244b8c..268bc8d9177b1 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -370,9 +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 thread; - } + 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(); @@ -399,9 +397,8 @@ export const make = Effect.gen(function* () { autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests, }); if (settledAt === null) return thread; - if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) { - 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", diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index feef0c9413063..dd578d2c27fb0 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3940,44 +3940,27 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* closeIdle(input); }); - const hasActiveSubprocess: TerminalManager["Service"]["hasActiveSubprocess"] = (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), - ); - if (running.length === 0) return false; - const marks = new Map( - running.map((session) => [session.terminalId, terminalActivityMark(session)]), - ); - const { inspector: inspectorResult } = yield* acquireSubprocessInspector( - platform === "win32" ? CLOSE_IDLE_QUERY_TIMEOUT.win32 : CLOSE_IDLE_QUERY_TIMEOUT.posix, - ); - if (Result.isFailure(inspectorResult)) { - return running.some((session) => session.hasRunningSubprocess); - } - const inspector = inspectorResult.success; - for (const session of running) { - const result = yield* inspector(session.pid, session.shell); - if ( - result.hasRunningSubprocess || - terminalActivityMark(session) !== marks.get(session.terminalId) - ) { - return true; - } - } - return false; - }), - ).pipe( - Effect.catch((error) => - Effect.logWarning("failed to check active terminal subprocess", { - threadId: input.threadId, - error: error.message, - }).pipe(Effect.as(false)), - ), + const hasActiveSubprocess = Effect.fn("terminal.hasActiveSubprocess")(function* (input: { + readonly threadId: string; + }) { + const running = (yield* sessionsForThread(input.threadId)).filter( + (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, From c74e8fb472d01e1cb6cf7f5e8eb9e65c0176dd2a Mon Sep 17 00:00:00 2001 From: angrojo Date: Fri, 20 Nov 2026 20:10:19 +0100 Subject: [PATCH 3/4] fix(server): treat terminal as active if session membership changes during inspection When hasActiveSubprocess runs without a thread lock, a new session can be opened while the subprocess query is in-flight. Revalidate the thread's running sessions before concluding all sessions are idle so a newly opened session is treated as active. Gemini 3.8 Flash on T3 Code --- apps/server/src/terminal/Manager.test.ts | 21 +++++++++++++++++++++ apps/server/src/terminal/Manager.ts | 13 ++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index dea7d3f31a3f0..e935dff7d0402 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1012,6 +1012,27 @@ it.layer( }), ); + it.effect("treats a thread as active if session membership changes during inspection", () => + Effect.gen(function* () { + let managerRef: TerminalManager.TerminalManager | null = null; + const { manager } = yield* createManager(5, { + processTable: Effect.gen(function* () { + if (managerRef !== null) { + yield* managerRef.open(openInput({ terminalId: "raced", threadId: "thread-raced" })); + } + return [ + { pid: 9000, ppid: 1, name: "zsh" }, + { pid: 100, ppid: 9000, name: "zsh" }, + ]; + }), + }).pipe(Effect.provide(layerWithHostPlatform("linux"))); + managerRef = manager; + yield* manager.open(openInput({ terminalId: "initial", threadId: "thread-raced" })); + + expect(yield* manager.hasActiveSubprocess({ threadId: "thread-raced" })).toBe(true); + }), + ); + it.effect.each([ ["linux", ["SIGHUP", "SIGTERM"]], ["win32", ["SIGTERM"]], diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index dd578d2c27fb0..0dc3f154f39e1 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3959,7 +3959,18 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.map((result) => result.hasRunningSubprocess), Effect.orElseSucceed(() => session.hasRunningSubprocess), ); - return Option.isSome(yield* Effect.findFirst(running, isActive)); + if (Option.isSome(yield* Effect.findFirst(running, isActive))) return true; + const latestRunning = (yield* sessionsForThread(input.threadId)).filter( + (session): session is TerminalSessionState & { pid: number } => + session.status === "running" && Number.isInteger(session.pid), + ); + return ( + latestRunning.length !== running.length || + latestRunning.some( + (session, index) => + session.terminalId !== running[index]?.terminalId || session.pid !== running[index]?.pid, + ) + ); }); return TerminalManager.of({ From 4a81dc549b88eb06caf70b450ffe954f4966d4a8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 20 Nov 2026 19:11:47 +0000 Subject: [PATCH 4/4] Revert "fix(server): treat terminal as active if session membership changes during inspection" This reverts commit c74e8fb472. Settlement sweeps every minute, so a terminal opened during one check is seen by the next sweep; the extra revalidation and its test are not needed. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/terminal/Manager.test.ts | 21 --------------------- apps/server/src/terminal/Manager.ts | 13 +------------ 2 files changed, 1 insertion(+), 33 deletions(-) diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index e935dff7d0402..dea7d3f31a3f0 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1012,27 +1012,6 @@ it.layer( }), ); - it.effect("treats a thread as active if session membership changes during inspection", () => - Effect.gen(function* () { - let managerRef: TerminalManager.TerminalManager | null = null; - const { manager } = yield* createManager(5, { - processTable: Effect.gen(function* () { - if (managerRef !== null) { - yield* managerRef.open(openInput({ terminalId: "raced", threadId: "thread-raced" })); - } - return [ - { pid: 9000, ppid: 1, name: "zsh" }, - { pid: 100, ppid: 9000, name: "zsh" }, - ]; - }), - }).pipe(Effect.provide(layerWithHostPlatform("linux"))); - managerRef = manager; - yield* manager.open(openInput({ terminalId: "initial", threadId: "thread-raced" })); - - expect(yield* manager.hasActiveSubprocess({ threadId: "thread-raced" })).toBe(true); - }), - ); - it.effect.each([ ["linux", ["SIGHUP", "SIGTERM"]], ["win32", ["SIGTERM"]], diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 0dc3f154f39e1..dd578d2c27fb0 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -3959,18 +3959,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.map((result) => result.hasRunningSubprocess), Effect.orElseSucceed(() => session.hasRunningSubprocess), ); - if (Option.isSome(yield* Effect.findFirst(running, isActive))) return true; - const latestRunning = (yield* sessionsForThread(input.threadId)).filter( - (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), - ); - return ( - latestRunning.length !== running.length || - latestRunning.some( - (session, index) => - session.terminalId !== running[index]?.terminalId || session.pid !== running[index]?.pid, - ) - ); + return Option.isSome(yield* Effect.findFirst(running, isActive)); }); return TerminalManager.of({