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([issue-12769]): submit a pasted TUI prompt left sitting in the composer
[._.]/ Adam Eivy0454118df6b0
diff --git a/server/lib/agentOutputMarkers.js b/server/lib/agentOutputMarkers.jsindex c3a55da16c..1ed1a17d64 100644--- a/server/lib/agentOutputMarkers.js+++ b/server/lib/agentOutputMarkers.js@@ -116,6 +116,7 @@ export const LIFECYCLE_LINES = Object.freeze({truncationNudged: lifecycleLine`🔁 Response was truncated before completion — nudged the session to continue (attempt ${'attempt'}/${'max'})`,stallNudged: lifecycleLine`🔁 Session idle with the task unfinished — nudged it to continue (attempt ${'attempt'}/${'max'}, ${'sent'}/${'total'} this run)`,stallGaveUp: lifecycleLine`🛑 Session still idle after ${'nudges'} nudges — it is not finishing; open the Shell tab to take it over`,+ unsubmittedPromptEntered: lifecycleLine`⏎ Prompt still unsubmitted in the composer — pressed Enter (attempt ${'attempt'}/${'max'})`,// Completion and interruptionmergeGateReprompted: lifecycleLine`🔁 Merge Gate not finished (PR still OPEN, no blocker stated) — re-prompted the session (1 nudge only)`,hostRestarted: lifecycleLine`🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.`,diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex b8e2990fd1..33c6b87b5f 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -98,7 +98,7 @@ export function doneSentinelAgentId(name) {return name.startsWith(prefix) && name.length > prefix.length ? name.slice(prefix.length) : null;}-const STARTUP_SENTINEL_REASONS = new Set(['paste-not-rendered', 'tui-not-ready', 'command-not-found']);+const STARTUP_SENTINEL_REASONS = new Set(['paste-not-rendered', 'tui-not-ready', 'command-not-found', 'prompt-not-submitted']);/*** The operator line for a TUI that ended without its completion sentinel.diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 912330d47c..3a1224ae42 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -1843,6 +1843,90 @@ export function createStallNudgeGate({};}+// ─── Unsubmitted prompt — "the paste landed, the Enter did not" ─────────────+//+// A TUI can render the paste chip and still ignore every submit Enter that+// follows it: the composer shows `❯ [Pasted text #1 +353 lines]` and nothing else+// ever happens. Seen on Claude Code claim runs started in a burst (#12769). The+// likeliest mechanism is a TUI too busy committing a large paste to read the+// trailing CRs as a submit; the transcripts show the outcome, not the cause. A+// bare Enter once the composer has settled submits the paste where it sits.+// Re-pasting — which is all the stall nudge can do — would only stack a second+// chip on the first.+//+// Silence is the signal, as for the stall nudge: a submitted prompt starts a+// turn, and every TUI we drive repaints its in-flight chrome at least once a+// second for as long as a turn runs. Quiet this long after the submit, with the+// paste chip still the last thing painted, means the turn never started.+export const UNSUBMITTED_PROMPT_SETTLE_MS = 20000;+export const UNSUBMITTED_PROMPT_ENTER_MAX_ATTEMPTS = 3;+// Output arriving this long after PortOS's own last keystroke cannot be the+// echo of that keystroke, so it is a turn running. The same 30s that proves a+// stall nudge took.+export const PROMPT_WORK_EVIDENCE_MS = STALL_NUDGE_RECOVERY_MS;+const UNSUBMITTED_PROMPT_TAIL_CAP = 4096;+// A selector or confirmation painted after the chip owns the Enter key; a bare+// Enter there would pick its highlighted default.+const SELECTOR_AFTER_PASTE_PATTERN = /enter\s*to\s*(?:select|confirm)|↑\s*\/\s*↓|❯\s*1\.|do\s*you\s*want\s*to\s*proceed\?|press\s*enter\s*to\s*continue/i;++/**+ * State machine for "the prompt was pasted and submitted, but the turn never+ * started". Owned per run by the agent session controller.+ *+ * - `noteInput(nowMs, evidence)` — every PortOS keystroke into the composer: the+ * submit (with the paste-commit buffer as `evidence`, because a TUI that+ * ignores the Enter may never repaint the chip), a nudge, a bare Enter.+ * - `observe(strippedText, nowMs)` — every ANSI-stripped chunk.+ * - `takeEnter(nowMs, lastOutputAtMs)` — the 1-based bare-Enter number when one+ * is due, else 0.+ * - `worked` — whether the run ever produced output that was not the echo of a+ * PortOS keystroke. A run whose stall-nudge budget runs out with this still+ * false never started, and the caller fails it rather than parking it.+ *+ * @param {{ promptMarkerCount?: number, settleMs?: number, maxAttempts?: number, workEvidenceMs?: number }} [options]+ */+export function createPromptSubmissionGate({+ promptMarkerCount = 0,+ settleMs = UNSUBMITTED_PROMPT_SETTLE_MS,+ maxAttempts = UNSUBMITTED_PROMPT_ENTER_MAX_ATTEMPTS,+ workEvidenceMs = PROMPT_WORK_EVIDENCE_MS,+} = {}) {+ let inputAt = null;+ let worked = false;+ let tail = '';+ let enters = 0;+ const holdsUnsubmittedPaste = () => {+ if (!isPasteCommitted(tail, { promptMarkerCount })) return false;+ let lastMarkerEnd = -1;+ for (const match of tail.matchAll(PASTE_MARKER_PATTERN_GLOBAL)) lastMarkerEnd = match.index + match[0].length;+ return lastMarkerEnd >= 0 && !SELECTOR_AFTER_PASTE_PATTERN.test(tail.slice(lastMarkerEnd));+ };+ return {+ noteInput(nowMs, evidence = '') {+ inputAt = nowMs;+ if (!worked && evidence) tail = (tail + evidence).slice(-UNSUBMITTED_PROMPT_TAIL_CAP);+ },+ observe(strippedText, nowMs) {+ if (worked || inputAt === null || !strippedText) return;+ if (nowMs - inputAt >= workEvidenceMs) {+ worked = true;+ tail = '';+ return;+ }+ tail = (tail + strippedText).slice(-UNSUBMITTED_PROMPT_TAIL_CAP);+ },+ takeEnter(nowMs, lastOutputAtMs) {+ if (worked || inputAt === null || enters >= maxAttempts) return 0;+ if (nowMs - lastOutputAtMs < settleMs || nowMs - inputAt < settleMs) return 0;+ if (!holdsUnsubmittedPaste()) return 0;+ enters += 1;+ inputAt = nowMs;+ return enters;+ },+ get worked() { return worked; },+ };+}+// ─── agy exited to its launch shell ─────────────────────────────────────────//// When agy quits (a crash, a dropped connection, a stray `/exit`), it printsdiff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex 06568cb8b0..5f21342553 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -17,6 +17,7 @@ import {createTruncationNudgeGate,TRUNCATION_NUDGE_MAX_ATTEMPTS,createStallNudgeGate,+ createPromptSubmissionGate,STALL_NUDGE_MAX_TOTAL,STALL_NUDGE_IDLE_MS,STALL_NUDGE_RECOVERY_MS,@@ -2109,6 +2110,35 @@ describe('answerStartupDialogs', () => {});});+// The bare Enter can pick a dialog's highlighted default, so it is withheld+// unless the paste chip is still the last thing on screen (#12769).+describe('createPromptSubmissionGate', () => {+ const CHIP = '❯ [Pasted text #1 +353 lines]\n⏵⏵ bypass permissions on';+ const settled = (gate, at = 0) => gate.takeEnter(at + 21_000, at);++ it('presses Enter on a settled chip, and never over selector chrome painted after it', () => {+ const gate = createPromptSubmissionGate({ settleMs: 20_000 });+ gate.noteInput(0, CHIP);+ expect(gate.takeEnter(10_000, 0)).toBe(0);+ expect(settled(gate)).toBe(1);++ const dialog = createPromptSubmissionGate({ settleMs: 20_000 });+ dialog.noteInput(0, CHIP);+ dialog.observe('Do you want to proceed?\n❯ 1. Yes\n 2. No', 1_000);+ expect(settled(dialog, 1_000)).toBe(0);+ });++ it('counts only output past the echo window as the turn running', () => {+ const gate = createPromptSubmissionGate({ settleMs: 20_000, workEvidenceMs: 30_000 });+ gate.noteInput(0, CHIP);+ gate.observe('echo of our own keystroke', 29_000);+ expect(gate.worked).toBe(false);+ gate.observe('• Working (31s • esc to interrupt)', 31_000);+ expect(gate.worked).toBe(true);+ expect(settled(gate, 31_000)).toBe(0);+ });+});+describe('createStallNudgeGate', () => {it('nudges a session that went quiet with its task unfinished', () => {const gate = createStallNudgeGate();diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 9649686ad6..2056d4a619 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -902,6 +902,15 @@ export const COMPLETION_REASON_ANALYSES = {message: 'Prompt never rendered in the TUI input box',suggestedFix: 'The provider CLI accepted the bracketed paste but the prompt never appeared, so nothing was ever submitted. Usually the TUI was still initializing, or a startup dialog (folder trust, an opt-in offer, an account banner) was up and swallowed the paste. Check the tail of the raw transcript for a modal — if it is one PortOS does not know about yet, it needs a dismissal branch in agentTuiSpawning.js.'},+ // The TUI spawner's verdict for a prompt that was submitted but never started+ // a turn (createPromptSubmissionGate): bare Enters and every stall nudge went+ // unanswered. Retryable — a fresh session usually takes the same prompt.+ 'prompt-not-submitted': {+ category: 'startup-failure',+ actionable: false,+ message: 'Prompt was delivered but the TUI never started working on it',+ suggestedFix: 'The paste rendered and Enter was sent, but the session stayed idle through every bare Enter and stall nudge, so the run was failed and the task requeued. If it recurs, check the tail of the raw transcript: a composer still holding a pasted-text chip means the TUI ignored the submit key, and a dialog or banner there means it needs a dismissal branch.'+ },'tui-not-ready': {category: 'startup-failure',actionable: false,@@ -1075,7 +1084,7 @@ const AWAITING_INPUT_REFINABLE_REASONS = new Set(['idle-no-changes', 'idle-no-ac* dialog is a STARTUP gate the spawner does not know how to dismiss, and the fix* is a dismissal branch, not a reworded task.*/-const STARTUP_GATE_REFINABLE_REASONS = new Set(['paste-not-rendered', 'tui-not-ready']);+const STARTUP_GATE_REFINABLE_REASONS = new Set(['paste-not-rendered', 'tui-not-ready', 'prompt-not-submitted']);/*** Re-word a run whose transcript ends on an unanswered prompt — a legacy idle-out thatdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 04037447f5..303fb0ec61 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -275,6 +275,9 @@ import {STALL_NUDGE_IDLE_MS,STALL_NUDGE_MAX_ATTEMPTS,STALL_NUDGE_TEXT,+ PROMPT_WORK_EVIDENCE_MS,+ UNSUBMITTED_PROMPT_SETTLE_MS,+ UNSUBMITTED_PROMPT_ENTER_MAX_ATTEMPTS,RETRY_STALL_MS,TOOL_PERMISSION_NUDGE_TEXT,} from '../lib/tuiHandshake.js';@@ -1233,6 +1236,11 @@ describe('spawnTuiAgent runtime', () => {await flushMicrotasks();await vi.advanceTimersByTimeAsync(3600);await flushMicrotasks();+ // It works for a while before going quiet: a run that never started is+ // failed instead (#12769), and this one is about the lack of a ceiling.+ await vi.advanceTimersByTimeAsync(PROMPT_WORK_EVIDENCE_MS);+ await capturedOnData(Buffer.from('Reading the repository…\n'));+ await flushMicrotasks();await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000);await flushMicrotasks();@@ -2299,6 +2307,11 @@ describe('spawnTuiAgent runtime', () => {it("badges a session that ignored every nudge instead of giving up silently", async () => {await driveAgyToSubmittedPrompt();+ // A run that worked and then stopped; one that never started is failed+ // instead (see the never-started case below).+ await vi.advanceTimersByTimeAsync(PROMPT_WORK_EVIDENCE_MS);+ await capturedOnData(Buffer.from('Reading the repository…\n'));+ await flushMicrotasks();vi.mocked(shellService.pasteToSession).mockClear();// A session wedged below its composer never echoes the paste, so nothing@@ -2318,6 +2331,71 @@ describe('spawnTuiAgent runtime', () => {);});+ // ── Unsubmitted prompt: the paste chip rendered, every submit Enter was lost ──+ // #12769: claim runs sat at `❯ [Pasted text #1 +N lines]` indefinitely. As+ // possible claim owners they held every claim checkout in their repository.+ const driveToUnsubmittedChip = async () => {+ runSpawn({ prompt: 'claim the issue and ship a PR' });+ await flushMicrotasks();+ await capturedOnData(Buffer.from('>_ OpenAI Codex\n' + CODEX_COMPOSER));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();+ expect(pasteCount()).toBe(1);+ await capturedOnData(Buffer.from('> [Pasted Content 29448 chars]\n'));+ await flushMicrotasks();+ // The paste confirms and every submit Enter goes out; the TUI ignores them.+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();+ };+ const enterCount = () => vi.mocked(shellService.writeToSession).mock.calls+ .filter(([id, data]) => id === SESSION_ID && data === '\r').length;++ it('presses Enter again on a prompt left unsubmitted in the composer, without re-pasting', async () => {+ await driveToUnsubmittedChip();+ const submitted = enterCount();+ expect(submitted).toBeGreaterThan(0);++ await vi.advanceTimersByTimeAsync(UNSUBMITTED_PROMPT_SETTLE_MS - 5000);+ await flushMicrotasks();+ expect(enterCount()).toBe(submitted);++ await vi.advanceTimersByTimeAsync(5000 + SIGNAL_POLL_MS);+ await flushMicrotasks();+ expect(enterCount()).toBe(submitted + 1);+ expect(pasteCount()).toBe(1);+ expect(shellService.pasteToSession).not.toHaveBeenCalled();++ // That Enter started the turn: a working session is left alone.+ for (let elapsed = 0; elapsed < 3 * 60_000; elapsed += 1000) {+ await capturedOnData(Buffer.from('• Working (12s • esc to interrupt)\n'));+ await vi.advanceTimersByTimeAsync(1000);+ }+ await flushMicrotasks();+ expect(enterCount()).toBe(submitted + 1);+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ });++ it('fails a run that never started after the full nudge budget, so the task retries', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });+ await driveToUnsubmittedChip();+ const submitted = enterCount();++ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS * (STALL_NUDGE_MAX_ATTEMPTS + 2));+ await flushMicrotasks();+ // A bounded number of bare Enters, then the stall nudges, then the verdict.+ expect(enterCount()).toBe(submitted + UNSUBMITTED_PROMPT_ENTER_MAX_ATTEMPTS);+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(STALL_NUDGE_MAX_ATTEMPTS);+ vi.useRealTimers();+ await completeDone;+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', success: false, completionReason: 'prompt-not-submitted' }),+ );+ expect(cosAgentLifecycle.updateAgent).not.toHaveBeenCalledWith('agent-1', { metadata: { phase: 'stalled' } });+ });+// ── 1b. Submit-Enter retries ─────────────────────────────────────────────────// A single `\r` after a large bracketed paste can be swallowed mid-paste-// commit, stranding the prompt unsent (the "I had to hit Enter myself" bug,diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.jsindex 453c0c787a..7594aef00a 100644--- a/server/services/agentTuiSpawning/sessionController.js+++ b/server/services/agentTuiSpawning/sessionController.js@@ -62,6 +62,8 @@ import {TRUNCATION_NUDGE_MAX_ATTEMPTS,TRUNCATION_NUDGE_TEXT,createStallNudgeGate,+ createPromptSubmissionGate,+ UNSUBMITTED_PROMPT_ENTER_MAX_ATTEMPTS,createAgyResumeGate,AGY_RESUME_MAX_ATTEMPTS,STALL_NUDGE_MAX_ATTEMPTS,@@ -113,7 +115,9 @@ const SENTINEL_RECOVERY_RETRY_MS = 250;// read by handleData and the provider-signal timer well outside this cluster, so// they stay owned by the controller and are threaded through rather than// duplicated here. `finishStartupFailure`/`appendLine` are likewise the-// controller's own closures, passed in rather than re-implemented.+// controller's own closures, passed in rather than re-implemented, and+// `noteInput` reports each submit and re-delivery to the controller's+// prompt-submission gate.function createPasteRetryController({agentId,sessionLabel,@@ -129,6 +133,7 @@ function createPasteRetryController({isFinalized,markPromptSent,markPromptSubmitted,+ noteInput,finishStartupFailure,}) {// Markers already present in the prompt text itself (a transcript-analysis task@@ -228,6 +233,7 @@ function createPasteRetryController({if (submitEnterTimer) clearInterval(submitEnterTimer);const handle = paste(text, { label: `[cosAgents] ${label}` });submitEnterTimer = handle || null;+ if (handle) noteInput();return !!handle;};@@ -259,12 +265,17 @@ function createPasteRetryController({attemptPaste(reason);};- const submitPaste = () => {+ // The commit buffer goes to noteInput because it holds the paste chip: a TUI+ // that ignores the submit Enter may never repaint it (createPromptSubmissionGate).+ const submitConfirmedPaste = () => {+ const evidence = pasteState.buffer;+ clearPaste();if (pasteRetryTimer) {clearTimeout(pasteRetryTimer);pasteRetryTimer = null;}markPromptSubmitted();+ noteInput(evidence);submitEnterTimer = scheduleSubmitEnters(() => write(SUBMIT_KEY, { promptSubmission: true }),() => isFinalized()@@ -328,8 +339,7 @@ function createPasteRetryController({pasteRetryTimer = null;if (isFinalized()) return;if (pasteConfirmed(pasteState.buffer)) {- clearPaste();- submitPaste();+ submitConfirmedPaste();return;}attemptPaste(reason);@@ -384,8 +394,7 @@ function createPasteRetryController({// pasteConfirmed is a superset of the pasteCommitted exit above, so only// the commitWaitMs timeout can fall through to the verification window.if (pasteConfirmed(commitBuffer)) {- clearPaste();- submitPaste();+ submitConfirmedPaste();return;}// Markerless AND text not visible yet: give the prompt a short window to@@ -407,8 +416,7 @@ function createPasteRetryController({clearInterval(pasteVerifyTimer);pasteVerifyTimer = null;if (confirmed) {- clearPaste();- submitPaste();+ submitConfirmedPaste();} else {enterBackoff();retryOrFailPaste();@@ -434,8 +442,7 @@ function createPasteRetryController({if (pasteState.phase === 'backoff' && pasteRetryTimer && pasteConfirmed(pasteState.buffer)) {clearTimeout(pasteRetryTimer);pasteRetryTimer = null;- clearPaste();- submitPaste();+ submitConfirmedPaste();}};@@ -608,6 +615,10 @@ export function createTuiSessionController({// The stall no detector can see, because nothing is on screen: a turn that// ended with the task unfinished. Reads pure silence. See createStallNudgeGate.const stallNudgeGate = createStallNudgeGate();+ // A prompt whose paste landed but whose submit Enter was ignored: pressed+ // again where it sits, and a run that never started is failed rather than+ // parked. See createPromptSubmissionGate.+ const promptGate = createPromptSubmissionGate({ promptMarkerCount: countPasteMarkers(stripAnsi(prompt)) });// Guards ingestDoneSentinel to a single read. finish() is its only caller and// is itself guarded by `sessionPhase`, so this is defensive — it pins the// read-at-most-once invariant at the helper.@@ -1434,6 +1445,7 @@ export function createTuiSessionController({}if (promptSubmittedAt) codexModelRejectionGate?.observe(stripped);+ promptGate.observe(stripped, now);// Startup-idle detection (the promptTimer's non-inputReady branch below)// reads lastOutputAt/firstOutputAt to decide the TUI has gone quiet and is// ready for the prompt paste. Gate them on commandInjected for the same@@ -1689,6 +1701,7 @@ export function createTuiSessionController({isFinalized: () => isTerminal() || !!terminalRefusal,markPromptSent: () => { promptSentAt = Date.now(); },markPromptSubmitted: () => { if (promptSubmittedAt === null) promptSubmittedAt = Date.now(); },+ noteInput: (evidence) => promptGate.noteInput(Date.now(), evidence),finishStartupFailure,});@@ -1927,6 +1940,15 @@ export function createTuiSessionController({}return;}+ // A prompt still sitting unsubmitted gets the Enter it missed, long before+ // the stall nudge below would paste a second message on top of it.+ const enter = sessionPhase === 'running' && promptSubmittedAt ? promptGate.takeEnter(now, lastOutputAt) : 0;+ if (enter) {+ if (session.write(sessionId, SUBMIT_KEY, { promptSubmission: true }) !== false) {+ appendLine(LIFECYCLE_LINES.unsubmittedPromptEntered({ attempt: enter, max: UNSUBMITTED_PROMPT_ENTER_MAX_ATTEMPTS }));+ }+ return;+ }// Last, and only once no gate above has a say: every one of them describes a// session stalled for a KNOWN reason, and their own silence tests would be// pre-empted by a nudge sent on plain quiet.@@ -1946,6 +1968,19 @@ export function createTuiSessionController({// own clock, so a run can be done-but-not-yet-finalized at this instant, and// this is the only moment the answer is acted on.if (sentinelPresent()) return;+ if (stalled === 'exhausted' && !promptGate.worked) {+ // Nothing but echoes of PortOS's own keystrokes since the submit: the+ // prompt never started a turn. Parking it would keep a live run that+ // registered as a possible claim owner (claimSelectionPending) holding+ // every claim checkout in its repository; failing it releases them and+ // requeues the task through the ordinary retry budget.+ emitLog('warn', `🛑 TUI agent ${agentId} never started its prompt — failing it after ${stallNudgeGate.nudgesSent} stall nudges`, { agentId });+ finishStartupFailure(+ 'prompt-not-submitted',+ `${tuiConfig.command} never started working on the submitted prompt: the session stayed idle through ${stallNudgeGate.nudgesSent} stall nudges.`,+ ).catch(err => emitLog('error', `TUI agent ${agentId} finishStartupFailure(prompt-not-submitted) failed: ${err?.message || err}`, { agentId }));+ return;+ }if (stalled === 'exhausted') {// Every nudge in the streak was ignored (wedged below its composer), or the// run spent its lifetime budget answering nudges without ever finishing