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
address review: reuse pasteToSession for the handshake retry and drop the gate's prompt coupling
Adam Eivy9d95f52f4eeb
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 4f0ff96d6c..707d44e92d 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -545,20 +545,32 @@ export function createGenerationActivityTracker() {// attempts inside the grace window.export const SELF_CLEARING_RESUBMIT_INTERVAL_MS = 20000;+// How often a consumer without its own poll should ASK the gate whether a+// re-submission is due. Deliberately a sub-multiple of the interval above rather+// than equal to it: a timer whose period matches the cadence exactly can tick a+// hair early (timer rounding vs. `Date.now()`, or an event-loop stall shifting+// phase), `takeResubmit` refuses, and that attempt is silently forfeited for a+// whole interval. Polling faster than the cadence leaves the gate the single+// authority on timing — the same shape the agent path gets for free by folding+// the question into its existing 5s idle poll.+export const SELF_CLEARING_RESUBMIT_POLL_MS = 5000;+// How long after a re-submission the gate ignores output when deciding whether-// the provider recovered — applied ONLY to a prompt that could fake a recovery-// (see the `prompt` option on createSelfClearingSignalGate).+// the provider recovered.+//+// The generation tracker matches a single chunk, which is safe only while the+// stream cannot contain the prompt. Re-pasting breaks that: a prompt quoting+// `Generating…` (a task about this very failure mode does) echoes straight into+// the tracker and latches a bogus recovery — strictly worse than the expiry it+// replaced, because a recovered gate neither retries nor fails over, leaving the+// run to idle-reap into a false success. 3s covers the paste and its spaced+// submit-Enters (~1.4s).//-// The generation tracker is deliberately loose ("any sign of life"), which is-// safe only because it is normally fed a window that CANNOT contain the prompt-// echo. Re-pasting inside the window breaks that: a prompt quoting `esc to-// cancel` or `Generating…` (a task about this very failure mode does) would echo-// straight into the tracker and latch a bogus recovery — strictly worse than the-// expiry it replaced, because a recovered gate neither retries nor fails over,-// leaving the run to idle-reap into a false success. 3s covers the paste and its-// spaced submit-Enters (~1.4s); a provider that genuinely accepted the retry-// repaints its in-flight chrome continuously (40–48 times in a healthy agy run),-// so the next chunk past the window still latches.+// Applied to every re-submission rather than only to prompts whose text could+// actually match: conditioning on that made the gate's behavior depend on a+// content coincidence in the caller's payload, and the thing it bought — up to+// 3s of recovery latency on a 20s retry cadence, against chrome that repaints+// continuously — is not worth the coupling.export const SELF_CLEARING_RESUBMIT_ECHO_MS = 3000;/**@@ -587,24 +599,15 @@ export const SELF_CLEARING_RESUBMIT_ECHO_MS = 3000;* `gate.takeExpired(Date.now())` returns the analysis to fail over with, or null* while still waiting / after a recovery.*- * @param {object} [opts]- * @param {string} [opts.prompt] - the text this run re-pastes. Only a prompt- * that itself contains in-flight chrome can fake a recovery once it echoes- * back, so the echo window is armed only for those; every other prompt echoes- * inertly and suppressing its window would just delay a real recovery.* @returns {{ arm: (analysis: object, nowMs: number) => boolean,- * observe: (strippedText: string, nowMs?: number) => boolean,+ * observe: (strippedText: string, nowMs: number) => boolean,* takeResubmit: (nowMs: number) => number,* takeExpired: (nowMs: number) => object|null,* readonly armed: boolean }}*/-export function createSelfClearingSignalGate({ prompt = '' } = {}) {- const echoCanFakeRecovery = typeof prompt === 'string' && GENERATION_ACTIVITY_PATTERN.test(prompt);- let armed = null; // { analysis, deadlineAt, nextResubmitAt }+export function createSelfClearingSignalGate() {+ let armed = null; // { analysis, deadlineAt, nextResubmitAt, echoUntil, resubmits }let activity = null;- // 1-based count of re-submissions made inside the CURRENT window (reset by- // arm), used only to label the attempt in the consumers' logs.- let resubmits = 0;// Latched once a window is ridden out successfully, which suppresses re-arming// for the rest of the run. This is not just tidiness: the caller's detector is// a BUFFERED stream matcher (createImmediateFallbackSignalDetector keeps a@@ -631,22 +634,21 @@ export function createSelfClearingSignalGate({ prompt = '' } = {}) {nextResubmitAt: nowMs + SELF_CLEARING_RESUBMIT_INTERVAL_MS,// Nothing has been re-pasted yet, so nothing in the stream is our echo.echoUntil: 0,+ // 1-based count of re-submissions made inside THIS window, used only to+ // label the attempt in the consumers' logs. Lives on `armed` so its+ // per-window lifetime is structural rather than a reset to remember.+ resubmits: 0,};activity = createGenerationActivityTracker();- resubmits = 0;return true;},// Returns true on the call that ends the window because the provider came// back — disarming here (rather than at the deadline) is what stops a// recovered run from sitting under idle suppression for the rest of the- // window.- // `nowMs` is optional but every live consumer passes it: without a clock- // there is no way to tell our own re-pasted prompt from the provider's- // output, so the echo window (SELF_CLEARING_RESUBMIT_ECHO_MS) can't be- // applied and a chrome-quoting prompt can fake a recovery.+ // window. `nowMs` is required: without a clock there is no way to tell our+ // own re-pasted prompt from the provider's output.observe(strippedText, nowMs) {- if (!armed) return false;- if (echoCanFakeRecovery && typeof nowMs === 'number' && nowMs < armed.echoUntil) return false;+ if (!armed || nowMs < armed.echoUntil) return false;if (!activity.observe(strippedText)) return false;armed = null;activity = null;@@ -663,8 +665,8 @@ export function createSelfClearingSignalGate({ prompt = '' } = {}) {if (!armed || nowMs < armed.nextResubmitAt || nowMs >= armed.deadlineAt) return 0;armed.nextResubmitAt = nowMs + SELF_CLEARING_RESUBMIT_INTERVAL_MS;armed.echoUntil = nowMs + SELF_CLEARING_RESUBMIT_ECHO_MS;- resubmits += 1;- return resubmits;+ armed.resubmits += 1;+ return armed.resubmits;},// Returns the analysis to fail over with, or null while still waiting (or// after a recovery). `nowMs` is OPTIONAL: a poller passes the clock and getsdiff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex e9c94d3d99..611ed3a908 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -353,7 +353,7 @@ describe('tuiHandshake — paste timing constants', () => {it('closes on the first sign of generation instead of holding to the deadline', () => {const gate = createSelfClearingSignalGate();gate.arm(BANNER, 1000);- expect(gate.observe('Generating...')).toBe(true);+ expect(gate.observe('Generating...', 2000)).toBe(true);expect(gate.armed).toBe(false);// Nothing left to fail over with — the run continues.expect(gate.takeExpired(61000)).toBeNull();@@ -365,7 +365,7 @@ describe('tuiHandshake — paste timing constants', () => {it('does not re-arm on a stale banner match after the provider recovered', () => {const gate = createSelfClearingSignalGate();gate.arm(BANNER, 1000);- gate.observe('Generating...');+ gate.observe('Generating...', 2000);expect(gate.recovered).toBe(true);expect(gate.arm(BANNER, 2000)).toBe(false);expect(gate.takeExpired(120000)).toBeNull();@@ -391,10 +391,10 @@ describe('tuiHandshake — paste timing constants', () => {it('does not treat pre-arm output as evidence of recovery', () => {const gate = createSelfClearingSignalGate();- expect(gate.observe('Generating...')).toBe(false);+ expect(gate.observe('Generating...', 500)).toBe(false);gate.arm(BANNER, 1000);// Only the banner screen repaints from here — still stuck.- gate.observe('> ? for shortcuts');+ gate.observe('> ? for shortcuts', 2000);expect(gate.takeExpired(61001)).toBe(BANNER);});@@ -413,7 +413,7 @@ describe('tuiHandshake — paste timing constants', () => {it('force-expiry still returns null once the provider recovered', () => {const gate = createSelfClearingSignalGate();gate.arm(BANNER, 1000);- gate.observe('Generating...');+ gate.observe('Generating...', 2000);expect(gate.takeExpired()).toBeNull();});@@ -469,19 +469,16 @@ describe('tuiHandshake — paste timing constants', () => {expect(gate.takeResubmit(BANNER.graceMs + I)).toBe(1);});- // The generation tracker is deliberately loose, which is only safe while it- // can't see the prompt. Re-pasting puts the prompt back in the stream, so a- // task whose text quotes in-flight chrome (a task about THIS failure mode- // does) would latch a bogus recovery — worse than expiring, because a- // recovered gate neither retries nor fails over and the run idle-reaps into- // a false success.- const RISKY_PROMPT = 'Investigate why the TUI shows `Generating…` forever';-- it('discounts the echo of a chrome-quoting prompt it just re-pasted', () => {- const gate = createSelfClearingSignalGate({ prompt: RISKY_PROMPT });+ // The tracker matches a single chunk, which is only safe while the stream+ // can't contain the prompt. Re-pasting puts it back, so a task whose text+ // quotes in-flight chrome (a task about THIS failure mode does) would latch+ // a bogus recovery — worse than expiring, because a recovered gate neither+ // retries nor fails over and the run idle-reaps into a false success.+ it('discounts the echo of the prompt it just re-pasted', () => {+ const gate = createSelfClearingSignalGate();gate.arm(BANNER, 0);gate.takeResubmit(I);- expect(gate.observe(RISKY_PROMPT, I + 10)).toBe(false);+ expect(gate.observe('Investigate why the TUI shows `Generating…` forever', I + 10)).toBe(false);expect(gate.armed).toBe(true);// Real chrome repaints continuously, so the next chunk past the echo// window still latches.@@ -489,28 +486,18 @@ describe('tuiHandshake — paste timing constants', () => {});it('only discounts the echo window, not everything after a re-submission', () => {- const gate = createSelfClearingSignalGate({ prompt: RISKY_PROMPT });+ const gate = createSelfClearingSignalGate();gate.arm(BANNER, 0);gate.takeResubmit(I);expect(gate.observe('Generating...', I + SELF_CLEARING_RESUBMIT_ECHO_MS + 1)).toBe(true);});- // Suppression costs recovery latency, so it is scoped to the prompts that- // can actually cause the problem. An ordinary prompt echoes inertly — the- // provider's first sign of life still counts immediately, even if it lands- // in the same instant as the re-paste.- it('does not delay recovery for a prompt whose echo cannot fake one', () => {- const gate = createSelfClearingSignalGate({ prompt: 'update the documentation' });- gate.arm(BANNER, 0);- gate.takeResubmit(I);- expect(gate.observe('Generating...', I + 10)).toBe(true);- });-- it('keeps the clockless observe form working for callers that have no clock', () => {- const gate = createSelfClearingSignalGate({ prompt: RISKY_PROMPT });+ // Nothing has been re-pasted before the first attempt, so nothing in the+ // stream is our echo and a recovery counts immediately.+ it('does not suppress anything before the first re-submission', () => {+ const gate = createSelfClearingSignalGate();gate.arm(BANNER, 0);- gate.takeResubmit(I);- expect(gate.observe('Generating...')).toBe(true);+ expect(gate.observe('Generating...', 10)).toBe(true);});// Cross-file invariant between the signal that sets the window and the gatediff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex bdffa659f6..27dbf0d1fc 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -46,7 +46,7 @@ import {createTerminalRequestTimeoutDetector,} from './aiToolkit/errorDetection.js';import { getRunsPath, finalizeRunRecord, emitRunStarted, registerActiveRun, unregisterActiveRun, consumeRunStopRequested, resolveRunCwd } from '../services/runner.js';-import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached } from '../services/shell.js';+import { registerExternalSession, unregisterExternalSession, isExternalSessionAttached, pasteToSession } from '../services/shell.js';import { isHostShuttingDown } from './hostShutdown.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,@@ -55,7 +55,7 @@ import {PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,scheduleSubmitEnters,- SELF_CLEARING_RESUBMIT_INTERVAL_MS,+ SELF_CLEARING_RESUBMIT_POLL_MS,PASTE_DEADLINE_MS,READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,@@ -331,9 +331,13 @@ ${prompt}`;// Re-sends the prompt on a cadence while that window is open (the banner is a// REJECTION, not a spinner — see resubmitAfterSignal).let selfClearingResubmitTimer = null;- // The prompt is handed over so the gate can discount its own echo when- // re-pasting a prompt whose TEXT could fake a recovery.- const selfClearingGate = createSelfClearingSignalGate({ prompt: wrappedPrompt });+ const selfClearingGate = createSelfClearingSignalGate();+ // The deadline and its retry poll are armed together and always die together —+ // on recovery, at expiry, and on any finish.+ const stopSelfClearingTimers = () => {+ if (selfClearingTimer) { clearTimeout(selfClearingTimer); selfClearingTimer = null; }+ if (selfClearingResubmitTimer) { clearInterval(selfClearingResubmitTimer); selfClearingResubmitTimer = null; }+ };const cleanupTimers = () => {// Stop the post-paste accumulator from growing on any chunk that lands@@ -345,8 +349,7 @@ ${prompt}`;if (idleWatchTimer) { clearInterval(idleWatchTimer); idleWatchTimer = null; }if (responseFileWatchTimer) { clearInterval(responseFileWatchTimer); responseFileWatchTimer = null; }if (hardTimeoutTimer) { clearTimeout(hardTimeoutTimer); hardTimeoutTimer = null; }- if (selfClearingTimer) { clearTimeout(selfClearingTimer); selfClearingTimer = null; }- if (selfClearingResubmitTimer) { clearInterval(selfClearingResubmitTimer); selfClearingResubmitTimer = null; }+ stopSelfClearingTimers();};return new Promise((resolve) => {@@ -476,6 +479,10 @@ ${prompt}`;};ptyProcess.onData((data) => {+ // One clock reading for the whole chunk — the grace-window bookkeeping+ // below and the idle/response timestamps at the end all want the same+ // instant, and this runs on every PTY chunk of every run.+ const now = Date.now();const text = data.toString();rawBuffer += text;if (rawBuffer.length > RAW_BUFFER_HEADROOM) rawBuffer = rawBuffer.slice(-RAW_BUFFER_CAP);@@ -498,9 +505,8 @@ ${prompt}`;// lifts the idle suppression below instead of holding it to the deadline.// The clock is load-bearing — it lets the gate discount the echo of a// prompt IT just re-pasted (see SELF_CLEARING_RESUBMIT_ECHO_MS).- if (selfClearingGate.observe(stripped, Date.now())) {- if (selfClearingTimer) { clearTimeout(selfClearingTimer); selfClearingTimer = null; }- if (selfClearingResubmitTimer) { clearInterval(selfClearingResubmitTimer); selfClearingResubmitTimer = null; }+ if (selfClearingGate.observe(stripped, now)) {+ stopSelfClearingTimers();console.log(`✅ TUI run ${runId} provider signal cleared — generating again`);}@@ -514,17 +520,16 @@ ${prompt}`;// gate closed. A graceful signal can only ever arm a window (or be// ignored, when one is already open or the provider already recovered).if (fallbackSignal?.graceMs > 0) {- if (selfClearingGate.arm(fallbackSignal, Date.now())) {+ if (selfClearingGate.arm(fallbackSignal, now)) {console.log(`⏳ TUI run ${runId} holding for a self-clearing provider signal (${Math.round(fallbackSignal.graceMs / 1000)}s): ${fallbackSignal.message}`);- // The wait is ACTIVE — see resubmitAfterSignal. Cleared on recovery+ // The wait is ACTIVE — see resubmitAfterSignal. This only ASKS on a+ // sub-multiple of the cadence; the gate decides when an attempt is+ // actually due (SELF_CLEARING_RESUBMIT_POLL_MS). Stopped on recovery// above, at expiry below, and by cleanupTimers on any finish.- selfClearingResubmitTimer = setInterval(() => {- if (finalized) return;- resubmitAfterSignal();- }, SELF_CLEARING_RESUBMIT_INTERVAL_MS);+ selfClearingResubmitTimer = setInterval(resubmitAfterSignal, SELF_CLEARING_RESUBMIT_POLL_MS);selfClearingTimer = setTimeout(() => {selfClearingTimer = null;- if (selfClearingResubmitTimer) { clearInterval(selfClearingResubmitTimer); selfClearingResubmitTimer = null; }+ stopSelfClearingTimers();// No clock argument: this timer IS this window's deadline, and it// is one-shot — a deadline re-check that came up a millisecond// short would strand the gate armed with nothing left to retry it.@@ -546,7 +551,6 @@ ${prompt}`;}}- const now = Date.now();lastOutputAt = now;if (firstOutputAt === null) firstOutputAt = now;if (promptSentAt && firstResponseAt === null && now > promptSentAt) {@@ -714,21 +718,17 @@ ${prompt}`;const resubmitAfterSignal = () => {// A banner during startup has nothing to re-send — the ready watch below// still owns first delivery.- if (!promptSentAt) return;+ if (finalized || !promptSentAt) return;const attempt = selfClearingGate.takeResubmit(Date.now());if (!attempt) return;- try {- ptyProcess.write(`\x1b[200~${wrappedPrompt}\x1b[201~`);- } catch {- return; // PTY already gone; the deadline timer still owns the fail-over- }// Overwriting a live handle would leak the previous attempt's Enter- // interval past cleanupTimers.+ // interval past cleanupTimers. `pasteToSession` returns false once the PTY+ // has been unregistered, which is also the "don't bother" answer here —+ // the deadline timer still owns the fail-over.if (submitEnterTimer) clearInterval(submitEnterTimer);- submitEnterTimer = scheduleSubmitEnters(- () => { try { ptyProcess.write('\r'); } catch { /* PTY may have already exited */ } },- () => finalized- );+ submitEnterTimer = pasteToSession(runId, wrappedPrompt, {+ label: `[tuiRun ${runId}] provider-handshake resubmit`,+ }) || null;console.log(`🔁 TUI run ${runId} re-submitted its prompt while the provider handshake is open (attempt ${attempt})`);};diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 65f80fae6b..2f47a96d75 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -38,6 +38,17 @@ const { ptyInstances, ptySpawnMock, runnerMocks, shellMocks, runsTmpDirRef } = vregisterExternalSession: vi.fn(),unregisterExternalSession: vi.fn(),isExternalSessionAttached: vi.fn(() => false),+ // The run registers its own PTY as an external session, so a paste routed+ // through the session registry lands back on that PTY. Modelled faithfully+ // (bracketed paste, then the submit Enter, then an interval handle for the+ // caller to cancel) so assertions can read pty.write like the direct path.+ pasteToSession: vi.fn((_sessionId, text) => {+ const pty = ptyInstances[ptyInstances.length - 1];+ if (!pty) return false;+ pty.write(`\x1b[200~${text}\x1b[201~`);+ pty.write('\r');+ return setInterval(() => {}, 60000);+ }),},}));runnerMocks.getRunsPath.mockImplementation(() => runsTmpDirRef.current);@@ -52,7 +63,7 @@ vi.mock('./fileUtils.js', async () => {import { cleanTuiResponse, resolveTuiResponseText, executeTuiRun } from './tuiPromptRunner.js';import { markHostShuttingDown, resetHostShutdownFlagForTests } from './hostShutdown.js';-import { SELF_CLEARING_RESUBMIT_INTERVAL_MS } from './tuiHandshake.js';+import { SELF_CLEARING_RESUBMIT_INTERVAL_MS, SELF_CLEARING_RESUBMIT_ECHO_MS } from './tuiHandshake.js';const makeFakePty = () => {const fake = {@@ -837,8 +848,13 @@ describe('executeTuiRun', () => {expect(pastes()).toBe(2);expect(pty.write).toHaveBeenCalledWith('\r');- // …and it stops re-asking the moment agy actually answers.- pty.emitData('Generating...\nesc to cancel');+ // …and it stops re-asking the moment agy actually answers. The first+ // repaint lands inside the echo window and is discounted (it could be the+ // prompt we just pasted echoing back); agy repaints continuously, so the+ // next one is what closes the window.+ pty.emitData('Generating...');+ await vi.advanceTimersByTimeAsync(SELF_CLEARING_RESUBMIT_ECHO_MS);+ pty.emitData('Generating...');await vi.advanceTimersByTimeAsync(3 * SELF_CLEARING_RESUBMIT_INTERVAL_MS);await flushAsync();expect(pastes()).toBe(2);diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 75643500d8..9e01ee6b6b 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -678,9 +678,8 @@ export async function spawnTuiAgent({// Holds the wait-it-out window for a provider signal carrying a `graceMs`// (agy's account-eligibility banner). The idle timer below both resolves its// deadline, drives the re-submission cadence, and defers to `.armed` for idle- // suppression. The prompt is handed over so the gate can discount its own echo- // when re-pasting a prompt whose TEXT could fake a recovery.- const selfClearingGate = createSelfClearingSignalGate({ prompt });+ // suppression.+ const selfClearingGate = createSelfClearingSignalGate();// Guards ingestDoneSentinel to a single read. finish() is its only caller and// is itself guarded by `finalized`, so this is defensive — it pins the// read-at-most-once invariant at the helper.@@ -1138,13 +1137,13 @@ export async function spawnTuiAgent({const resubmitAfterSignal = () => {// A banner that paints during startup (before the prompt was ever submitted)// has nothing to re-send — the ordinary paste path still owns first delivery.- if (finalized || !promptSubmittedAt) return;- if (!sessionId || !shellService.getSession(sessionId)) return;+ if (finalized || !promptSubmittedAt || !sessionId) return;const attempt = selfClearingGate.takeResubmit(Date.now());if (!attempt) return;// Overwriting a live handle would leak the previous attempt's Enter interval- // past finish(); pasteToSession returns a fresh one (or false on a session- // that vanished between the check above and the write).+ // past finish(); pasteToSession returns a fresh one, or false once the+ // session is gone — which is also the "don't bother" answer, since the+ // deadline still owns the fail-over.if (submitEnterTimer) clearInterval(submitEnterTimer);submitEnterTimer = shellService.pasteToSession(sessionId, prompt, {label: '[cosAgents] provider-handshake resubmit',