Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: finalize a runner TUI run whose PTY exit decides an owed merge gate (#11861)

Adam Eivybe76b9115ef7
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index b986b5590a..ac95bea60a 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -172,7 +172,16 @@ export async function createAgentTuiSession({
// response. Open the readiness gate before handing off to avoid discarding
// the TUI's first bracketed-paste/input-ready signals.
onInitialCommandSent?.();
- const session = await spawnTuiSessionViaRunner({
+ // An external session's exit wiring belongs to its owner (shell.js
+ // adoptPtySession), so this branch unregisters it, as agentRunnerSync.js
+ // does for a recovered run. Otherwise the record outlives the PTY and a
+ // later paste "succeeds" into the runner proxy, whose writes always report
+ // true (#11861). It runs BEFORE the controller sees the exit; `exited`
+ // keeps a `tui:exit` that beats the spawn response from registering a
+ // session that is already dead.
+ let session = null;
+ let exited = false;
+ session = await spawnTuiSessionViaRunner({
agentId,
taskId,
command: tuiConfig.spawnCommand,
@@ -183,9 +192,13 @@ export async function createAgentTuiSession({
doneSentinelPath,
securityScanGrant,
onData,
- onExit,
+ onExit: (event) => {
+ exited = true;
+ if (session) shellService.unregisterExternalSession(session.sessionId, { exitCode: event?.exitCode });
+ return onExit?.(event);
+ },
});
- shellService.registerExternalSession(session.sessionId, session.ptyProcess, sessionOptions);
+ if (!exited) shellService.registerExternalSession(session.sessionId, session.ptyProcess, sessionOptions);
// The runner owns this PTY, so it already returns the pty/pid pair the tail
// below would otherwise have to look up locally.
return session;
@@ -588,8 +601,7 @@ export async function spawnTuiAgent({
// this process. The controller's handleExit then finalizes the run while
// createAgentTuiSession is still awaiting that response. Do not revive the
// finalized agent by registering its returned session, timers, or active-agent
- // record; release the external shell session that was registered during the
- // late response.
+ // record; release any external shell session the late response registered.
if (controller.isTerminal()) {
if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);
return null;
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index cfcd01c9c5..af383bfd06 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -13,6 +13,7 @@ vi.mock('./shell.js', () => ({
getSession: vi.fn(),
getSessionProcess: vi.fn(),
registerExternalSession: vi.fn(),
+ unregisterExternalSession: vi.fn(),
}));
// Only the spawn rpc is faked. The refusal/ambiguity classifier is the real one
@@ -852,6 +853,13 @@ describe('spawnTuiAgent runtime', () => {
);
await capturedOnExit({ exitCode: 1, signal: 15 });
+
+ // The runner proxy accepts writes after its PTY died, so only removing the
+ // record makes a later paste report the session gone (#11861) — and it has
+ // to happen before the run is finalized, which is where a nudge is decided.
+ expect(shellService.unregisterExternalSession).toHaveBeenCalledWith(SESSION_ID, { exitCode: 1 });
+ expect(vi.mocked(shellService.unregisterExternalSession).mock.invocationCallOrder[0])
+ .toBeLessThan(vi.mocked(agentLifecycle.finalizeAgent).mock.invocationCallOrder[0]);
});
it('passes the repo-owner-pinned GH_TOKEN into the TUI session env (buildSafeEnv would otherwise strip it)', async () => {
@@ -2824,7 +2832,7 @@ describe('spawnTuiAgent runtime', () => {
expect(activeAgents.has('agent-1')).toBe(false);
expect(vi.getTimerCount()).toBe(0);
- expect(shellService.killSession).toHaveBeenCalledWith(SESSION_ID);
+ expect(shellService.registerExternalSession, 'a PTY that already exited is not registered').not.toHaveBeenCalled();
expect(cosAgentLifecycle.updateAgent).not.toHaveBeenCalled();
});
@@ -3459,6 +3467,14 @@ describe('spawnTuiAgent runtime', () => {
for (let i = 0; i < 8; i += 1) await flushMicrotasks();
};
+ // The sentinel watcher's fallback poll, past the 5000ms tick AND the 50ms
+ // settle delay `watchForFile` applies after a `detect()`. A nudge is only
+ // ever decided on this trigger: a PTY exit means nobody is left to read it.
+ const fireSentinelWatcher = async () => {
+ await vi.advanceTimersByTimeAsync(5100);
+ await settle();
+ };
+
beforeEach(() => { sentinelExists = false; });
it('leaves a read-only run with an open PR to PortOS without a merge re-prompt', async () => {
@@ -3492,8 +3508,7 @@ describe('spawnTuiAgent runtime', () => {
await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
sentinelExists = true; // the agent writes .agent-done
- await capturedOnExit({ exitCode: 0, killed: false });
- await settle();
+ await fireSentinelWatcher();
// Round 1: nudged, not finalized. The reprompt path deletes the
// sentinel (`rm` flips `sentinelExists` false, see withSentinel) and
@@ -3507,11 +3522,7 @@ describe('spawnTuiAgent runtime', () => {
// blocker) and the RE-ARMED watcher's fallback poll picks it up —
// proving the re-arm itself works, not just a second exit event.
sentinelExists = true;
- // Past the 5000ms poll AND the 50ms settle delay `watchForFile` applies
- // after a `detect()` — a bare 5000ms advance lands exactly on the poll
- // tick but not the settle timer it then schedules.
- await vi.advanceTimersByTimeAsync(5100);
- await settle();
+ await fireSentinelWatcher();
await spawnPromise;
// One nudge per run: round 2 finalizes instead of nudging again.
@@ -3554,12 +3565,34 @@ describe('spawnTuiAgent runtime', () => {
await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
sentinelExists = true; // the agent writes .agent-done
+ await fireSentinelWatcher();
+ await spawnPromise;
+
+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);
+ });
+
+ // #11861: a runner proxy accepts a paste after its PTY died, so a truthy
+ // paste cannot prove the nudge reached anyone. When the exit is what
+ // decides, the run finalizes; the open PR takes the post-finalize path.
+ it('finalizes without nudging when a PTY exit is the deciding trigger, even if the paste would succeed', async () => {
+ vi.mocked(shellService.pasteToSession).mockReturnValue(999);
+ vi.mocked(probePrForBranch).mockResolvedValue({
+ prState: 'OPEN', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true,
+ });
+ withSentinel('## Summary\nShipped the fix and opened the PR.');
+
+ const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });
+ await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+
+ sentinelExists = true; // the agent writes .agent-done, then exits first
await capturedOnExit({ exitCode: 0, killed: false });
await settle();
await spawnPromise;
- expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
+ expect(shellService.pasteToSession).not.toHaveBeenCalled();
expect(agentLifecycle.finalizeAgent).toHaveBeenCalledTimes(1);
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({ success: true }));
});
it('replays a finish() trigger dropped while the merge-gate check was deciding, instead of losing it', async () => {
@@ -3572,17 +3605,26 @@ describe('spawnTuiAgent runtime', () => {
const spawnPromise = runSpawn({ task: openPrTask, workspacePath: '/tmp/ws' });
await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
+ // Hold the forge probe so the second trigger lands mid-decision.
+ let releaseProbe;
+ vi.mocked(probePrForBranch).mockImplementationOnce(() => new Promise((resolve) => {
+ releaseProbe = () => resolve({
+ prState: 'OPEN', prUrl: 'https://example.com/pr/1', prNumber: 1, cli: 'gh', readable: true,
+ });
+ }));
+
sentinelExists = true; // the agent writes .agent-done
- // Two triggers fire back-to-back with no await between them: the first
- // (a clean exit) starts the merge-gate decision; the second (a kill
- // signal racing in right after) is dropped by the `finishing` guard
- // while the first is still deciding. It must be replayed — not lost —
- // once the first settles on "not finalizing after all", or the run
- // would sit forever waiting for a nudge into a session that already died.
- const p1 = capturedOnExit({ exitCode: 0, killed: false });
- const p2 = capturedOnExit({ exitCode: 1, killed: true });
+ // The sentinel watcher starts the merge-gate decision; a kill signal
+ // racing in while it decides is parked by the `finishing` guard. It must
+ // be replayed — not lost — once the first settles on "not finalizing
+ // after all", or the run would sit forever waiting for a nudge into a
+ // session that already died.
+ await fireSentinelWatcher();
+ expect(releaseProbe).toBeTypeOf('function');
+ const exited = capturedOnExit({ exitCode: 1, killed: true });
+ releaseProbe();
await settle();
- await Promise.all([p1, p2]);
+ await exited;
await spawnPromise;
expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
@@ -3609,8 +3651,7 @@ describe('spawnTuiAgent runtime', () => {
await flushMicrotasks(); // initial watcher arms while quiet — must not self-fire
sentinelExists = true; // the agent writes .agent-done
- await capturedOnExit({ exitCode: 0, killed: false });
- await settle();
+ await fireSentinelWatcher();
expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);
expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index b07ffd394c..adb72459fa 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -962,7 +962,7 @@ export function createTuiSessionController({
* file, re-arms the watcher) — so finish() reopens the phase only after this
* whole function settles.
*/
- const runFinishDecision = async ({ success }) => {
+ const runFinishDecision = async ({ success, reason }) => {
if (terminalRefusal) return { type: 'finalize' };
// PortOS is going down. Whatever path got here — the PTY exiting under
// TreeKill, a provider-signal failure, a paste that failed because the shell died —
@@ -1009,7 +1009,14 @@ export function createTuiSessionController({
// mergeGateContract.js for the full decision table. The re-prompt expects
// a fresh completion signal; a trigger that arrived while this was
// deciding is the only thing that could say the session died meanwhile.
- if (success && sentinelSummary !== null && mergeGateIsOwed && !mergeGateReprompted
+ //
+ // Never when a PTY exit (`shell-*`) is the deciding trigger: a dead
+ // session cannot answer the nudge, and `tui:exit` is already consumed, so
+ // nothing would ever finish the run. `resubmit()` cannot be the liveness
+ // test — a runner proxy accepts writes after its PTY died (#11861). The
+ // still-open PR takes the post-finalize merge path instead.
+ const sessionExited = reason?.startsWith('shell-');
+ if (success && sentinelSummary !== null && mergeGateIsOwed && !mergeGateReprompted && !sessionExited
&& await checkMergeGateCompliance(sentinelSummary)) {
return { type: 'reprompt', replayParked: 'always' };
}
@@ -1039,7 +1046,7 @@ export function createTuiSessionController({
}
sessionPhase = 'finishing';
- let decision = await runFinishDecision({ success });
+ let decision = await runFinishDecision({ success, reason });
// A refusal observed while a sentinel/probe was awaited outranks its result.
if (terminalRefusal) {
decision = { type: 'finalize' };