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
recover agy runs stuck on the account-eligibility banner instead of idling out
Adam Eivye76ac97a528e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b173fd04df..79c8b60351 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,8 @@- Merge follow-ups already stranded that way are revived on upgrade, so the pull requests they left open finally land. Their blocking reason was exempt from both the failed-task reaper and the automatic retry, so they would otherwise have sat blocked forever.- Task metadata that has no value is no longer written to the task file at all. Any unset field previously became the literal word "null", which every reader then saw as a real value — the same class of bug as the blocked merge follow-up above. Task files an older version already wrote are repaired on read.- Blocking a task that exists to merge a pull request now raises a notification naming that PR, so it can be landed by hand instead of going unnoticed. This covers every way a task can get blocked, not just the one fixed above.+- An Antigravity (agy) agent no longer sits doing nothing on "Verifying your account…" until it is reaped. PortOS already held such a run open for a grace window instead of killing it, but that wait could never work: the banner is agy rejecting the submission — the prompt is discarded and the composer goes back to empty and idle — so nothing was ever in flight for the wait to notice, and the window's only possible outcome was to expire. PortOS now re-sends the prompt every 20 seconds for the length of the window (which is what the banner itself asks for), so a verification that clears — the normal case, in seconds — gets the work done on the provider you picked instead of failing over.+- Fixed the reason those runs hung for their full idle timeout rather than failing over at all. PortOS decided the provider had come back if it saw agy's `esc to cancel` footer — but agy shows that same footer for its slash-command menu, so merely opening the menu in a parked session (a `/usage` check, or a glance from the Shell page) counted as recovery. That permanently disarmed both the retry and the fail-over, and the run was finally recorded as "idle with no changes". Recovery is now judged only on chrome agy paints while a request is genuinely running.- A series' pinned image backend now actually renders its comic pages and covers. The pin was saved on the series and honoured by first-pass portraits, but the comic stage sent the install-wide default as an explicit choice — which outranks any pin — so a series pinned to one backend quietly rendered every page and cover on another. The Pipeline visuals default from Settings → Image Gen now applies to these renders too, and a pin naming a backend you have since turned off falls back instead of failing the render.## Changeddiff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 7069814b77..2d62291c33 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -189,12 +189,23 @@ const IMMEDIATE_FALLBACK_SIGNALS = [// limit is equally self-resolving but resets in hours, so it stays at 0// (fail now) while this waits.//- // Why 60s: the observed handshake retries are sub-second and Google's own- // copy says "this usually takes a moment", so 60s is far past any plausible- // settle while staying under the 180s default TUI idle timeout — a genuinely- // stuck provider still fails over sooner than the idle reaper would have- // caught it, which is the whole point of an immediate signal.- graceMs: 60000,+ // ── 2026-08-12 FOLLOW-UP: the wait had to become ACTIVE ──+ // A 60s PASSIVE window never once cleared, because the banner is agy's+ // REJECTION of the submission, not a spinner over an in-flight one: agy+ // discards the prompt, empties its composer and returns to its idle footer+ // (agent-1f08178b's raw.txt; confirmed on a live session parked at the+ // banner). With nothing in flight, the generation chrome the window watches+ // for cannot appear, so its only reachable outcome was expiry — a 60s pause+ // bolted in front of the same fail-over. The window now RE-SUBMITS the+ // prompt on a cadence (createSelfClearingSignalGate#takeResubmit in+ // ../tuiHandshake.js), which is what the vendor's own "try again shortly"+ // asks for, and fails over only once those retries are exhausted.+ //+ // Why 120s: with retries every 20s that is five real attempts rather than+ // one dead wait, and it still sits under the 180s default TUI idle timeout —+ // a genuinely stuck provider fails over sooner than the idle reaper would+ // have caught it, which is the whole point of an immediate signal.+ graceMs: 120000,pattern: /We're finishing verifying your account eligibility\.\s*This usually takes a moment\. Please try again shortly\./i,// The banner sentence is distinctive, but it is not chrome-ONLY: it matches// anywhere in the stream, so an agent that merely quotes it (investigatingdiff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex ad2a679de3..5554640601 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -245,7 +245,7 @@ describe('Error Detection', () => {it('gives the eligibility banner a grace window instead of an immediate kill', () => {expect(detectImmediateFallbackSignal("We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly."- )).toMatchObject({ graceMs: 60000 });+ )).toMatchObject({ graceMs: 120000 });});// `actionable` and `graceMs` are independent axes: a usage limit is equallydiff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 1ec328674b..4f0ff96d6c 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -453,21 +453,31 @@ export function createWorkActivityTracker() {}// Chrome a TUI paints only while a model request is actually IN FLIGHT. agy-// swaps its idle composer footer (`? for shortcuts`) for `esc to cancel` and an-// animated `Generating…` for exactly as long as the request runs; Claude Code and-// Codex render their bulleted elapsed counter, so WORK_COUNTER_PATTERN's shape is-// spliced in (rather than re-spelled) to keep the two from drifting apart.+// renders an animated `Generating…` for exactly as long as the request runs;+// Claude Code and Codex render their bulleted elapsed counter, so+// WORK_COUNTER_PATTERN's shape is spliced in (rather than re-spelled) to keep the+// two from drifting apart.//-// Measured against real transcripts: the five agy runs killed on the eligibility-// banner (2026-08-07 → 2026-08-11) contain ZERO `esc to cancel` and ZERO-// `Generating`, while healthy agy runs from 2026-08-05 carry 40–48 and 55–206-// respectively — a clean separation, which is what makes this usable as the-// "did the provider recover?" verdict.+// `esc to cancel` is DELIBERATELY NOT HERE, despite being half of agy's in-flight+// footer. It is ambiguous chrome: agy paints the identical footer (down to the+// trailing `Gemini 3.6 Flash · medium` status) for its SLASH-COMMAND PALETTE,+// where it means "esc to cancel the palette". agent-03904eb1 (2026-08-12) is the+// receipt: parked on the eligibility banner, a `/usage` scrape opened the palette+// in its session, the palette footer read as "the provider recovered", and the+// gate latched — which disarms BOTH the re-submission and the fail-over, so the+// run sat at the banner until the 180s idle reaper finalized it as a bogus+// `idle-no-changes`. That is the failure this whole mechanism exists to prevent,+// and no local feature separates the two footers.+//+// Dropping it costs nothing measurable: across every agy transcript on disk, each+// healthy run carries 10–115 `Generating` hits (2026-08-02 → 08-05, n=14) while+// every stuck-on-the-banner run carries zero. `Generating` alone is the clean+// separator; `esc to cancel` only ever added false positives.export const GENERATION_ACTIVITY_PATTERN =- new RegExp(`esc to cancel|Generating\\s*[.·•…]|${WORK_COUNTER_PATTERN.source}`, 'i');+ new RegExp(`Generating\\s*[.·•…]|${WORK_COUNTER_PATTERN.source}`, 'i');// Carry-over kept across chunks so in-flight chrome split by a PTY chunk boundary-// (`esc to ` + `cancel`) still matches. The sibling trackers below each learned+// (`Generat` + `ing…`) still matches. The sibling trackers below each learned// this the hard way — see createReviewLoopTracker's docblock.//// Only needs to span the longest pattern alternative, because `observe` tests the@@ -481,13 +491,17 @@ const GENERATION_ACTIVITY_CARRY_CAP = 64;* `active` once any in-flight chrome appears, and returns true on the call that* flipped it (so a caller can react to the transition).*- * Unlike `createWorkActivityTracker` this deliberately does NOT try to be- * echo-proof, because its callers feed it a window that cannot contain the- * prompt echo: observation starts only AFTER a provider banner has armed a grace- * window, which is strictly after the paste has rendered. Within that window ANY- * sign of life is the answer we want, so a loose pattern is the correct bias — a- * false "recovered" merely falls back to the ordinary idle reaper, whereas a- * false "still stuck" throws away a run that was about to work.+ * Unlike `createWorkActivityTracker` this does not try to be echo-proof by+ * construction — the gate that owns it handles the one case where the prompt can+ * re-enter the stream (a re-submission; see SELF_CLEARING_RESUBMIT_ECHO_MS).+ *+ * It is NOT, however, a "match anything that looks alive" pattern, which is how+ * `esc to cancel` got in and then cost a run (see GENERATION_ACTIVITY_PATTERN).+ * The cost asymmetry runs the other way now that the grace window re-submits: a+ * false "still stuck" merely re-asks a provider that was about to answer, while a+ * false "recovered" latches, disarming the retry AND the fail-over and leaving+ * the run to idle-reap into a reported success it never earned. Only chrome that+ * a TUI paints EXCLUSIVELY while a request is in flight belongs here.** @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}*/@@ -512,6 +526,41 @@ export function createGenerationActivityTracker() {};}+// How often to re-submit the prompt while a self-clearing signal's grace window+// is open.+//+// A passive wait CANNOT clear agy's eligibility banner: the banner is that+// submission's REJECTION, not a progress spinner. agy discards the submitted+// prompt, empties its composer and returns to the idle `? for shortcuts` footer+// — verbatim from agent-1f08178b's raw.txt, and confirmed on a live session left+// sitting at the banner. Nothing is in flight, so the generation chrome the gate+// watches for can never appear and the window's only possible outcome is+// expiry + fail-over. Retrying is also exactly what the vendor's own copy asks+// for ("Please try again shortly"), so the window now re-pastes and re-submits+// on this cadence and only fails over once the retries are exhausted.+//+// 20s: slow enough that a re-paste can't outrun agy's own reflow + round trip+// (a submission that IS accepted paints `esc to cancel` within ~1s, which closes+// the window before the next retry is due), and fast enough to fit several+// attempts inside the grace window.+export const SELF_CLEARING_RESUBMIT_INTERVAL_MS = 20000;++// 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 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.+export const SELF_CLEARING_RESUBMIT_ECHO_MS = 3000;+/*** The wait-it-out policy for a provider signal that carries a `graceMs` (today:* agy's account-eligibility banner — see IMMEDIATE_FALLBACK_SIGNALS in@@ -519,58 +568,104 @@ export function createGenerationActivityTracker() {** Owns the whole state machine so the consumers can't drift: arm-once (a* repainting TUI re-matches constantly and must not restart the clock),- * feed-the-tracker only inside the window, disarm the moment the provider is+ * feed-the-tracker only inside the window, re-submit the prompt on a cadence+ * (see SELF_CLEARING_RESUBMIT_INTERVAL_MS — the wait is ACTIVE, because the+ * banner rejected the submission), disarm the moment the provider is* demonstrably generating again, and hand back a verdict at the deadline. Each* consumer keeps only its own timing mechanism — `agentTuiSpawning` folds the- * deadline into its existing 5s idle poll, while `tuiPromptRunner` needs a- * `setTimeout` because its idle watcher is created lazily on the first- * post-prompt chunk and may not exist yet when the banner paints.+ * deadline and the retry cadence into its existing 5s idle poll, while+ * `tuiPromptRunner` needs its own timers because its idle watcher is created+ * lazily on the first post-prompt chunk and may not exist yet when the banner+ * paints.** Usage per chunk: `gate.observe(stripped)` then, on a match,* `gate.arm(analysis, Date.now())`. `gate.armed` is the idle-suppression* predicate — a session waiting out a handshake is silent by design, and letting* an idle reaper finalize it would report a bogus success that scrapes the- * banner as the answer. `gate.takeExpired(Date.now())` returns the analysis to- * fail over with, or null while still waiting / after a recovery.+ * banner as the answer. `gate.takeResubmit(Date.now())` returns the 1-based+ * attempt number when it is time to re-send the prompt (0 otherwise), and+ * `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) => boolean,+ * observe: (strippedText: string, nowMs?: number) => boolean,+ * takeResubmit: (nowMs: number) => number,* takeExpired: (nowMs: number) => object|null,* readonly armed: boolean }}*/-export function createSelfClearingSignalGate() {- let armed = null; // { analysis, deadlineAt }+export function createSelfClearingSignalGate({ prompt = '' } = {}) {+ const echoCanFakeRecovery = typeof prompt === 'string' && GENERATION_ACTIVITY_PATTERN.test(prompt);+ let armed = null; // { analysis, deadlineAt, nextResubmitAt }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// 512-char window), so the banner keeps matching for many chunks after the// provider has recovered. Without this latch the first post-recovery chunk- // re-arms a fresh window and fails the run over 60s later — the exact bug the- // grace window exists to prevent. A genuine second banner is therefore ignored- // rather than re-waited; the provider has demonstrably worked once, and the- // idle reaper remains the backstop if it truly wedges.+ // re-arms a fresh window and fails the run over a full grace window later —+ // the exact bug the grace window exists to prevent (and it would now re-paste+ // the prompt into a working session on the way there). A genuine second banner+ // is therefore ignored rather than re-waited; the provider has demonstrably+ // worked once, and the idle reaper remains the backstop if it truly wedges.let recovered = false;return {get armed() { return armed !== null; },get recovered() { return recovered; },arm(analysis, nowMs) {if (armed || recovered || !analysis || !(analysis.graceMs > 0)) return false;- armed = { analysis, deadlineAt: nowMs + analysis.graceMs };+ armed = {+ analysis,+ deadlineAt: nowMs + analysis.graceMs,+ // First retry is one full interval out, not immediate: the banner paints+ // within a second of the submit-Enter, and re-pasting on top of a TUI+ // still settling from the rejected paste is how you get two prompts+ // concatenated in the composer.+ nextResubmitAt: nowMs + SELF_CLEARING_RESUBMIT_INTERVAL_MS,+ // Nothing has been re-pasted yet, so nothing in the stream is our echo.+ echoUntil: 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.- observe(strippedText) {- if (!armed || !activity.observe(strippedText)) return false;+ // `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.+ observe(strippedText, nowMs) {+ if (!armed) return false;+ if (echoCanFakeRecovery && typeof nowMs === 'number' && nowMs < armed.echoUntil) return false;+ if (!activity.observe(strippedText)) return false;armed = null;activity = null;recovered = true;return true;},+ // Returns the 1-based attempt number when the prompt is due to be re-sent,+ // or 0. The consumer owns the actual paste; this only owns "is it time?" so+ // both consumers keep the same cadence. Deliberately silent once the+ // provider has recovered (not armed) — and once the deadline has passed,+ // because a retry that lands after `takeExpired` would paste into a session+ // the fail-over is already tearing down.+ takeResubmit(nowMs) {+ 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;+ },// 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 gets// a deadline comparison, while a consumer whose own `setTimeout` fired fordiff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex 82e0b5803f..e9c94d3d99 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -14,6 +14,8 @@ import {createWorkActivityTracker,createGenerationActivityTracker,createSelfClearingSignalGate,+ SELF_CLEARING_RESUBMIT_INTERVAL_MS,+ SELF_CLEARING_RESUBMIT_ECHO_MS,MERGE_QUEUE_IDLE_TIMEOUT_MS,isMergeQueueSignal,createMergeQueueTracker,@@ -54,6 +56,7 @@ import {createInputReadyTracker,AGY_INPUT_READY_PATTERN,} from './tuiHandshake.js';+import { detectImmediateFallbackSignal } from './aiToolkit/errorDetection.js';import { CODEX_CONFIGURED_DEFAULT } from './providerModels.js';import { readFileSync } from 'fs';import { dirname, resolve } from 'path';@@ -253,10 +256,16 @@ describe('tuiHandshake — paste timing constants', () => {expect(tracker.active).toBe(true);});- it('createGenerationActivityTracker latches on the esc-to-cancel footer', () => {+ // `esc to cancel` is agy's in-flight footer AND its slash-command-palette+ // footer, down to the trailing status line — so it proves nothing. Verbatim+ // from agent-03904eb1, which was parked on the eligibility banner when a+ // `/usage` scrape opened the palette in its session: reading this as recovery+ // disarmed the retry and the fail-over, and the run idle-reaped into a bogus+ // `idle-no-changes`.+ it('createGenerationActivityTracker ignores the ambiguous esc-to-cancel footer', () => {const tracker = createGenerationActivityTracker();- tracker.observe('esc to cancelGemini 3.6 Flash high');- expect(tracker.active).toBe(true);+ tracker.observe(' ↑/↓ Navigate · enter Select · tab Complete\nesc to cancelGemini 3.6 Flash · medium');+ expect(tracker.active).toBe(false);});it('createGenerationActivityTracker also admits the Claude/Codex elapsed counter', () => {@@ -293,9 +302,9 @@ describe('tuiHandshake — paste timing constants', () => {// The sibling trackers each had to learn this after review found the miss.it('createGenerationActivityTracker matches chrome split across PTY chunks', () => {const tracker = createGenerationActivityTracker();- tracker.observe('esc to ');+ tracker.observe('Generat');expect(tracker.active).toBe(false);- tracker.observe('cancel');+ tracker.observe('ing…');expect(tracker.active).toBe(true);});@@ -311,7 +320,7 @@ describe('tuiHandshake — paste timing constants', () => {it('createGenerationActivityTracker matches chrome mid-way through a large chunk', () => {const tracker = createGenerationActivityTracker();- tracker.observe(`${'a'.repeat(300)}esc to cancel${'b'.repeat(300)}`);+ tracker.observe(`${'a'.repeat(300)}Generating…${'b'.repeat(300)}`);expect(tracker.active).toBe(true);});@@ -362,6 +371,24 @@ describe('tuiHandshake — paste timing constants', () => {expect(gate.takeExpired(120000)).toBeNull();});+ // Replays agent-03904eb1 (2026-08-12), the run that made this whole file's+ // fail-over unreachable: parked on the eligibility banner, a `/usage` scrape+ // opened agy's slash-command palette in its session, and the palette's+ // `esc to cancel` footer read as recovery. The gate latched, which disarms+ // BOTH the re-submission and the fail-over, so the run sat silent until the+ // idle reaper finalized it as a bogus `idle-no-changes` — the "agy hangs on+ // Verifying your account" report. Palette chrome must leave the window open.+ it('does not accept slash-command-palette chrome as recovery', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm(BANNER, 1000);+ // Verbatim shapes from that transcript, ANSI-stripped.+ expect(gate.observe('/\n> /add-dir Add a directory to the workspace', 2000)).toBe(false);+ expect(gate.observe(' ↑/↓ Navigate · enter Select · tab Complete\nesc to cancelu', 3000)).toBe(false);+ expect(gate.observe('esc to cancelGemini 3.6 Flash · medium', 4000)).toBe(false);+ expect(gate.armed).toBe(true);+ expect(gate.takeExpired(61001)).toBe(BANNER);+ });+it('does not treat pre-arm output as evidence of recovery', () => {const gate = createSelfClearingSignalGate();expect(gate.observe('Generating...')).toBe(false);@@ -396,6 +423,109 @@ describe('tuiHandshake — paste timing constants', () => {expect(gate.takeExpired(4999)).toBeNull();expect(gate.takeExpired(5000)).toMatchObject({ graceMs: 5000 });});++ // The window has to be ACTIVE: agy's banner is the REJECTION of the+ // submission (composer emptied, session back at its idle footer), so nothing+ // is in flight and no amount of waiting produces generation chrome. Without a+ // re-submission the window's only reachable outcome is expiry.+ describe('re-submission cadence', () => {+ const I = SELF_CLEARING_RESUBMIT_INTERVAL_MS;++ it('asks for a re-submission once per interval, numbering the attempts', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm(BANNER, 0);+ // Not immediately: the banner paints a second after the submit-Enter, and+ // re-pasting into a TUI still settling concatenates two prompts.+ expect(gate.takeResubmit(0)).toBe(0);+ expect(gate.takeResubmit(I - 1)).toBe(0);+ expect(gate.takeResubmit(I)).toBe(1);+ expect(gate.takeResubmit(I)).toBe(0);+ expect(gate.takeResubmit(2 * I)).toBe(2);+ });++ it('never asks before the window opens or after the provider recovered', () => {+ const gate = createSelfClearingSignalGate();+ expect(gate.takeResubmit(I)).toBe(0);+ gate.arm(BANNER, 0);+ gate.observe('Generating...', I);+ expect(gate.takeResubmit(2 * I)).toBe(0);+ });++ // A retry landing after takeExpired would paste into a session the+ // fail-over is already tearing down.+ it('stops asking at the deadline', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm(BANNER, 0);+ expect(gate.takeResubmit(BANNER.graceMs - 1)).toBe(1);+ expect(gate.takeResubmit(BANNER.graceMs)).toBe(0);+ });++ it('numbers attempts per window, not per gate', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm(BANNER, 0);+ expect(gate.takeResubmit(I)).toBe(1);+ gate.takeExpired(BANNER.graceMs);+ gate.arm(BANNER, BANNER.graceMs);+ 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 });+ gate.arm(BANNER, 0);+ gate.takeResubmit(I);+ expect(gate.observe(RISKY_PROMPT, I + 10)).toBe(false);+ expect(gate.armed).toBe(true);+ // Real chrome repaints continuously, so the next chunk past the echo+ // window still latches.+ expect(gate.observe('Generating…', I + SELF_CLEARING_RESUBMIT_ECHO_MS)).toBe(true);+ });++ it('only discounts the echo window, not everything after a re-submission', () => {+ const gate = createSelfClearingSignalGate({ prompt: RISKY_PROMPT });+ 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 });+ gate.arm(BANNER, 0);+ gate.takeResubmit(I);+ expect(gate.observe('Generating...')).toBe(true);+ });++ // Cross-file invariant between the signal that sets the window and the gate+ // that spends it. Too short and the window is back to being a pause in+ // front of a fail-over; past the idle timeout and the reaper finalizes the+ // deliberately-silent session first — as an `idle-complete` SUCCESS that+ // scrapes the banner as the answer, since agy renders no work counter.+ it("sizes agy's eligibility window for several retries, still inside the idle timeout", () => {+ const signal = detectImmediateFallbackSignal(+ "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly."+ );+ expect(signal.graceMs).toBeGreaterThanOrEqual(3 * SELF_CLEARING_RESUBMIT_INTERVAL_MS);+ expect(signal.graceMs).toBeLessThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);+ });+ });});it('pins work-activity detection constants', () => {diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 605d0f9de1..bdffa659f6 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -55,6 +55,7 @@ import {PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,scheduleSubmitEnters,+ SELF_CLEARING_RESUBMIT_INTERVAL_MS,PASTE_DEADLINE_MS,READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,@@ -327,7 +328,12 @@ ${prompt}`;// needs its OWN timer: `idleWatchTimer` is created lazily on the first// post-prompt chunk and may not exist yet when the banner paints.let selfClearingTimer = null;- const selfClearingGate = createSelfClearingSignalGate();+ // 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 cleanupTimers = () => {// Stop the post-paste accumulator from growing on any chunk that lands@@ -340,6 +346,7 @@ ${prompt}`;if (responseFileWatchTimer) { clearInterval(responseFileWatchTimer); responseFileWatchTimer = null; }if (hardTimeoutTimer) { clearTimeout(hardTimeoutTimer); hardTimeoutTimer = null; }if (selfClearingTimer) { clearTimeout(selfClearingTimer); selfClearingTimer = null; }+ if (selfClearingResubmitTimer) { clearInterval(selfClearingResubmitTimer); selfClearingResubmitTimer = null; }};return new Promise((resolve) => {@@ -489,8 +496,11 @@ ${prompt}`;// While a grace window is open, every chunk is evidence about whether the// provider came back; the gate closes itself the moment it is, which also// lifts the idle suppression below instead of holding it to the deadline.- if (selfClearingGate.observe(stripped)) {+ // 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; }console.log(`✅ TUI run ${runId} provider signal cleared — generating again`);}@@ -506,8 +516,15 @@ ${prompt}`;if (fallbackSignal?.graceMs > 0) {if (selfClearingGate.arm(fallbackSignal, Date.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+ // above, at expiry below, and by cleanupTimers on any finish.+ selfClearingResubmitTimer = setInterval(() => {+ if (finalized) return;+ resubmitAfterSignal();+ }, SELF_CLEARING_RESUBMIT_INTERVAL_MS);selfClearingTimer = setTimeout(() => {selfClearingTimer = null;+ if (selfClearingResubmitTimer) { clearInterval(selfClearingResubmitTimer); selfClearingResubmitTimer = null; }// 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.@@ -686,6 +703,35 @@ ${prompt}`;}, PASTE_MARKER_POLL_MS);};+ /**+ * Re-deliver the prompt while a self-clearing provider signal's window is+ * open. Mirrors `resubmitAfterSignal` on the long-running agent path — see+ * that copy (and SELF_CLEARING_RESUBMIT_INTERVAL_MS) for why a passive wait+ * cannot clear agy's eligibility banner: it is the REJECTION of the+ * submission, so the prompt is gone, the composer is empty, and nothing will+ * generate until something re-asks.+ */+ const resubmitAfterSignal = () => {+ // A banner during startup has nothing to re-send — the ready watch below+ // still owns first delivery.+ if (!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.+ if (submitEnterTimer) clearInterval(submitEnterTimer);+ submitEnterTimer = scheduleSubmitEnters(+ () => { try { ptyProcess.write('\r'); } catch { /* PTY may have already exited */ } },+ () => finalized+ );+ console.log(`🔁 TUI run ${runId} re-submitted its prompt while the provider handshake is open (attempt ${attempt})`);+ };+// Ready watch — paste only once the TUI banner finishes repainting AND// we've had at least promptDelayMs of runtime. Falls back to forcing// the paste after PASTE_DEADLINE_MS so a silent provider still getsdiff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex b451a7fe53..65f80fae6b 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -52,6 +52,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';const makeFakePty = () => {const fake = {@@ -812,6 +813,41 @@ describe('executeTuiRun', () => {await promise;});+ // The banner is the REJECTION of the submission — agy discards the prompt and+ // returns to an empty, idle composer — so a PASSIVE window can never see the+ // generation chrome it waits for, and its only reachable outcome is expiry.+ // Re-asking is both the only way out and what the banner itself instructs.+ it('re-submits the prompt while the eligibility window is open', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });+ const provider = { id: 'antigravity', type: 'tui', command: 'agy', tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500 };+ const prompt = 'do thing big enough to clear the prompt guard';+ const promise = executeTuiRun({ runId: 'run-eligibility-retry', provider, prompt, workspacePath: TEST_WORKSPACE, onData: undefined, onComplete: vi.fn(), timeout: 600000 });+ await flushAsync();++ const pty = ptyInstances[0];+ pty.emitData('agy ready> ');+ await vi.advanceTimersByTimeAsync(5000); // first delivery+ const pastes = () => pty.write.mock.calls.filter(([chunk]) => String(chunk).includes(prompt)).length;+ expect(pastes()).toBe(1);++ pty.emitData(ELIGIBILITY_BANNER);+ pty.emitData('> ? for shortcuts');+ await vi.advanceTimersByTimeAsync(SELF_CLEARING_RESUBMIT_INTERVAL_MS + 1000);+ await flushAsync();+ 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');+ await vi.advanceTimersByTimeAsync(3 * SELF_CLEARING_RESUBMIT_INTERVAL_MS);+ await flushAsync();+ expect(pastes()).toBe(2);++ vi.useRealTimers();+ pty.emitExit(0);+ await promise;+ });+it('falls back once the eligibility banner outlasts its grace window with no generation', async () => {vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });const provider = { id: 'antigravity', type: 'tui', command: 'agy', tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500 };@@ -824,7 +860,9 @@ describe('executeTuiRun', () => {// Only idle composer chrome repaints — no sign of life. Notably this must// NOT idle-complete as success and scrape the banner as the response.pty.emitData('> ? for shortcuts');- await vi.advanceTimersByTimeAsync(70000);+ // Past the full grace window — every re-submission inside it went+ // unanswered too, so the fail-over is the correct verdict.+ await vi.advanceTimersByTimeAsync(130000);await flushAsync();await promise;diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 7d8196cbbf..75643500d8 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -677,8 +677,10 @@ export async function spawnTuiAgent({const detectImmediateFallbackSignal = createImmediateFallbackSignalDetector();// 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 and defers to `.armed` for idle suppression.- const selfClearingGate = createSelfClearingSignalGate();+ // 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 });// 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.@@ -1116,6 +1118,40 @@ export async function spawnTuiAgent({});};+ /**+ * Re-deliver the prompt while a self-clearing provider signal's window is open.+ *+ * agy's eligibility banner is the REJECTION of a submission, not a spinner over+ * an in-flight one: the prompt is discarded, the composer goes back to empty+ * and the session sits at its idle footer indefinitely. So the window can only+ * clear if something re-asks — hence a plain re-paste + submit, which is also+ * literally what the banner instructs ("Please try again shortly").+ *+ * Re-pasting the WHOLE prompt is correct precisely because the composer is+ * empty; the gate's 20s cadence keeps this well clear of the reflow that+ * follows the rejected paste. Nothing here re-runs paste VERIFICATION: this+ * prompt already rendered once (its rejection is why we're here), and routing+ * back through `attemptPaste` would spend the startup paste-retry budget and+ * let a verification hiccup mid-handshake finalize the run as+ * `paste-not-rendered`.+ */+ 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;+ 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).+ if (submitEnterTimer) clearInterval(submitEnterTimer);+ submitEnterTimer = shellService.pasteToSession(sessionId, prompt, {+ label: '[cosAgents] provider-handshake resubmit',+ }) || null;+ appendLine(`🔁 Provider handshake still open — re-submitted the prompt (attempt ${attempt})`);+ };+const handleData = async (data) => {// EventEmitter listeners run outside the request lifecycle — a rejection// here on Node ≥15 will kill the process unless we catch locally. The@@ -1205,8 +1241,10 @@ export async function spawnTuiAgent({// binary fails fast instead of idling.//// While a grace window is open, every chunk is evidence about whether the- // provider came back; the gate closes itself the moment it is.- if (selfClearingGate.observe(stripped)) {+ // provider came back; the gate closes itself the moment it is. 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, now)) {appendLine(`✅ Provider signal cleared — ${tuiConfig.command} is generating again; continuing the run`);}@@ -1497,7 +1535,13 @@ export async function spawnTuiAgent({// idle path reports `idle-complete` SUCCESS for a run that never produced a// token. Safely bounded — the window carries its own deadline, resolved just// above, which fires strictly before any idle window it outlasts.- if (selfClearingGate.armed) return;+ //+ // The wait is ACTIVE: re-send the prompt on the gate's cadence, because the+ // banner is the provider REJECTING this submission (see resubmitAfterSignal).+ if (selfClearingGate.armed) {+ resubmitAfterSignal();+ return;+ }if (!promptSentAt) return;// Don't reap a session that just received real input — a human pasting// into the Shell page, or our own auto-paste. A big bracketed paste candiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex f33b358dc5..8d16de21e0 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -211,7 +211,7 @@ import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgentLifecycle from './cosAgentLifecycle.js';import * as gitService from './git.js';import { activeAgents, userTerminatedAgents } from './agentState.js';-import { MAX_RUNTIME_WRAP_UP_GRACE_MS } from '../lib/tuiHandshake.js';+import { MAX_RUNTIME_WRAP_UP_GRACE_MS, SELF_CLEARING_RESUBMIT_INTERVAL_MS } from '../lib/tuiHandshake.js';// Real module, not a mock: the flag is a plain process-local boolean, so driving// it directly exercises the same code path production does.import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';@@ -1444,7 +1444,10 @@ describe('spawnTuiAgent runtime', () => {// ── 1c. claude waits for bracketed-paste mode (input ready) before pasting ───const claudeTuiConfig = { command: 'claude', args: [], commandLine: 'claude', promptDelayMs: 100, idleTimeoutMs: 50 };// Antigravity (agy) gets the SAME positive input-ready gate as claude (#2705).- const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100, idleTimeoutMs: 50 };+ // maxRuntimeMs is explicit for the same reason defaultTuiConfig pins it: left+ // undefined, the wall-clock backstop is a `setTimeout(…, undefined)` that fires+ // on the next tick and prods every one of these runs to wrap up.+ const agyTuiConfig = { command: 'agy', args: [], commandLine: 'agy', promptDelayMs: 100, idleTimeoutMs: 50, maxRuntimeMs: 3600000 };const pasteCount = () => vi.mocked(shellService.writeToSession).mock.calls.filter(([, d]) => typeof d === 'string' && d.includes('\x1b[200~')).length;// The launch shell turns bracketed-paste OFF to run the command, then claude@@ -1703,6 +1706,41 @@ describe('spawnTuiAgent runtime', () => {expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();});+ // The banner is the REJECTION of the submission — agy discards the prompt and+ // drops back to an empty, idle composer (agent-1f08178b's raw.txt, and a live+ // session confirmed parked there). Nothing is in flight, so a PASSIVE window+ // can never see the generation chrome it waits for: its only reachable outcome+ // is expiry, making it a pause bolted in front of the same fail-over. Re-asking+ // is the only way out, and what the banner itself instructs.+ it('re-submits the prompt while the eligibility window is open, and stops once agy answers', async () => {+ await driveAgyToSubmittedPrompt();++ await capturedOnData(Buffer.from(ELIGIBILITY_BANNER));+ await capturedOnData(Buffer.from('> ? for shortcuts'));+ await flushMicrotasks();+ expect(shellService.pasteToSession).not.toHaveBeenCalled();++ await vi.advanceTimersByTimeAsync(SELF_CLEARING_RESUBMIT_INTERVAL_MS + 5000);+ await flushMicrotasks();+ expect(shellService.pasteToSession).toHaveBeenCalledWith(+ SESSION_ID,+ 'do the thing',+ expect.objectContaining({ label: expect.stringContaining('handshake') }),+ );++ // The retry lands: agy paints its in-flight chrome, which closes the window+ // and must stop the re-asking too.+ await capturedOnData(Buffer.from('Generating...\nesc to cancel'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(3 * SELF_CLEARING_RESUBMIT_INTERVAL_MS);+ await flushMicrotasks();+ expect(shellService.pasteToSession).toHaveBeenCalledTimes(1);+ // The run belongs to the ordinary reaper again, not to the fail-over.+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalledWith(+ expect.objectContaining({ completionReason: 'fallback-signal' })+ );+ });+it('resumes the run when the eligibility banner clears and agy starts generating', async () => {await driveAgyToSubmittedPrompt();@@ -1734,7 +1772,9 @@ describe('spawnTuiAgent runtime', () => {await capturedOnData(Buffer.from('> ? for shortcuts'));await flushMicrotasks();- await vi.advanceTimersByTimeAsync(70000);+ // Past the full grace window — every re-submission inside it went unanswered+ // too, so the fail-over is the correct verdict.+ await vi.advanceTimersByTimeAsync(130000);vi.useRealTimers();await completeDone;