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: unify shell-session paste submission (#3216)
[._.]/ Adam Eivy6b54a449e7fd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex ab90e5046d..97456ba77b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@- **[issue-3202] Restarting PortOS no longer marks a running agent "completed" or burns its retry budget** — a restart kills every agent PortOS owns, and the terminal-based ones reported that as a clean finish. The task was recorded as done with nothing but two startup lines to show for it, and the folder holding its work was deleted on the way out. When the task did come back, the restart was counted against it as a failure: three routine restarts were enough to block the task outright, and two in a row left it sitting in a 30-minute cooldown. PortOS now recognizes that it was the one that pulled the plug. An agent cut short by a restart — terminal-based or headless — is recorded as interrupted rather than finished, its working folder is left untouched, and the task returns to the queue immediately, resuming from what the interrupted run left behind with no retry charged and no cooldown. An agent that had already reported its results still completes normally, one you terminated yourself is still recorded as terminated, and agents that genuinely fail on their own are unaffected. Agents still stop when PortOS restarts; keeping them running across one is separate work.- **[issue-3202] CoS terminal agents now stay alive through a PortOS server restart** — their interactive processes run under the standalone CoS runner, while the web server reconnects to the surviving session, restores its Shell view and status stream, and continues without launching a duplicate. A deliberate full-stack restart still terminates the runner and its agents.- **[issue-3211] Orphaned agents now close their run history during recovery** — a process that disappeared before normal completion left its run permanently unfinished, with no end time, outcome, transcript size, or usage reconciliation. The recovery sweep now closes that run exactly once before requeuing the task, records PortOS-restart interruptions separately from ordinary failures, and safely handles older agents or missing run data.+- **[issue-3216] Messages pasted into agent terminals now submit reliably** — BTW notes, Shell photo drops, and max-runtime wrap-up prompts use the same repeated-Enter strategy, so a TUI reflow can no longer swallow the only submit keystroke and leave the message stranded.- **A brief internet outage no longer kills a working CoS agent.** When the machine lost its connection, a running agent's terminal went quiet — it couldn't reach the model — and after a few minutes the idle watchdog mistook that silence for a hung or finished agent and reaped it, throwing away in-progress work. PortOS now checks whether the machine is actually online before reaping an idle agent: while the connection is down, the reap is deferred and the agent is left alone to resume the moment the network returns (with a short grace so it isn't reaped in the instant between reconnecting and picking back up). Genuinely stuck agents on a healthy connection are still reaped on the same schedule as before, and the long absolute run-time ceiling still bounds an agent kept alive through a very long outage.- **Agents are now told nobody is there to answer them, and a run that stalled on a question says so.** An agent PortOS launches runs unattended, but nothing in its briefing said that — so an agent that hit a multiple-choice question or an approval gate would sit there presenting it to an empty room until the idle watchdog killed the run and discarded the work. One task was retried into the same question three times and filed nothing. Every agent briefing now states that no human is present, to decide for itself and record the assumption rather than ask, and to invoke slash commands in their non-interactive form. When a run does stall this way, the failure is no longer reported as a bare idle-out — PortOS notices the transcript ends on an unanswered prompt and says that's what happened, so the next step is skipping the gate rather than hunting for a stalled provider.- **An agent killed by a server restart now picks up where it left off instead of starting over.** Restarting PortOS kills every running agent mid-edit, and the task went back in the queue for a brand-new agent that built a fresh worktree from `main` — so hours of in-progress work sat on disk, untouched, while the replacement redid it from scratch. PortOS now records what the interrupted run left behind and hands the retry its actual working directory: its commits, its uncommitted edits, and its untracked files, exactly as they were. The retry is told up front that it's continuing someone else's run and to check `git status`, the commit log, and whether a PR was already opened or merged before writing any code. Work that already landed is still never resumed onto, and if the leftover folder can't be handed over for any reason the retry starts clean rather than failing to start.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex ae450889a2..1e6214e86c 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -980,16 +980,14 @@ export async function spawnTuiAgent({emitLog('warn', `Failed to mark TUI agent ${agentId} as wrapping up: ${err.message}`, { agentId });});- shellService.writeToSession(sessionId, `\x1b[200~${buildWrapUpProdMessage(MAX_RUNTIME_WRAP_UP_GRACE_MS)}\x1b[201~`);- // Submit with the same repeated-Enter helper the initial prompt uses — a- // single `\r` can be swallowed while the TUI reflows the paste, and a prod- // that never submits is a prod that never happened. Clear any prior- // submit-Enter interval first: hours after submission the prompt's own is- // long finished, but overwriting a live handle would leak it past finish().+ // Clear any prior submit-Enter interval first: hours after submission the+ // prompt's own is long finished, but overwriting a live handle would leak+ // it past finish().if (submitEnterTimer) clearInterval(submitEnterTimer);- submitEnterTimer = scheduleSubmitEnters(- () => shellService.writeToSession(sessionId, '\r'),- () => finalized,+ submitEnterTimer = shellService.pasteToSession(+ sessionId,+ buildWrapUpProdMessage(MAX_RUNTIME_WRAP_UP_GRACE_MS),+ { label: '[cosAgents] max-runtime wrap-up' },);// A single deadline, NOT a poll: the 2s doneSentinelTimer is already watchingdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex df8da1615d..2f7f62b5a3 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -6,6 +6,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';vi.mock('./shell.js', () => ({createShellSession: vi.fn(),writeToSession: vi.fn(),+ pasteToSession: vi.fn(),killSession: vi.fn(),getSession: vi.fn(),getSessionProcess: vi.fn(),@@ -1057,8 +1058,10 @@ describe('spawnTuiAgent runtime', () => {// The ceiling PRODS rather than reaping (#3167): it pastes a wrap-up message// and opens a grace window, so the agent is NOT finalized yet.expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();- expect(shellService.writeToSession).toHaveBeenCalledWith(- SESSION_ID, expect.stringContaining('you have hit your maximum runtime')+ expect(shellService.pasteToSession).toHaveBeenCalledWith(+ SESSION_ID,+ expect.stringContaining('you have hit your maximum runtime'),+ { label: '[cosAgents] max-runtime wrap-up' },);// No sentinel ever appears → the grace window expires → NOW it reaps.diff --git a/server/services/shell.js b/server/services/shell.jsindex c5ed1bc961..c3d5d22af3 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -2,6 +2,7 @@ import * as pty from 'node-pty';import os from 'os';import { v4 as uuidv4 } from '../lib/uuid.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';+import { scheduleSubmitEnters } from '../lib/tuiHandshake.js';// Store active shell sessions (persist across socket reconnects)const shellSessions = new Map();@@ -546,54 +547,35 @@ export function writeToSession(sessionId, data) {return false;}-// Gap between the bracketed paste and the Enter that submits it. Claude Code-// commits its paste buffer asynchronously, so an Enter in the same tick arrives-// before the buffer is committed and submits nothing.-const PASTE_SUBMIT_DELAY_MS = 400;-/**- * Deliver `text` to a session as a SINGLE bracketed-paste event, then submit it- * with a delayed Enter.+ * Deliver `text` to a session as a SINGLE bracketed-paste event, then submit it.** This is how you hand a message to a live agent TUI rather than to a shell:* Claude Code reads `ESC[200~…ESC[201~` as one paste, so a multi-line message* lands as one input event instead of N submits.*- * Scope: this is the ONE-SHOT form, for short payloads that don't need- * confirmation. A large paste that must be *verified* to have landed (an agent's- * initial prompt) goes through `lib/tuiHandshake.js` instead — its- * `scheduleSubmitEnters` sends repeated Enters because a single `\r` can be- * swallowed while the TUI is still reflowing a big paste, and `attemptPaste` in- * `agentTuiSpawning.js` retries against a paste-marker probe. Don't grow this- * function into that; reach for those.- *- * The return value reports that the paste was WRITTEN, deliberately not that the- * TUI submitted it — the submitting Enter is fire-and-forget. Making it awaitable- * would delay every caller's response by `PASTE_SUBMIT_DELAY_MS` to cover only the- * case where the PTY dies inside that window, which the user is already watching- * happen in the terminal (`shell:exit` paints "[Shell exited…]"). This is the same- * contract `shell:input` has for ordinary keystrokes: delivery to the PTY is what- * is promised.+ * The returned interval handle lets lifecycle-aware callers cancel pending+ * submission retries. The helper self-cancels when the session disappears or+ * after its attempt budget is spent.** @param {string} sessionId* @param {string} text - paste payload (no trailing newline; the Enter submits it)* @param {object} [opts]- * @param {string} [opts.label='paste'] - log label for the delayed-Enter failure path- * @returns {boolean} false when the session is unknown (nothing was written)+ * @param {string} [opts.label='paste'] - log label for the submit-Enter failure path+ * @returns {ReturnType<typeof setInterval>|false} false when the session is unknown*/export function pasteToSession(sessionId, text, { label = 'paste' } = {}) {if (!writeToSession(sessionId, `\x1b[200~${text}\x1b[201~`)) return false;- setTimeout(() => {+ const writeEnter = () => {try {- // writeToSession no-ops if the PTY died inside the window. try/catch still- // earns its place: a write to a live-but-broken pty can throw, and this- // runs outside the request lifecycle where that would crash the process.writeToSession(sessionId, '\r');} catch (err) {- console.error(`🐚 ${label} delayed Enter failed for ${sessionId.slice(0, 8)}: ${err.message}`);+ // Timer callbacks run outside the request lifecycle, and a write to a+ // live-but-broken PTY can throw.+ console.error(`🐚 ${label} submit Enter failed for ${sessionId.slice(0, 8)}: ${err.message}`);}- }, PASTE_SUBMIT_DELAY_MS);- return true;+ };+ return scheduleSubmitEnters(writeEnter, () => !shellSessions.has(sessionId));}/**diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex ecfe8781de..00fffedea4 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -381,21 +381,23 @@ describe('pasteToSession', () => {pty = ptyInstances[0];});- it('writes one bracketed paste, then submits with a delayed Enter', () => {- expect(shell.pasteToSession(id, 'line one\nline two')).toBe(true);+ it('writes one bracketed paste, then submits with repeated Enters', () => {+ const timer = shell.pasteToSession(id, 'line one\nline two');+ expect(timer).toBeTruthy();// The paste is a SINGLE write — a multi-line message must not become N submits.expect(pty.write).toHaveBeenCalledWith('\x1b[200~line one\nline two\x1b[201~');- expect(pty.write).not.toHaveBeenCalledWith('\r');-- vi.advanceTimersByTime(400);expect(pty.write).toHaveBeenCalledWith('\r');++ vi.advanceTimersByTime(1400);+ expect(pty.write.mock.calls.filter(([data]) => data === '\r')).toHaveLength(3);});- it('skips the delayed Enter when the session dies inside the window', () => {+ it('cancels pending Enters when the session dies', () => {shell.pasteToSession(id, 'hi');+ expect(pty.write.mock.calls.filter(([data]) => data === '\r')).toHaveLength(1);shell.killSession(id);- vi.advanceTimersByTime(400);- expect(pty.write).not.toHaveBeenCalledWith('\r');+ vi.advanceTimersByTime(1400);+ expect(pty.write.mock.calls.filter(([data]) => data === '\r')).toHaveLength(1);});it('returns false and writes nothing for a missing session', () => {