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

feat([agent-tui-spawn-truncation-warn-parity]): mirror tuiPromptRunner overflow warn + metadata flag for agent spawner

[._.]/ Adam Eivy8ba7022d71be
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index ddea59743f..24147c7779 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -138,6 +138,14 @@ export async function spawnTuiAgent({
let lastOutputAt = Date.now();
let lastLine = '';
let sessionId = null;
+ // True once the respective buffer crossed its HEADROOM and the head was
+ // dropped. Mirrors `outputBufferTruncated` in `tuiPromptRunner.js`: warn
+ // once per buffer and surface via agent metadata so the agent record
+ // distinguishes a long-run-with-overflow from a clean short run. The raw
+ // buffer feeds analyzeAgentFailure on failure, so a silent slice there can
+ // hide the actual failure tail behind chatty progress redraws.
+ let outputBufferTruncated = false;
+ let rawBufferTruncated = false;
let pendingLines = [];
let flushTimer = null;
@@ -176,6 +184,12 @@ export async function spawnTuiAgent({
outputBuffer += `${cleanLine}\n`;
if (outputBuffer.length > OUTPUT_BUFFER_HEADROOM) {
outputBuffer = outputBuffer.slice(-OUTPUT_BUFFER_CAP);
+ if (!outputBufferTruncated) {
+ outputBufferTruncated = true;
+ console.warn(`⚠️ TUI agent ${agentId} parsed-output buffer exceeded ${Math.round(OUTPUT_BUFFER_HEADROOM / 1024 / 1024)}MB — head dropped (output.txt is the authoritative on-disk record)`);
+ updateAgent(agentId, { metadata: { outputBufferTruncated: true } })
+ .catch(err => console.error(`❌ TUI agent ${agentId} outputBufferTruncated metadata write failed: ${err.message}`));
+ }
}
pendingLines.push(cleanLine);
scheduleFlush();
@@ -271,7 +285,15 @@ export async function spawnTuiAgent({
const handleData = async (data) => {
const text = data.toString();
rawBuffer += text;
- if (rawBuffer.length > RAW_BUFFER_HEADROOM) rawBuffer = rawBuffer.slice(-RAW_BUFFER_CAP);
+ if (rawBuffer.length > RAW_BUFFER_HEADROOM) {
+ rawBuffer = rawBuffer.slice(-RAW_BUFFER_CAP);
+ if (!rawBufferTruncated) {
+ rawBufferTruncated = true;
+ console.warn(`⚠️ TUI agent ${agentId} raw PTY buffer exceeded ${Math.round(RAW_BUFFER_HEADROOM / 1024 / 1024)}MB — head dropped (failure analysis may miss earlier symptoms)`);
+ updateAgent(agentId, { metadata: { rawBufferTruncated: true } })
+ .catch(err => console.error(`❌ TUI agent ${agentId} rawBufferTruncated metadata write failed: ${err.message}`));
+ }
+ }
lastOutputAt = Date.now();
if (firstOutputAt === null) firstOutputAt = lastOutputAt;
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index e033e382f7..50a2669d35 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -85,10 +85,25 @@ vi.mock('../lib/providerModels.js', () => ({
resolveCliModel: vi.fn((m) => (m === 'codex-configured-default' || !m) ? null : m)
}));
+// Shrink buffer thresholds so the truncation tests can trip them with tiny
+// inputs. Real values (640 KB raw, 10 MB output) would force tests to push
+// millions of bytes through the spawner; the wiring under test is identical.
+vi.mock('../lib/tuiHandshake.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ OUTPUT_BUFFER_HEADROOM: 50,
+ OUTPUT_BUFFER_CAP: 20,
+ RAW_BUFFER_HEADROOM: 200,
+ RAW_BUFFER_CAP: 100,
+ };
+});
+
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import * as shellService from './shell.js';
import * as agentLifecycle from './agentLifecycle.js';
import * as agentErrorAnalysis from './agentErrorAnalysis.js';
+import * as cosAgents from './cosAgents.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
describe('agent TUI spawning', () => {
@@ -234,6 +249,8 @@ describe('spawnTuiAgent runtime', () => {
});
}
+ let warnSpy = null;
+
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
@@ -245,6 +262,13 @@ describe('spawnTuiAgent runtime', () => {
capturedOnData = null;
capturedOnExit = null;
+ // Silence the truncation warn globally for this describe block — the
+ // mocked tiny OUTPUT_BUFFER_HEADROOM (above) makes every spawn trip it
+ // via the two initial appendLine calls, so non-truncation tests would
+ // otherwise spam stderr. The truncation-specific tests below reach for
+ // this same spy to assert the warn fired.
+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
// Default createShellSession captures callbacks and returns a valid session id
vi.mocked(shellService.createShellSession).mockImplementation((_socket, opts) => {
capturedOnData = opts.onData;
@@ -258,6 +282,7 @@ describe('spawnTuiAgent runtime', () => {
afterEach(() => {
vi.useRealTimers();
+ warnSpy?.mockRestore();
});
// The TUI spawn path delegates the central completion sequence
@@ -399,4 +424,76 @@ describe('spawnTuiAgent runtime', () => {
})
);
});
+
+ // ── 6. Raw-buffer truncation warning + metadata flag ────────────────────────
+ // Mirrors `outputBufferTruncated` in tuiPromptRunner.js — long-running TUI
+ // agents whose raw PTY stream overflows RAW_BUFFER_HEADROOM silently dropped
+ // the head before this change; analyzeAgentFailure then operated on a slice
+ // missing the failure tail with no signal that anything was clipped.
+ it('rawBuffer overflow: warns once and writes rawBufferTruncated:true to agent metadata', async () => {
+ runSpawn();
+ await flushMicrotasks();
+
+ // Feed a chunk larger than the mocked 200-byte HEADROOM in one go so the
+ // raw buffer trips on the first handleData call.
+ await capturedOnData(Buffer.from('x'.repeat(300)));
+ await flushMicrotasks();
+
+ // Second chunk: should NOT emit a second warn or metadata write — the
+ // flag is a once-per-run signal, not a per-overflow counter.
+ await capturedOnData(Buffer.from('x'.repeat(300)));
+ await flushMicrotasks();
+
+ const truncWarns = warnSpy.mock.calls.filter(args =>
+ typeof args[0] === 'string' && args[0].includes('raw PTY buffer exceeded')
+ );
+ expect(truncWarns).toHaveLength(1);
+
+ const truncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(
+ ([_id, payload]) => payload?.metadata?.rawBufferTruncated === true
+ );
+ expect(truncMetaCalls).toHaveLength(1);
+ expect(truncMetaCalls[0][0]).toBe('agent-1');
+ });
+
+ it('rawBuffer below threshold: no truncation warn or metadata flag', async () => {
+ runSpawn();
+ await flushMicrotasks();
+
+ // 150 bytes is under the mocked 200-byte HEADROOM.
+ await capturedOnData(Buffer.from('x'.repeat(150)));
+ await flushMicrotasks();
+
+ const truncWarns = warnSpy.mock.calls.filter(args =>
+ typeof args[0] === 'string' && args[0].includes('raw PTY buffer exceeded')
+ );
+ expect(truncWarns).toHaveLength(0);
+
+ const truncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(
+ ([_id, payload]) => payload?.metadata?.rawBufferTruncated === true
+ );
+ expect(truncMetaCalls).toHaveLength(0);
+ });
+
+ // ── 7. Output-buffer truncation warning + metadata flag ─────────────────────
+ // outputBuffer is filled via appendLine, which fires on initial spawn
+ // (session-started + open-shell-tab) plus the prompt-pasted notice. With
+ // the mocked 50-byte HEADROOM the second spawn line crosses the cap, so
+ // the wiring is exercised on every spawn — but only ONCE per run
+ // regardless of how many subsequent lines arrive.
+ it('outputBuffer overflow: warns once and writes outputBufferTruncated:true to agent metadata', async () => {
+ runSpawn();
+ await flushMicrotasks();
+
+ const truncWarns = warnSpy.mock.calls.filter(args =>
+ typeof args[0] === 'string' && args[0].includes('parsed-output buffer exceeded')
+ );
+ expect(truncWarns).toHaveLength(1);
+
+ const truncMetaCalls = vi.mocked(cosAgents.updateAgent).mock.calls.filter(
+ ([_id, payload]) => payload?.metadata?.outputBufferTruncated === true
+ );
+ expect(truncMetaCalls).toHaveLength(1);
+ expect(truncMetaCalls[0][0]).toBe('agent-1');
+ });
});