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
feat: type "continue" into a CoS TUI agent that stopped mid-task
[._.]/ Adam Eivyde6c39f5a112
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 3b5c20c152..cfe1920f4d 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -639,11 +639,18 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,</span>)}{!inactive && (- <span className={`px-2 py-0.5 text-xs rounded animate-pulse shrink-0 ${- agent.metadata?.phase === 'initializing' ? 'bg-yellow-500/20 text-yellow-400' :- 'bg-port-accent/20 text-port-accent'- }`}>- {agent.metadata?.phase === 'initializing' ? 'Initializing'+ // 'stalled' is the one phase that does NOT pulse: the run is still+ // alive but has ignored every nudge, and an animated badge reads as+ // progress. See the stall gate in server/services/agentTuiSpawning.js.+ <span className={`px-2 py-0.5 text-xs rounded shrink-0 ${+ agent.metadata?.phase === 'stalled' ? 'bg-orange-500/20 text-orange-400' :+ agent.metadata?.phase === 'initializing' ? 'bg-yellow-500/20 text-yellow-400 animate-pulse' :+ 'bg-port-accent/20 text-port-accent animate-pulse'+ }`} title={agent.metadata?.phase === 'stalled'+ ? 'Idle and not responding to nudges — open the Shell tab to take it over'+ : undefined}>+ {agent.metadata?.phase === 'stalled' ? 'Stalled'+ : agent.metadata?.phase === 'initializing' ? 'Initializing': 'Working'}</span>)}diff --git a/docs/features/cos-agent-runner.md b/docs/features/cos-agent-runner.mdindex bbfee08088..90cfc32bfa 100644--- a/docs/features/cos-agent-runner.md+++ b/docs/features/cos-agent-runner.md@@ -41,6 +41,24 @@ A separate `portos-cos` PM2 process that:- A disconnect does **not** demote. In runner mode the runner owns every agent process, so while it is down new tasks are **held** as `pending` (logged once, not per task) and resume on reconnect. Demoting would spawn them as children of `portos-server` — the orphaning this app exists to prevent.- Agents already spawned directly keep completing through the direct path across a promotion; reconciliation only adopts agents this server does not already own.+## Unattended recovery gates++Nobody is watching a CoS TUI session, so nothing types into it when the model stops early. Five gates in `server/services/agentTuiSpawning.js` watch the PTY stream and act on one shared 5s poll. Four of them prefer a nudge into the live session over a kill, because the TUI still holds the whole conversation; only the retry stall ends the run, since a request the provider never answers will not answer the next one either. No gate reaps a run on the clock alone — the wall-clock ceiling was removed deliberately, after it killed agents 30 seconds past a merged PR.++| Gate | What it sees | What it does |+| --- | --- | --- |+| Self-clearing provider signal | agy's "verifying your account eligibility" banner, which REJECTS the submission | Re-pastes the whole prompt while a grace window is open, then fails over |+| Local-runtime OOM | a Metal/CUDA out-of-memory box that killed the turn | Pastes `continue` once the session is quiet; fails over to a fallback provider after 3 |+| Retry stall | the TUI retrying one request past attempt 3, ten minutes on | Fails the run over to a fallback provider |+| Tool-permission dialog | Claude Code asking to approve a call nobody can approve | Declines it, then explains why and sends the session back to work |+| **Stall** | **nothing at all — the session went quiet with the task unfinished** | **Pastes a `continue` nudge after 3 minutes of silence, up to 3 times; then badges the agent card `Stalled`** |++The stall gate is the one with no signal to match on: the model narrates its next step ("Next: /do:pr"), ends its turn, and the TUI returns to its idle composer. Since the wall-clock ceiling was removed, nothing else would ever touch that session. It reads pure silence rather than provider chrome, because in-flight chrome is per-TUI vocabulary while bytes on the PTY are universal. Claude Code repaints its working counter about once a second for as long as any tool or API call is in flight; OpenCode barely repaints its chrome at all, but streams megabytes of transcript through the same stream. Three unbroken minutes of NOTHING is a composer at rest under both.++It stays out of the way of the other four: it is polled last, it waits for the prompt to actually be in, and it skips a run that already wrote its completion sentinel or is mid-`finish()`. Its post-nudge wait is measured from the nudge rather than from output, because a session wedged below its composer never echoes the paste. A session that prints for 30s past a nudge took the hint and gets its full budget back, so a long run that stalls again hours later is not treated as a second strike.++A session that ignores all three nudges is wedged below its composer, and no paste will reach it. Rather than give up silently — leaving a run holding its execution lane with nothing to show for it — the spawner logs the verdict and sets `metadata.phase = 'stalled'`, which the agent card renders as a non-pulsing **Stalled** badge pointing at the Shell tab. The badge clears itself on the session's next byte of output. Prevention lives on the other side of the same problem: `UNATTENDED_RUN_RULE` (`server/services/agentPromptBuilder.js`) tells every agent that naming its next step is not doing it. Constants: `STALL_NUDGE_*` in `server/lib/tuiHandshake.js`.+## Features- **Process Isolation**: Agent processes survive server restartsdiff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 85d5ecb26d..f91f073061 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -1436,3 +1436,106 @@ export function createToolPermissionGate() {takeNudge: nudge.takeNudge,};}++// ---------------------------------------------------------------------------+// Stall nudge — "the session stopped mid-task and nothing will ever re-ask"+// ---------------------------------------------------------------------------+//+// The failure this exists for has no error banner, no dialog and no exit: the+// model narrates its next step ("Next: /do:pr"), ends its turn, and the TUI+// returns to its idle composer. The run is not finished, the sentinel is not+// written, and — since the wall-clock ceiling was removed — nothing else in the+// unattended path will ever touch that session again. A human dropping into the+// Shell tab and typing `continue` recovers it every time; this gate types it.+//+// Unlike the OOM and tool-permission gates, there is nothing to ARM on: the+// condition IS the silence, so this one is poll-only. That also makes the+// threshold the entire false-positive defense — see STALL_NUDGE_IDLE_MS.++// How long the session must have printed NOTHING before it counts as stopped.+//+// Deliberately a silence test rather than a chrome test, for the reason+// OOM_NUDGE_SETTLE_MS spells out: in-flight chrome is per-provider vocabulary,+// while silence is universal. One number covers every TUI because what it+// measures is bytes on the PTY, not a footer — Claude Code repaints its working+// counter about once a second for as long as ANY tool or API call is in flight,+// and the provider that barely repaints its chrome at all (OpenCode, ~8 times+// across a 74MB transcript) is streaming that 74MB through this same stream.+// Three unbroken minutes of NOTHING is a composer at rest under both.+//+// Three minutes rather than the old ceiling's scale because the cost asymmetry+// runs one way: a nudge that was not needed is queued into the composer and read+// as "keep going", while a nudge that never comes leaves the run holding its+// lane forever.+export const STALL_NUDGE_IDLE_MS = 3 * 60 * 1000;+// How much output AFTER a nudge proves the session took the hint. Long enough to+// exclude the bracketed-paste echo of the nudge itself (which lands within a+// second or so), short enough that a session that genuinely resumed clears its+// streak immediately. A run that works for hours and then stalls again gets the+// full budget back rather than inheriting a spent one.+export const STALL_NUDGE_RECOVERY_MS = 30000;+// After this many CONSECUTIVE unanswered nudges, stop. A session that ignored+// three of them is wedged below the composer (a dead child, a TUI that stopped+// reading its PTY), and pasting into it forever only fills raw.txt.+export const STALL_NUDGE_MAX_ATTEMPTS = 3;+// What gets pasted. It leads with the literal word a human used, for the literal+// reason it worked — the TUI still holds the whole conversation and the model+// only needs a turn — and then closes the two doors that produce this state in+// an unattended run: waiting on an answer that is never coming, and treating+// "I described the next step" as finishing it.+export const STALL_NUDGE_TEXT = 'continue — this session went quiet with its task unfinished, and the completion sentinel has not been written. Nobody is watching it: no question will be answered and no approval is coming, so choose the most reasonable option yourself. Carry out the next step you named, then the one after it, and keep going until the task is genuinely complete and the sentinel is written.';++/**+ * State machine for "nudge a TUI session that stopped mid-task".+ *+ * Poll `takeNudge(nowMs, lastOutputAtMs)` on whatever timer the consumer already+ * runs. It owns the silence threshold, the post-nudge quiet period, the recovery+ * reset and the attempt budget so a consumer can't get any of them subtly wrong,+ * and returns:+ * - the 1-based nudge number — paste and say so+ * - `'exhausted'` (once) — the budget is spent and the session is STILL quiet,+ * so it is wedged below its composer rather than merely stopped. Reported+ * rather than swallowed because giving up silently is the very condition+ * this gate exists to end: the run holds its lane with nothing to show for+ * it, and the sibling gates all announce their verdict.+ * - 0 — nothing to do+ *+ * The post-nudge wait is measured from the NUDGE, not from output, and that is+ * the load-bearing detail: a session wedged below its composer never echoes the+ * paste, so a purely output-based gate would re-fire on the very next poll tick+ * and paste continuously until the budget ran out seconds later.+ *+ * @param {{ idleMs?: number, recoveryMs?: number, maxAttempts?: number }} [options]+ * @returns {{ takeNudge: (nowMs: number, lastOutputAtMs: number) => number|'exhausted' }}+ */+export function createStallNudgeGate({+ idleMs = STALL_NUDGE_IDLE_MS,+ recoveryMs = STALL_NUDGE_RECOVERY_MS,+ maxAttempts = STALL_NUDGE_MAX_ATTEMPTS,+} = {}) {+ let attempts = 0;+ let nudgedAt = null;+ let reportedExhausted = false;+ return {+ takeNudge(nowMs, lastOutputAtMs) {+ // Checked before the budget so an exhausted streak can still be cleared by+ // a session that came back to life — which also re-arms the verdict, since+ // a run that recovered and stalled again is wedged afresh.+ if (nudgedAt !== null && lastOutputAtMs - nudgedAt > recoveryMs) {+ attempts = 0;+ nudgedAt = null;+ reportedExhausted = false;+ }+ if (nowMs - lastOutputAtMs < idleMs) return 0;+ if (nudgedAt !== null && nowMs - nudgedAt < idleMs) return 0;+ if (attempts >= maxAttempts) {+ if (reportedExhausted) return 0;+ reportedExhausted = true;+ return 'exhausted';+ }+ attempts += 1;+ nudgedAt = nowMs;+ return attempts;+ },+ };+}diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex f82f55d40c..54bdb4fa7e 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -14,6 +14,10 @@ import {OOM_NUDGE_ARM_WINDOW_MS,OOM_NUDGE_COOLDOWN_MS,OOM_NUDGE_MAX_ATTEMPTS,+ createStallNudgeGate,+ STALL_NUDGE_IDLE_MS,+ STALL_NUDGE_RECOVERY_MS,+ STALL_NUDGE_MAX_ATTEMPTS,SELF_CLEARING_RESUBMIT_INTERVAL_MS,SELF_CLEARING_RESUBMIT_ECHO_MS,MCP_BOOT_PASTE_DEADLINE_MS,@@ -2030,3 +2034,64 @@ describe('answerStartupDialogs', () => {expect(second.written).toEqual([]);});});++describe('createStallNudgeGate', () => {+ it('nudges a session that went quiet with its task unfinished', () => {+ const gate = createStallNudgeGate();+ const quietSince = 0;+ // Still inside the threshold: a slow tool call is not a stall.+ expect(gate.takeNudge(STALL_NUDGE_IDLE_MS - 1, quietSince)).toBe(0);+ expect(gate.takeNudge(STALL_NUDGE_IDLE_MS, quietSince)).toBe(1);+ });++ it('waits out the threshold from the NUDGE, not from output', () => {+ // The case this exists for: a session wedged below its composer never+ // echoes the paste, so lastOutputAt stays put. Measuring from output alone+ // would re-fire on the very next 5s poll and spend the whole budget in+ // seconds.+ const gate = createStallNudgeGate();+ const quietSince = 0;+ const firstNudgeAt = STALL_NUDGE_IDLE_MS;+ expect(gate.takeNudge(firstNudgeAt, quietSince)).toBe(1);+ expect(gate.takeNudge(firstNudgeAt + 5000, quietSince)).toBe(0);+ expect(gate.takeNudge(firstNudgeAt + STALL_NUDGE_IDLE_MS - 1, quietSince)).toBe(0);+ expect(gate.takeNudge(firstNudgeAt + STALL_NUDGE_IDLE_MS, quietSince)).toBe(2);+ });++ it('reports exhaustion once after STALL_NUDGE_MAX_ATTEMPTS unanswered nudges, then goes quiet', () => {+ const gate = createStallNudgeGate();+ let now = 0;+ for (let i = 1; i <= STALL_NUDGE_MAX_ATTEMPTS; i += 1) {+ now += STALL_NUDGE_IDLE_MS;+ expect(gate.takeNudge(now, 0)).toBe(i);+ }+ // Wedged below the composer: pasting into it forever only fills raw.txt, so+ // the verdict is handed back ONCE and the consumer says it out loud.+ expect(gate.takeNudge(now + STALL_NUDGE_IDLE_MS, 0)).toBe('exhausted');+ expect(gate.takeNudge(now + STALL_NUDGE_IDLE_MS * 2, 0)).toBe(0);+ expect(gate.takeNudge(now + STALL_NUDGE_IDLE_MS * 10, 0)).toBe(0);+ });++ it('does not read the nudge\'s own paste echo as recovery', () => {+ const gate = createStallNudgeGate();+ const firstNudgeAt = STALL_NUDGE_IDLE_MS;+ expect(gate.takeNudge(firstNudgeAt, 0)).toBe(1);+ // The bracketed-paste echo lands a beat later and is the ONLY output the+ // wedged session produces. Counting it would reset the streak forever.+ const echoAt = firstNudgeAt + 1000;+ expect(gate.takeNudge(echoAt + STALL_NUDGE_IDLE_MS, echoAt)).toBe(2);+ });++ it('clears an exhausted streak — and re-arms the verdict — once the session comes back to life', () => {+ const gate = createStallNudgeGate();+ let now = 0;+ for (let i = 1; i <= STALL_NUDGE_MAX_ATTEMPTS; i += 1) {+ now += STALL_NUDGE_IDLE_MS;+ gate.takeNudge(now, 0);+ }+ // It printed well past the paste echo, so the nudges landed after all. A+ // stall hours later is a fresh one, with the whole budget available again.+ const revivedAt = now + STALL_NUDGE_RECOVERY_MS + 1;+ expect(gate.takeNudge(revivedAt + STALL_NUDGE_IDLE_MS, revivedAt)).toBe(1);+ });+});diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 4b6beabc9d..84daeb7b88 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -221,6 +221,7 @@ PortOS launched you autonomously. Nobody is watching this session and nothing ca- **Never ask the user to choose or approve.** Make the call yourself, state the assumption in your summary, and proceed.- **Invoke commands and skills in their non-interactive form.** If one drafts something and gates on approval before acting, pass the flag that skips that gate (\`--yes\` for the slashdo commands that have one).- **Ambiguous task?** Pick the most reasonable reading, do the work, and note the alternatives you rejected in your completion summary.+- **Never end a turn with the task unfinished.** Naming your next step is not doing it — if you write "Next: open the PR", open it in that same turn. Nothing will type "continue" for you, and a turn that ends early strands the run.- **Genuinely blocked** (missing credential, contradictory requirements)? Write why to the completion sentinel and stop. Do NOT wait for a reply.`;/** Load and safely stage the review recipe shared by full and light prompts. */diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex ec0b2b0c05..6fe75145aa 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -51,6 +51,9 @@ import {TOOL_PERMISSION_NUDGE_TEXT,OOM_NUDGE_MAX_ATTEMPTS,OOM_NUDGE_TEXT,+ createStallNudgeGate,+ STALL_NUDGE_MAX_ATTEMPTS,+ STALL_NUDGE_TEXT,createMcpBootTracker,MCP_BOOT_PASTE_DEADLINE_MS,MCP_BOOT_PASTE_RETRY_DELAY_MS,@@ -814,6 +817,9 @@ export async function spawnTuiAgent({// the launch posture already decided the run's scope — then nudged along// once the session goes quiet. See createToolPermissionGate.const toolPermissionGate = createToolPermissionGate();+ // 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();// 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.@@ -1960,7 +1966,10 @@ export async function spawnTuiAgent({// a CoS TUI may remain silent for as long as the provider needs.const providerSignalTimer = setInterval(() => {if (isTerminal()) return;- const expired = selfClearingGate.takeExpired(Date.now());+ // One clock for every gate on this tick. They all measure the same silence,+ // so reading the wall four times only invites them to disagree about it.+ const now = Date.now();+ const expired = selfClearingGate.takeExpired(now);if (expired) {// setInterval can't await, and an unhandled rejection here would crash the// process (the callback-boundary hazard AGENTS.md calls out).@@ -1980,7 +1989,7 @@ export async function spawnTuiAgent({}// A declined permission dialog ends the turn; once the session is quiet,// tell it why and send it back to work.- const declined = toolPermissionGate.takeNudge(Date.now(), lastOutputAt);+ const declined = toolPermissionGate.takeNudge(now, lastOutputAt);if (declined) {if (pasteController?.resubmit({ text: TOOL_PERMISSION_NUDGE_TEXT, label: 'declined-permission nudge' })) {appendLine(`🔁 Nudged the session to continue after declined permission prompt ${declined}`);@@ -1990,10 +1999,46 @@ export async function spawnTuiAgent({// Nudge a session a local-GPU OOM parked. Rides this timer rather than one// of its own so the nudge cadence and the fail-over verdict stay on the same// clock — and so there is one fewer interval to leak past finish().- const nudge = oomNudgeGate.takeNudge(Date.now(), lastOutputAt);- if (!nudge) return;- if (pasteController?.resubmit({ text: OOM_NUDGE_TEXT, label: 'local-runtime OOM nudge' })) {- appendLine(`🔁 Local runtime OOM — nudged the session to continue (attempt ${nudge}/${OOM_NUDGE_MAX_ATTEMPTS})`);+ const nudge = oomNudgeGate.takeNudge(now, lastOutputAt);+ if (nudge) {+ if (pasteController?.resubmit({ text: OOM_NUDGE_TEXT, label: 'local-runtime OOM nudge' })) {+ appendLine(`🔁 Local runtime OOM — nudged the session to continue (attempt ${nudge}/${OOM_NUDGE_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.+ //+ // `sessionPhase`, not `isTerminal()`: a finish() parked on the merge-gate+ // contract check (a `gh` PR probe) sits in 'finishing' for as long as that+ // network call takes, non-terminal the whole time, and it may yet paste a+ // nudge of its own. And `promptSubmittedAt`, because before the prompt is+ // in the promptTimer owns delivery — silence there is startup, not a stall.+ if (sessionPhase !== 'running' || !promptSubmittedAt) return;+ const stalled = stallNudgeGate.takeNudge(now, lastOutputAt);+ if (!stalled) return;+ // Read the sentinel here rather than on every tick: its watcher polls on its+ // 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') {+ // Every nudge was ignored, so the session is wedged below its composer+ // rather than merely stopped. There is no ceiling left to reap it, so say+ // so loudly and badge the card — an agent nobody can see is stuck is the+ // condition this gate exists to end, and only a human can end this one.+ appendLine(`🛑 Session still idle after ${STALL_NUDGE_MAX_ATTEMPTS} nudges — it is not responding; open the Shell tab to take it over`);+ emitLog('warn', `🛑 TUI agent ${agentId} is wedged — ${STALL_NUDGE_MAX_ATTEMPTS} stall nudges went unanswered`, { agentId });+ updateAgent(agentId, { metadata: { phase: 'stalled' } }).catch((err) =>+ emitLog('error', `TUI agent ${agentId} stalled-phase update failed: ${err?.message || err}`, { agentId }));+ // Re-arm the onData handler's one-shot "phase: working" write, so a+ // session that wakes up later (a provider call that finally returned)+ // clears the badge on its next chunk instead of wearing it to the end.+ hasStartedWorking = false;+ return;+ }+ if (pasteController?.resubmit({ text: STALL_NUDGE_TEXT, label: 'stalled-session nudge' })) {+ appendLine(`🔁 Session idle with the task unfinished — nudged it to continue (attempt ${stalled}/${STALL_NUDGE_MAX_ATTEMPTS})`);}}, PROVIDER_SIGNAL_POLL_MS);diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 666cf9c4a9..e68a0295ed 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -257,6 +257,9 @@ import {OOM_NUDGE_COOLDOWN_MS,OOM_NUDGE_MAX_ATTEMPTS,OOM_NUDGE_TEXT,+ STALL_NUDGE_IDLE_MS,+ STALL_NUDGE_MAX_ATTEMPTS,+ STALL_NUDGE_TEXT,RETRY_STALL_MS,TOOL_PERMISSION_NUDGE_TEXT,} from '../lib/tuiHandshake.js';@@ -1931,6 +1934,73 @@ describe('spawnTuiAgent runtime', () => {expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();});+ // The spawner acts on every gate from one 5s poll (PROVIDER_SIGNAL_POLL_MS,+ // module-private), so each nudge lands within a tick of its threshold.+ const SIGNAL_POLL_MS = 5000;++ // ── Stalled session: the turn just ended, with the task unfinished ─────────+ // agent-bb3061af (2026-09-17): the run finished its /simplify pass, printed+ // "Next: /do:pr", ended its turn and sat at an idle composer. Nothing was on+ // screen for a detector to match and — since the wall-clock ceiling was+ // removed — nothing would ever have touched it again. A human opened the Shell+ // tab and typed "continue", and it finished.+ it("nudges a session that went quiet with the task unfinished", async () => {+ await driveAgyToSubmittedPrompt();+ vi.mocked(shellService.pasteToSession).mockClear();++ // A short lull is ordinary: a slow tool call paints nothing.+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS - 60_000);+ await flushMicrotasks();+ expect(shellService.pasteToSession).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(60_000 + SIGNAL_POLL_MS);+ await flushMicrotasks();+ expect(shellService.pasteToSession).toHaveBeenCalledWith(+ SESSION_ID,+ STALL_NUDGE_TEXT,+ expect.objectContaining({ label: expect.stringContaining("stalled") }),+ );+ // A nudge, never a verdict: the run carries on.+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ });++ it("leaves a working session alone however long the run lasts", async () => {+ await driveAgyToSubmittedPrompt();+ vi.mocked(shellService.pasteToSession).mockClear();++ // Claude Code repaints its working counter about once a second for as long+ // as any call is in flight. A run that keeps printing is never nudged.+ for (let elapsed = 0; elapsed < STALL_NUDGE_IDLE_MS + 60_000; elapsed += 60_000) {+ await capturedOnData(Buffer.from("· Thinking… (42s · esc to interrupt)\n"));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(60_000);+ await flushMicrotasks();+ }+ expect(shellService.pasteToSession).not.toHaveBeenCalled();+ });++ it("badges a session that ignored every nudge instead of giving up silently", async () => {+ await driveAgyToSubmittedPrompt();+ vi.mocked(shellService.pasteToSession).mockClear();++ // A session wedged below its composer never echoes the paste, so nothing+ // rewinds the idle clock — the budget is the only thing that stops it.+ // One window per nudge, plus one for the exhaustion verdict — and a spare,+ // because each nudge lands on the first 5s tick AFTER its threshold, so the+ // windows drift later as they stack.+ await vi.advanceTimersByTimeAsync(STALL_NUDGE_IDLE_MS * (STALL_NUDGE_MAX_ATTEMPTS + 2));+ await flushMicrotasks();+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(STALL_NUDGE_MAX_ATTEMPTS);+ // There is no runtime ceiling left to reap it, so the run keeps its lane —+ // which is only tolerable because the card now says it needs a human.+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ expect(cosAgentLifecycle.updateAgent).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,