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(tui): agent self-runs simplify+pr, signals done via sentinel file

[._.]/ Adam Eivy560f45e420f5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 48408a18d9..9259c4aa24 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -886,6 +886,27 @@
## Changed
+- **TUI agents now own the simplify → push → PR sequence and self-signal
+ completion.** With Claude Code TUI available as a provider type, the
+ system no longer needs to drive `cleanupAgentWorktree`'s push/PR steps
+ from outside the agent: the agent's prompt now ends with a Completion
+ Workflow section instructing it to run `/simplify` (when enabled),
+ `/do:pr` (or `/do:push` when `openPR` is false), write `.agent-done`
+ in the workspace as a completion sentinel, and `/quit` to exit. PortOS
+ polls for the sentinel every 2 s and finalizes the agent with reason
+ `agent-signaled-done` as soon as it appears (the existing idle-timeout
+ is kept as a fallback for non-compliant agents). The TUI cleanup path
+ forces `openPR: false`, `requestCopilotReview: false`, `skipMerge: true`
+ so the worktree cleanup never double-fires push/PR after the agent has
+ already done it. CLAUDE.md is also no longer pasted into TUI prompts —
+ Claude Code reads it natively at session start, so duplicating it just
+ wastes tokens. The agent "Show output" panel for TUI agents drops
+ per-line PTY capture entirely (TUI is a screen, not a log — the
+ attached Shell tab is the live view) and only records lifecycle
+ events. Touches `server/services/agentPromptBuilder.js`,
+ `server/services/agentLifecycle.js`,
+ `server/services/agentTuiSpawning.js` + tests.
+
- **Writers Room / Universe Builder / Series detail — collapse UX now matches
CoS.** The three pages previously left a 32px vertical rail in place when
their middle sidebar was collapsed. They now mirror the Chief of Staff
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 9ae0eb5f1c..6671d89ec0 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -441,8 +441,12 @@ export async function spawnAgentForTask(task) {
}
} // end !isReadOnly
- // Build the agent prompt (includes worktree and JIRA context if applicable)
- const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta);
+ const isTui = provider.type === 'tui';
+
+ // Build the agent prompt (includes worktree and JIRA context if applicable).
+ // TUI providers (Claude Code, etc.) read CLAUDE.md natively at session boot,
+ // so don't paste it into the prompt — saves tokens and avoids duplication.
+ const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, { skipClaudeMd: isTui, tui: isTui });
// Create agent directory
const agentDir = join(AGENTS_DIR, agentId);
@@ -455,8 +459,6 @@ export async function spawnAgentForTask(task) {
// Create run entry for usage tracking
const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);
-
- const isTui = provider.type === 'tui';
const executionMode = isTui ? 'tui' : useRunner ? 'runner' : 'direct';
// Register the agent with model info
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 812b348eab..3ac23c6a83 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -152,13 +152,24 @@ ${hints.map(h => `- ${h}`).join('\n')}
* @param {Object|null} worktreeInfo - Worktree details if using a worktree
* @param {Function} isTruthyMetaFn - isTruthyMeta function (passed to avoid circular dep)
*/
-export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, isTruthyMetaFn = (v) => v === true || v === 'true') {
+export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, isTruthyMetaFn = (v) => v === true || v === 'true', options = {}) {
+ // TUI agents run inside an interactive Claude Code shell that already reads
+ // CLAUDE.md natively at session start — re-pasting it into the prompt just
+ // wastes tokens and duplicates context. TUI agents also own their
+ // commit/push/PR workflow directly via slashdo commands (Claude Code TUI
+ // has /simplify, /do:pr, etc. available), so the worktree/simplify
+ // sections that assume system-side post-exit cleanup are replaced with a
+ // single TUI workflow block.
+ const skipClaudeMd = options.skipClaudeMd === true;
+ const isTui = options.tui === true;
// Fetch independent context sections in parallel
const [memorySection, claudeMdSection, digitalTwinSection] = await Promise.all([
getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 })
.catch(err => { console.log(`⚠️ Memory retrieval failed: ${err.message}`); return null; }),
- getClaudeMdContext(workspaceDir)
- .catch(err => { console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`); return null; }),
+ skipClaudeMd
+ ? Promise.resolve(null)
+ : getClaudeMdContext(workspaceDir)
+ .catch(err => { console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`); return null; }),
getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000 })
.catch(err => { console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`); return null; })
]);
@@ -177,9 +188,11 @@ You are working in an **isolated git worktree** to avoid conflicts with other ag
- **Worktree Path**: \`${worktreeInfo.worktreePath}\`
${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}
-**Important**: ${isWorktreeOnExistingBranch
- ? 'Commit and **push** any review-fix commits to this branch — the PR points at it, so pushed commits are how Copilot sees your fixes. Use `git pull --rebase` before pushing if needed.'
- : `Commit your changes to this branch.${willOpenPR ? ' When your task completes, the system will push this branch and open a pull request against the default branch — do NOT push or open a PR yourself.' : ' Your commits will be automatically merged back to the main development branch when your task completes.'}`} Do NOT manually switch branches or modify the worktree configuration.
+**Important**: ${isTui
+ ? 'Commit your changes to this branch — see the **Completion Workflow** section below for the full push/PR/exit sequence.'
+ : isWorktreeOnExistingBranch
+ ? 'Commit and **push** any review-fix commits to this branch — the PR points at it, so pushed commits are how Copilot sees your fixes. Use `git pull --rebase` before pushing if needed.'
+ : `Commit your changes to this branch.${willOpenPR ? ' When your task completes, the system will push this branch and open a pull request against the default branch — do NOT push or open a PR yourself.' : ' Your commits will be automatically merged back to the main development branch when your task completes.'}`} Do NOT manually switch branches or modify the worktree configuration.
` : '';
// Build pipeline context section if this is a pipeline stage
@@ -198,10 +211,32 @@ Use the findings from the previous stage to inform your work. If the previous st
// Build simplify section if enabled. In the worktree-with-openPR flow the
// system pushes and opens the PR after the agent exits, so the agent must
// only commit (not push) — keep this wording aligned with the worktree
- // section above.
- const simplifySection = isTruthyMetaFn(task.metadata?.simplify) ? `
+ // section above. TUI agents own the full simplify+push+PR sequence in the
+ // Completion Workflow section below, so this section is suppressed for TUI.
+ const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);
+ const simplifySection = simplifyEnabled && !isTui ? `
## Simplify Step
After completing your work and before committing, run \`/simplify\` to review the changed code for reuse, quality, and efficiency. Fix any issues found, then ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.
+` : '';
+
+ // TUI Completion Workflow. Claude Code TUI has direct access to the
+ // slashdo commands (the submodule mounts them as project-level slash
+ // commands), so the agent runs the whole tail end itself instead of
+ // having PortOS drive push/PR creation from cleanup. The sentinel file
+ // (.agent-done) is what PortOS polls for to know the agent has finished
+ // — write it AFTER /do:pr/push succeeds, then /quit exits Claude Code
+ // and the spawn's handleExit fires.
+ const tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';
+ const tuiCompletionSection = isTui ? `
+## Completion Workflow
+You are running inside the Claude Code TUI, which has the project's slashdo commands available as slash commands. When your task is complete, run the following — in order — without further user input:
+
+1. ${simplifyEnabled ? '`/simplify` — review the changed code for reuse, quality, and efficiency, and fix any issues it surfaces.' : '(simplify is disabled for this task — skip step 1)'}
+2. \`${tuiCompletionCommand}\` — commits${willOpenPR ? ', pushes, and opens a pull request against the default branch' : ' and pushes the branch'}.
+3. Write the completion sentinel so PortOS knows you finished: \`echo "done" > "${worktreeInfo?.worktreePath || workspaceDir}/.agent-done"\` (PortOS polls for this file; without it the agent will sit idle until the 3-minute fallback timer fires).
+4. Run \`/quit\` to exit the Claude Code session cleanly.
+
+Do not wait for further user input between these steps — run them in sequence as soon as the implementation work is finished.
` : '';
// Build review loop section if enabled. The agent itself does NOT open the PR
@@ -324,6 +359,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
pipelineSection,
jiraSection,
simplifySection,
+ tuiCompletionSection,
reviewLoopSection,
reviewLoopFollowUpSection,
compactionSection,
@@ -359,6 +395,7 @@ ${worktreeSection}
${pipelineSection}
${jiraSection}
${simplifySection}
+${tuiCompletionSection}
${reviewLoopSection}
${reviewLoopFollowUpSection}
${compactionSection}
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index baeb451c9f..e4bcbf054b 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -7,7 +7,8 @@
*/
import { join } from 'path';
-import { appendFile, rm } from 'fs/promises';
+import { existsSync } from 'fs';
+import { appendFile, readFile, rm } from 'fs/promises';
import * as shellService from './shell.js';
import { emitLog } from './cosEvents.js';
import { appendAgentOutputLines, updateAgent, completeAgent } from './cosAgents.js';
@@ -47,6 +48,12 @@ const READY_POLL_INTERVAL_MS = 300;
const READY_IDLE_THRESHOLD_MS = 1200;
const PASTE_TO_ENTER_DELAY_MS = 400;
const PASTE_DEADLINE_MS = 10000;
+// Sentinel-file polling. TUI agents write `.agent-done` in their workspace
+// when they've finished /simplify + /do:pr (or /do:push) — we poll for it
+// here so the agent gets cleanly finalized as soon as the work is done,
+// without waiting on the much longer idle timeout fallback.
+const DONE_SENTINEL_NAME = '.agent-done';
+const DONE_POLL_INTERVAL_MS = 2000;
const ANSI_PATTERN = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
@@ -83,42 +90,6 @@ function createStreamingAnsiStripper() {
};
}
-// TUI repaint artifacts that aren't useful to display in the agent output
-// panel. The raw PTY stream still goes to the attached shell session (and to
-// rawBuffer for error analysis) — this only suppresses display noise.
-const BOX_DRAW_CHARS = /[─│┌┐└┘├┤┬┴┼━┃╮╯╰╭╱╲╳▶◀▼▲╴╵╶╷▌▐▖▗▘▝▙▚▛▜▟►◄·•]/g;
-const STATUS_FOOTER_PATTERNS = [
- /bypass permissions (on|off)/i,
- /shift\s*\+\s*tab to cycle/i
-];
-
-export function isTuiNoise(line) {
- if (!line) return true;
- const stripped = line.replace(BOX_DRAW_CHARS, '').trim();
- if (!stripped) return true;
- // Single bullet/prompt marker with nothing else
- if (/^[>?]\s*$/.test(stripped)) return true;
- // "Try 'how does X work?'" placeholder
- if (/^try ["'].*["']\??$/i.test(stripped)) return true;
- // Welcome banner lines (Claude Code v…, Opus 4.x, etc.)
- if (/^claude code\b/i.test(stripped) && stripped.length < 64) return true;
- if (/^opus \d/i.test(stripped) && stripped.length < 64) return true;
- // Status footer / help bar
- if (STATUS_FOOTER_PATTERNS.some(re => re.test(stripped))) return true;
- // Letter-spaced gibberish from TUI animation: e.g. "c l a u d e - c o d e".
- // Match strings where the majority of whitespace-separated tokens are a
- // single character — the TUI sometimes renders typed input one glyph at a
- // time with separating spaces during paste/erase animation.
- if (stripped.length > 8) {
- const tokens = stripped.split(/\s+/);
- if (tokens.length >= 6) {
- const singleCharTokens = tokens.filter(t => t.length === 1).length;
- if (singleCharTokens >= tokens.length * 0.6) return true;
- }
- }
- return false;
-}
-
function shellQuote(value) {
const text = String(value ?? '');
if (/^[A-Za-z0-9_./:=+-]+$/.test(text)) return text;
@@ -164,7 +135,6 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
let promptSentAt = null;
let firstOutputAt = null;
let lastOutputAt = Date.now();
- let meaningfulLinesAfterPrompt = 0;
let lastLine = '';
let sessionId = null;
@@ -194,14 +164,12 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
}, OUTPUT_FLUSH_INTERVAL_MS);
};
- const appendLine = (line, { force = false } = {}) => {
+ // TUI agents only emit a handful of internal status lines (session-started,
+ // prompt-pasted, completion) — see handleData for why per-line capture of
+ // the PTY stream itself is intentionally dropped.
+ const appendLine = (line) => {
const cleanLine = line.trim();
if (!cleanLine || cleanLine === lastLine) return;
- if (promptPreview && cleanLine.replace(/\s+/g, ' ').includes(promptPreview)) return;
- // Filter TUI repaint artifacts (banners, status footer, box drawing,
- // letter-spaced animation frames). `force: true` lets internal messages
- // ("TUI session started", etc.) bypass the filter.
- if (!force && isTuiNoise(cleanLine)) return;
lastLine = cleanLine;
outputBuffer += `${cleanLine}\n`;
@@ -210,7 +178,6 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
}
pendingLines.push(cleanLine);
scheduleFlush();
- if (promptSentAt) meaningfulLinesAfterPrompt++;
};
const finish = async ({ success, exitCode = 0, error = null, reason = 'completed' }) => {
@@ -220,6 +187,7 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
const agentData = activeAgents.get(agentId);
if (agentData?.idleTimer) clearInterval(agentData.idleTimer);
if (agentData?.promptTimer) clearInterval(agentData.promptTimer);
+ if (agentData?.doneSentinelTimer) clearInterval(agentData.doneSentinelTimer);
if (pasteEnterTimer) { clearTimeout(pasteEnterTimer); pasteEnterTimer = null; }
// Drain pending parsed lines before the final state writes so completion
@@ -300,13 +268,17 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
await processAgentCompletion(agentId, task, finalSuccess, outputBuffer);
if (workspacePath) await rm(join(workspacePath, 'BTW.md')).catch(() => {});
+ if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});
- const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
+ // TUI agents run /do:pr (or /do:push) themselves before signaling via
+ // .agent-done, so the system-side cleanup must NOT also push or open a
+ // PR — that would double-fire. `skipMerge` is forced on so the
+ // post-exit auto-merge doesn't trip over a branch the agent already
+ // pushed. The worktree directory itself is still cleaned up.
await cleanupWorktreeFn(agentId, finalSuccess, {
- openPR: directOpenPR,
- requestCopilotReview: directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
- skipMerge: directReviewLoopFollowUp,
+ openPR: false,
+ requestCopilotReview: false,
+ skipMerge: true,
description: task.description,
agentOutput: outputBuffer,
originalTask: task
@@ -330,21 +302,23 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
emitLog('info', `TUI agent ${agentId} working...`, { agentId, phase: 'working' });
}
- const clean = streamingStrip(text).replace(/\r/g, '\n');
- const lowerClean = clean.toLowerCase();
- if (!promptSentAt && lowerClean.includes('command not found') && lowerClean.includes(commandName.toLowerCase())) {
- await finish({
- success: false,
- exitCode: 127,
- error: `TUI command not found: ${tuiConfig.command}`,
- reason: 'command-not-found'
- });
- return;
- }
-
- const lines = clean.split('\n').map(line => line.trim()).filter(Boolean);
- for (const line of lines) {
- appendLine(line);
+ // The TUI is a *screen*, not a log: every progress tick repaints the
+ // status line (`thinking with…`, token counters, footer) and gets
+ // re-captured if we parse it line-by-line. The attached shell session
+ // shows the live TUI faithfully — see-the-shell is the user-facing
+ // path. We still buffer the raw stream into rawBuffer for error
+ // analysis on failure, and we detect early "command not found" so a
+ // missing binary fails fast instead of idling.
+ if (!promptSentAt) {
+ const lowerStripped = streamingStrip(text).toLowerCase();
+ if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {
+ await finish({
+ success: false,
+ exitCode: 127,
+ error: `TUI command not found: ${tuiConfig.command}`,
+ reason: 'command-not-found'
+ });
+ }
}
};
@@ -405,7 +379,7 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
if (finalized) return;
shellService.writeToSession(sessionId, '\r');
}, PASTE_TO_ENTER_DELAY_MS);
- appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)} (${reason})`, { force: true });
+ appendLine(`📟 Prompt pasted into TUI session ${sessionId.slice(0, 8)} (${reason})`);
};
const promptTimer = setInterval(() => {
@@ -432,7 +406,10 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
const runtime = Date.now() - promptSentAt;
const idle = Date.now() - lastOutputAt;
if (runtime < DEFAULT_TUI_MIN_RUNTIME_MS) return;
- if (meaningfulLinesAfterPrompt < 2) return;
+ // We track post-paste activity via lastOutputAt instead of parsed-line
+ // counts because per-line PTY capture is intentionally disabled for TUI
+ // agents — see handleData.
+ if (lastOutputAt <= promptSentAt) return;
if (idle >= tuiConfig.idleTimeoutMs) {
finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {
emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });
@@ -440,6 +417,28 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
}
}, 5000);
+ // Sentinel-file watcher. The agent's prompt instructs it to write
+ // .agent-done in the workspace after running /simplify + /do:pr; that's
+ // the primary completion signal (idle-complete is just the fallback for
+ // an agent that didn't comply).
+ const doneSentinelPath = workspacePath ? join(workspacePath, DONE_SENTINEL_NAME) : null;
+ const doneSentinelTimer = doneSentinelPath ? setInterval(() => {
+ if (finalized) return;
+ if (!existsSync(doneSentinelPath)) return;
+ clearInterval(doneSentinelTimer);
+ readFile(doneSentinelPath, 'utf8')
+ .then(contents => {
+ const trimmed = contents.trim();
+ if (trimmed) appendLine(`✅ Agent signaled completion: ${trimmed.slice(0, 200)}`);
+ })
+ .catch(() => {})
+ .finally(() => {
+ finish({ success: true, exitCode: 0, reason: 'agent-signaled-done' }).catch(err => {
+ emitLog('error', `Failed to finalize TUI agent ${agentId} after sentinel: ${err.message}`, { agentId });
+ });
+ });
+ }, DONE_POLL_INTERVAL_MS) : null;
+
activeAgents.set(agentId, {
process: ptyProcess || { kill: () => shellService.killSession(sessionId) },
taskId: task.id,
@@ -451,7 +450,8 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
laneName,
tuiSessionId: sessionId,
idleTimer,
- promptTimer
+ promptTimer,
+ doneSentinelTimer
});
await updateAgent(agentId, {
@@ -465,6 +465,7 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
}
});
- appendLine(`📟 TUI session started: ${sessionId.slice(0, 8)} (${tuiConfig.commandLine})`, { force: true });
+ appendLine(`📟 TUI session started: ${sessionId.slice(0, 8)} (${tuiConfig.commandLine})`);
+ appendLine(`💡 Open the Shell tab for live TUI output — this panel only logs lifecycle events.`);
return agentId;
}
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index d6213f82e6..d90d0b3521 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -82,7 +82,7 @@ vi.mock('../lib/providerModels.js', () => ({
resolveCliModel: vi.fn((m) => (m === 'codex-configured-default' || !m) ? null : m)
}));
-import { buildTuiSpawnConfig, isTuiNoise, spawnTuiAgent } from './agentTuiSpawning.js';
+import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import * as shellService from './shell.js';
import * as cosAgents from './cosAgents.js';
import * as cos from './cos.js';
@@ -148,30 +148,6 @@ describe('agent TUI spawning', () => {
});
});
-describe('isTuiNoise', () => {
- it('treats banner/status/box-drawing artifacts as noise', () => {
- expect(isTuiNoise('')).toBe(true);
- expect(isTuiNoise(' ')).toBe(true);
- expect(isTuiNoise('─────────────')).toBe(true);
- expect(isTuiNoise('>')).toBe(true);
- expect(isTuiNoise('?')).toBe(true);
- expect(isTuiNoise('Try "how does Layout.jsx work?"')).toBe(true);
- expect(isTuiNoise('Claude Code v2.1.133')).toBe(true);
- expect(isTuiNoise('Opus 4.7 with xhigh effort · Claude Max')).toBe(true);
- expect(isTuiNoise('►► bypass permissions on (shift+tab to cycle)')).toBe(true);
- // Letter-spaced animation frame from paste rendering
- expect(isTuiNoise('c l a u d e - d a n g e r o u s l y - s k i p')).toBe(true);
- });
-
- it('keeps real agent output', () => {
- expect(isTuiNoise('Reading file src/App.jsx...')).toBe(false);
- expect(isTuiNoise('🔧 ReadFile')).toBe(false);
- expect(isTuiNoise('Done! Refactored the auth middleware.')).toBe(false);
- // Short prompt-style line — only filtered if it's a *bare* > or ?
- expect(isTuiNoise('> hello')).toBe(false);
- });
-});
-
// ─── spawnTuiAgent runtime tests ─────────────────────────────────────────────
// Flush the microtask queue (pending Promise continuations). vi.runAllMicrotasksAsync
@@ -264,14 +240,15 @@ describe('spawnTuiAgent runtime', () => {
await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks();
- // Feed 2 meaningful lines AFTER the paste so meaningfulLinesAfterPrompt >= 2.
- // These must not match the promptPreview ("do the thing").
- await capturedOnData(Buffer.from('Agent output line one\n'));
- await capturedOnData(Buffer.from('Agent output line two\n'));
+ // Feed one PTY chunk AFTER the paste so lastOutputAt > promptSentAt
+ // (the idle gate's "we saw activity post-paste" signal — replaces the
+ // old per-line count now that line capture is dropped).
+ await capturedOnData(Buffer.from('Agent post-paste activity\n'));
// Advance past DEFAULT_TUI_MIN_RUNTIME_MS (15 000ms) + idleTimeoutMs (50ms).
- // The idle setInterval ticks every 5 000ms; at the >=15s tick the conditions
- // (runtime >= 15s, lines >= 2, idle >= 50ms) are all satisfied.
+ // The idle setInterval ticks every 5 000ms; at the >=15s tick the
+ // conditions (runtime >= 15s, lastOutputAt > promptSentAt, idle >= 50ms)
+ // are all satisfied.
await vi.advanceTimersByTimeAsync(21000);
// finish() is called as fire-and-forget inside the interval callback;