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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: guarantee executeTuiRun's finish() always settles the run promise
[._.]/ Adam Eivy81760dc0cc89
diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 5fc34b0fe8..6d87009158 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -279,43 +279,54 @@ ${prompt}`;const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {if (finalized) return;finalized = true;- cleanupTimers();- unregisterActiveRun(runId);- // Drop the live Shell view the moment the run ends (notifies any attached- // viewer via shell:exit). Idempotent — safe even if no viewer ever- // attached. Runs before the kill below so the session disappears from the- // list immediately rather than waiting on PTY teardown.- unregisterExternalSession(runId, { exitCode });-- // Kill the PTY if still alive — one-shot runs don't leave a session- // behind for the user to interact with.- try { if (ptyProcess && !ptyProcess.killed) ptyProcess.kill(); } catch { /* already gone */ }-- // Prefer the response file the TUI was directed to write; fall back- // to the ANSI-stripped screen scrape when the file is missing/empty- // or the run didn't succeed. Logic lives in `resolveTuiResponseText`- // so it can be unit-tested without a live PTY.- const { text: responseText, usedResponseFile } = await resolveTuiResponseText({- success, responseFilePath, outputBuffer, wrappedPrompt,- });+ // finish() is invoked fire-and-forget from PTY/timer callbacks outside the+ // request lifecycle (onData, onExit, sendPrompt's write-catch,+ // responseFileWatchTimer, hardTimeoutTimer) — none of them await or+ // .catch() this call. try/finally guarantees `resolve` below always fires+ // exactly once even if a step throws (including the caller-supplied+ // `onComplete` callback), so executeTuiRun's Promise can never hang forever.+ try {+ cleanupTimers();+ unregisterActiveRun(runId);+ // Drop the live Shell view the moment the run ends (notifies any attached+ // viewer via shell:exit). Idempotent — safe even if no viewer ever+ // attached. Runs before the kill below so the session disappears from the+ // list immediately rather than waiting on PTY teardown.+ unregisterExternalSession(runId, { exitCode });++ // Kill the PTY if still alive — one-shot runs don't leave a session+ // behind for the user to interact with.+ try { if (ptyProcess && !ptyProcess.killed) ptyProcess.kill(); } catch { /* already gone */ }++ // Prefer the response file the TUI was directed to write; fall back+ // to the ANSI-stripped screen scrape when the file is missing/empty+ // or the run didn't succeed. Logic lives in `resolveTuiResponseText`+ // so it can be unit-tested without a live PTY.+ const { text: responseText, usedResponseFile } = await resolveTuiResponseText({+ success, responseFilePath, outputBuffer, wrappedPrompt,+ });- // Delegate run-record finalization (output.txt + metadata.json merge- // + onRunCompleted/onRunFailed hooks + toolkit error analysis) to the- // shared runner helper. `completionReason` lands in `extras` so it- // gets persisted to metadata.json BEFORE the write (was previously- // set post-write and never made it to disk → /runs replay missed it).- const metadata = await finalizeRunRecord({- runId, output: responseText, exitCode, success, error, startTime,- extras: { completionReason: reason, usedResponseFile, outputTruncated: outputBufferTruncated },- }).catch((err) => {- console.error(`❌ TUI run ${runId} finalize failed: ${err.message}`);- return {- exitCode, success, error: error || err.message,- duration: Date.now() - startTime, completionReason: reason,- };- });- onComplete?.({ ...metadata, text: responseText, usedResponseFile, outputTruncated: outputBufferTruncated });- resolve();+ // Delegate run-record finalization (output.txt + metadata.json merge+ // + onRunCompleted/onRunFailed hooks + toolkit error analysis) to the+ // shared runner helper. `completionReason` lands in `extras` so it+ // gets persisted to metadata.json BEFORE the write (was previously+ // set post-write and never made it to disk → /runs replay missed it).+ const metadata = await finalizeRunRecord({+ runId, output: responseText, exitCode, success, error, startTime,+ extras: { completionReason: reason, usedResponseFile, outputTruncated: outputBufferTruncated },+ }).catch((err) => {+ console.error(`❌ TUI run ${runId} finalize failed: ${err.message}`);+ return {+ exitCode, success, error: error || err.message,+ duration: Date.now() - startTime, completionReason: reason,+ };+ });+ onComplete?.({ ...metadata, text: responseText, usedResponseFile, outputTruncated: outputBufferTruncated });+ } catch (err) {+ console.error(`❌ TUI run ${runId} finish() failed: ${err?.message || err}`);+ } finally {+ resolve();+ }};ptyProcess.onData((data) => {diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 31dcecb59d..699888595b 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -723,6 +723,30 @@ describe('executeTuiRun', () => {}));});+ it('still resolves the run promise exactly once when a step inside finish() throws synchronously', async () => {+ // unregisterExternalSession is invoked un-awaited inside finish()'s try+ // block, with no per-call try/catch of its own — unlike the PTY kill+ // (own try/catch) and finalizeRunRecord (own .catch()). If it throws,+ // finish()'s outer try/catch/finally must still guarantee `resolve()`+ // fires — otherwise executeTuiRun's promise hangs forever and any+ // caller awaiting it (pipeline stages, /runs) wedges.+ shellMocks.unregisterExternalSession.mockImplementationOnce(() => {+ throw new Error('boom: session registry corrupted');+ });+ const provider = { id: 'claude', type: 'tui', command: 'echo' };+ const onComplete = vi.fn();+ const promise = executeTuiRun({ runId: 'run-finish-throws', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onComplete, timeout: 60000 });+ await flushAsync();++ ptyInstances[0].emitExit({ exitCode: 0 });++ await expect(promise).resolves.toBeUndefined();+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('finish() failed'));+ // The throw happens before onComplete is reached in finish()'s body,+ // so onComplete must never fire for this run.+ expect(onComplete).not.toHaveBeenCalled();+ });+it('finishes with reason "killed" and surfaces the signal in the error when the PTY is terminated', async () => {const provider = { id: 'claude', type: 'tui', command: 'echo' };const promise = executeTuiRun({ runId: 'run-killed', provider, prompt: 'a prompt long enough', workspacePath: '/cwd', onData: undefined, onComplete: undefined, timeout: 60000 });