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
hold agy runs through the account-eligibility handshake instead of killing them on sight
[._.]/ Adam Eivyb3c7851d4be4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6cab3a0f8c..221816316e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,3 +20,4 @@- **A provider outage no longer hands a CoS task's model pin to a provider that can't run it.** A task pinned to Antigravity with `gemini-3.6-flash` hit an auth outage on that provider; the fallback chain correctly swapped it onto the Claude CLI but carried the Antigravity model id along, so every retry spawned `claude --model gemini-3.6-flash` and died in ~1.5s ("There's an issue with the selected model") until the task exhausted its retries and blocked. The pass-through exemption that let it through is deliberate — it exists so an explicit pin isn't silently downgraded to the provider's heaviest default just because the provider's `models` list spells an alias differently — but it only makes sense on the provider the pin was chosen *for*. A `metadata.model` pin is provider-scoped (the task form picks a provider, then a model from that provider's catalog), so a fallback swap now drops it back to the new provider's own default unless that provider actually lists it, logging the substitution rather than doing it silently. A swap between siblings that both serve the pinned id (claude-code ↔ claude-code-tui) still keeps it, and a run with no swap at all is untouched. The check also covers a fallback provider that enumerates no models, which the existing model-list validation could not inspect at all.- **The Claude CLI's own model rejection is now a recognized, actionable failure.** "There's an issue with the selected model (…)" is printed by the CLI at startup, before any API call, so it carries no `API Error: 4NN` token and matched none of the model-error patterns. It landed in the `unknown` bucket with "Error did not match known patterns" — which autoFixer maps to Tier 4 (escalate), so a task with a bad model id burned all three retries against an id that could never work and then spent an agent run on an investigation task. It now classifies as `model-not-found` with the rejected id extracted from the message, putting it in Tier 1 (config/env) where a model correction belongs. Promoted to a structured `provider`-origin signal, since the full banner with the parenthesised id and the `--model` hint is CLI text rather than something a task's own output prints in passing.- **Stopping the CoS Runner no longer burns through queued agent tasks.** `portos-cos` is a separate PM2 app you can stop from the Apps page, and while runner mode is active it owns every agent process — but the spawn path dispatched into it regardless and recorded the resulting rejection as a task failure. The CLI arm charged a retry each time (a runner left off overnight walked every queued task through its retry budget and into `blocked`), and the TUI arm reported an *actionable* spawn error, parking the task for a human over an app you had simply turned off. Tasks now hold instead, gated in two places: the queue stops dequeuing entirely while the runner is down — before the priority tiers drain on-demand requests, advance review cooldowns, or bind an app's "in review" marker — and dispatch itself holds anything that still reaches it, releasing that marker and freeing the scheduler's spawn reservation so an autonomous job re-registers instead of sitting wedged for five minutes. A held task keeps its exact queued record: pending, unclaimed, no agent, no retry charged. It spawns for real the moment the runner is back, because the runner socket's reconnect re-runs the dequeue. That reconnect is also now unbounded: the socket gave up after ten attempts (~10 seconds), so a runner that came back a minute later left the server connected to nothing while still routing every spawn at it. Backoff is capped at 10s and the resulting dequeue is debounced, so neither a long outage nor a crash-looping runner is expensive. You get one log line when the runner drops and one when it returns, not one per task. "Run now" is never held — it answers with the real reason (runner unreachable, or the daemon stopped, which was never checked at all) instead of toasting "Spawning" at a task that would sit pending.+- **The Antigravity account-eligibility banner no longer kills an agy run before it can start.** "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly." is the front of agy's sign-in handshake, not its verdict — the CLI's own log shows the session authenticating fine (OAuth succeeds, the keyring token refreshes for another hour) and then retrying `loadCodeAssist` while the composer shows that notice. PortOS was treating the banner as an immediate fatal signal and killing the terminal 0.85–1.5s after the prompt was pasted, so the model was never asked for a token. Every agy CoS agent run from 2026-08-07 onward died this way in 3–5s, while the same account and model answered instantly over `--print` and over a PTY whose eligibility was already warm. The signal is now marked self-clearing: both TUI paths hold the session for up to 60s and let the run continue the moment agy starts generating, and only fail over to a fallback provider if the banner outlasts that window with no sign of life. The grace window also suppresses the idle reaper while it's armed, so a waiting run can't be finalized as a bogus `idle-complete` success that scrapes the banner as its answer. Other fallback signals (usage limits, rejected model ids) still fail immediately.diff --git a/server/lib/aiToolkit/errorDetection.js b/server/lib/aiToolkit/errorDetection.jsindex 226c9c6610..26958d89e6 100644--- a/server/lib/aiToolkit/errorDetection.js+++ b/server/lib/aiToolkit/errorDetection.js@@ -135,10 +135,10 @@ const TUI_GUTTER_PREFIX = '^(?:[\\s│┃╎⎿⏺●•]|\\[stderr\\])*';const IMMEDIATE_FALLBACK_SIGNALS = [{// Antigravity leaves its composer visible while Google verifies account- // eligibility, so a CoS TUI agent can appear ready, accept a paste, then- // do no work until the idle reaper eventually kills it. This exact two-line- // banner is provider chrome (not a generic auth word an agent may print),- // making it safe to fail immediately and let the task select a fallback.+ // eligibility, so a CoS agent can appear ready, accept a paste, then do no+ // work until the idle reaper eventually kills it. This exact two-line banner+ // is provider chrome (not a generic auth word an agent may print), so it is+ // safe to act on and let the task select a fallback.//// NOT actionable: the account is fine and nothing in PortOS config is wrong// — Google is mid-verification and says so ("try again shortly"). Marking it@@ -148,6 +148,30 @@ const IMMEDIATE_FALLBACK_SIGNALS = [// sidelines the provider for the auth-error cooldown (providerCooldown.js)// so that retry resolves onto a fallback rather than re-dying on the same// banner three seconds later.+ //+ // ── CANONICAL ACCOUNT of the 2026-08-11 incident (other sites point here) ──+ // `graceMs` exists because killing on sight was wrong: this banner is the+ // FRONT of agy's eligibility handshake, not its verdict. agy's own CLI log+ // shows the run authenticating fine (`OAuth: authenticated successfully`,+ // keyring token refreshed for another hour) and then retrying+ // `v1internal:loadCodeAssist` while the composer shows this notice. PortOS+ // killed the session 0.85–1.5s after the paste, so `streamGenerateContent`+ // was NEVER reached. Every agy CoS run from 2026-08-07 on died this way+ // (5/5, each in 3–5s), while the same account + model answered instantly+ // over `--print` and over a PTY whose eligibility was already warm.+ //+ // Two INDEPENDENT axes, easy to conflate — a signal sets each on its own:+ // • `actionable` — must a HUMAN do something? (bad key ⇒ yes; this ⇒ no)+ // • `graceMs` — can a LIVE session profitably wait it out? A usage+ // 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,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 (investigating@@ -427,6 +451,12 @@ export function detectImmediateFallbackSignal(text, { lineStartTrusted = true }// Signals are actionable-by-default (a human has to do something); a// signal opts out when the provider says the condition clears on its own.actionable: signal.actionable !== false,+ // How long a consumer holding a LIVE session should hold it open for this+ // condition to clear before failing over. 0 (the default) = fail now, which+ // is every signal except a transient provider handshake. Always a number so+ // consumers branch on `> 0` without an `undefined` check. See the+ // account-eligibility entry for why this is a duration and not a boolean.+ graceMs: Number.isFinite(signal.graceMs) && signal.graceMs > 0 ? signal.graceMs : 0,suggestedFix: signal.suggestedFix,// Provider CHROME benches the provider host-side; text the agent itself// could have printed must not (#3631). See resolveSignalOrigin.diff --git a/server/lib/aiToolkit/errorDetection.test.js b/server/lib/aiToolkit/errorDetection.test.jsindex 597b578ceb..687b0810a4 100644--- a/server/lib/aiToolkit/errorDetection.test.js+++ b/server/lib/aiToolkit/errorDetection.test.js@@ -238,6 +238,21 @@ describe('Error Detection', () => {});});+ // The banner is the FRONT of agy's eligibility handshake, not its verdict —+ // a consumer holding a live session must wait it out rather than kill on+ // sight (see the signal's canonical comment for the 5/5 run-loss incident).+ 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 });+ });++ // `actionable` and `graceMs` are independent axes: a usage limit is equally+ // self-resolving, but it resets in hours — no live session can wait it out.+ it('leaves other signals at graceMs 0 so they still fail immediately', () => {+ expect(detectImmediateFallbackSignal('Now using extra usage\n')).toMatchObject({ graceMs: 0 });+ });+it('detects the Claude extra-usage status line', () => {const result = detectImmediateFallbackSignal('Now using extra usage');expect(result).toMatchObject({diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 22ec3bf07e..1b05c127f5 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -452,6 +452,125 @@ 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.+//+// 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.+export const GENERATION_ACTIVITY_PATTERN =+ new RegExp(`esc to cancel|Generating\\s*[.·•…]|${WORK_COUNTER_PATTERN.source}`, 'i');++// Rolling tail kept across chunks so in-flight chrome split by a PTY chunk+// boundary (`esc to ` + `cancel`) still matches. The sibling trackers below each+// learned this the hard way — see createReviewLoopTracker's docblock.+const GENERATION_ACTIVITY_TAIL_CAP = 64;++/**+ * Stateful latch for "the TUI is actively generating a response". Feed it each+ * ANSI-stripped chunk via `observe(strippedText)`; it becomes (and stays)+ * `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.+ *+ * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}+ */+export function createGenerationActivityTracker() {+ let active = false;+ let tail = '';+ return {+ observe(strippedText) {+ if (active) return true;+ if (typeof strippedText !== 'string' || !strippedText) return false;+ tail = (tail + strippedText).slice(-GENERATION_ACTIVITY_TAIL_CAP);+ if (GENERATION_ACTIVITY_PATTERN.test(tail)) active = true;+ return active;+ },+ get active() { return active; },+ };+}++/**+ * The wait-it-out policy for a provider signal that carries a `graceMs` (today:+ * agy's account-eligibility banner — see IMMEDIATE_FALLBACK_SIGNALS in+ * aiToolkit/errorDetection.js for the canonical account of why it exists).+ *+ * 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+ * 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.+ *+ * 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.+ *+ * @returns {{ arm: (analysis: object, nowMs: number) => boolean,+ * observe: (strippedText: string) => boolean,+ * takeExpired: (nowMs: number) => object|null,+ * readonly armed: boolean }}+ */+export function createSelfClearingSignalGate() {+ let armed = null; // { analysis, deadlineAt }+ let activity = null;+ // 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.+ 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 };+ activity = createGenerationActivityTracker();+ 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;+ armed = null;+ activity = null;+ recovered = true;+ return true;+ },+ takeExpired(nowMs) {+ if (!armed || nowMs < armed.deadlineAt) return null;+ const { analysis } = armed;+ armed = null;+ activity = null;+ return analysis;+ },+ };+}+// A SINGLE Enter after a large bracketed paste is unreliable: the TUI can still// be processing/reflowing the multi-line paste when the `\r` arrives and// swallow it, leaving the whole prompt sitting unsent in the input box. Thediff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex d621c21e57..3ce5f177a2 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -12,6 +12,8 @@ import {MIN_WORK_COUNTER_SPAN_MS,extractWorkCounterSeconds,createWorkActivityTracker,+ createGenerationActivityTracker,+ createSelfClearingSignalGate,MERGE_QUEUE_IDLE_TIMEOUT_MS,isMergeQueueSignal,createMergeQueueTracker,@@ -239,6 +241,128 @@ describe('tuiHandshake — paste timing constants', () => {expect(tracker.active).toBe(false);});+ // Verdict for agy's self-clearing eligibility banner: did the provider come+ // back? The chrome below is lifted from real transcripts — healthy agy runs+ // (2026-08-05) carry `esc to cancel`/`Generating…`; the five runs killed on the+ // banner (2026-08-07 → 08-11) carry neither.+ it('createGenerationActivityTracker latches on agy in-flight chrome', () => {+ const tracker = createGenerationActivityTracker();+ tracker.observe('> ? for shortcuts');+ expect(tracker.active).toBe(false);+ tracker.observe('Generating...');+ expect(tracker.active).toBe(true);+ });++ it('createGenerationActivityTracker latches on the esc-to-cancel footer', () => {+ const tracker = createGenerationActivityTracker();+ tracker.observe('esc to cancelGemini 3.6 Flash high');+ expect(tracker.active).toBe(true);+ });++ it('createGenerationActivityTracker also admits the Claude/Codex elapsed counter', () => {+ const tracker = createGenerationActivityTracker();+ tracker.observe('(12s · esc to interrupt)');+ expect(tracker.active).toBe(true);+ });++ it('createGenerationActivityTracker stays inactive on the stuck agy banner screen', () => {+ const tracker = createGenerationActivityTracker();+ // Verbatim from agent-09824620's raw.txt, ANSI-stripped.+ tracker.observe('[Pasted text #1 +43 lines]');+ tracker.observe('Verifying your account...');+ tracker.observe("We're finishing verifying your account eligibility.");+ tracker.observe('This usually takes a moment. Please try again shortly.');+ tracker.observe('> ? for shortcutsGemini 3.6 Flash high');+ expect(tracker.active).toBe(false);+ });++ it('createGenerationActivityTracker stays latched once active', () => {+ const tracker = createGenerationActivityTracker();+ tracker.observe('Generating...');+ tracker.observe('> ? for shortcuts');+ expect(tracker.active).toBe(true);+ });++ it('createGenerationActivityTracker ignores non-string input', () => {+ const tracker = createGenerationActivityTracker();+ tracker.observe(undefined);+ tracker.observe(null);+ expect(tracker.active).toBe(false);+ });++ // 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 ');+ expect(tracker.active).toBe(false);+ tracker.observe('cancel');+ expect(tracker.active).toBe(true);+ });++ describe('createSelfClearingSignalGate', () => {+ const BANNER = { message: 'eligibility', graceMs: 60000 };++ it('arms once and reports the deadline only after it passes', () => {+ const gate = createSelfClearingSignalGate();+ expect(gate.arm(BANNER, 1000)).toBe(true);+ expect(gate.armed).toBe(true);+ expect(gate.takeExpired(60000)).toBeNull();+ expect(gate.takeExpired(61000)).toBe(BANNER);+ expect(gate.armed).toBe(false);+ });++ it('refuses to re-arm while open, so a repainting banner cannot restart the clock', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm(BANNER, 1000);+ expect(gate.arm(BANNER, 50000)).toBe(false);+ // Deadline still measured from the FIRST sighting, not the latest repaint.+ expect(gate.takeExpired(61001)).toBe(BANNER);+ });++ it('ignores a signal with no grace window', () => {+ const gate = createSelfClearingSignalGate();+ expect(gate.arm({ message: 'usage limit', graceMs: 0 }, 1000)).toBe(false);+ expect(gate.armed).toBe(false);+ });++ 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.armed).toBe(false);+ // Nothing left to fail over with — the run continues.+ expect(gate.takeExpired(61000)).toBeNull();+ });++ // The caller's detector buffers ~512 chars, so the banner keeps matching well+ // after recovery. Re-arming on one of those stale matches would fail the run+ // over 60s later — the exact bug the grace window exists to prevent.+ it('does not re-arm on a stale banner match after the provider recovered', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm(BANNER, 1000);+ gate.observe('Generating...');+ expect(gate.recovered).toBe(true);+ expect(gate.arm(BANNER, 2000)).toBe(false);+ expect(gate.takeExpired(120000)).toBeNull();+ });++ it('does not treat pre-arm output as evidence of recovery', () => {+ const gate = createSelfClearingSignalGate();+ expect(gate.observe('Generating...')).toBe(false);+ gate.arm(BANNER, 1000);+ // Only the banner screen repaints from here — still stuck.+ gate.observe('> ? for shortcuts');+ expect(gate.takeExpired(61001)).toBe(BANNER);+ });++ it('honors a per-signal grace window rather than one global constant', () => {+ const gate = createSelfClearingSignalGate();+ gate.arm({ message: 'slow warmup', graceMs: 5000 }, 0);+ expect(gate.takeExpired(4999)).toBeNull();+ expect(gate.takeExpired(5000)).toMatchObject({ graceMs: 5000 });+ });+ });+it('pins work-activity detection constants', () => {expect(WORK_COUNTER_PATTERN).toBeInstanceOf(RegExp);expect(MIN_WORK_COUNTER_SAMPLES).toBe(2);diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex ee2d8222a0..c5451d3699 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -64,6 +64,7 @@ import {RAW_BUFFER_HEADROOM,buildTuiInvocation,detectMissingTuiBinary,+ createSelfClearingSignalGate,} from './tuiHandshake.js';import { buildCliChildEnv } from './cliChildEnv.js';import { isCodexCommand } from './codex.js';@@ -321,6 +322,12 @@ ${prompt}`;let idleWatchTimer = null;let responseFileWatchTimer = null;let hardTimeoutTimer = null;+ // Holds the wait-it-out window for a provider signal carrying a `graceMs`+ // (agy's account-eligibility banner). Unlike the long-running agent path this+ // 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();const cleanupTimers = () => {// Stop the post-paste accumulator from growing on any chunk that lands@@ -332,6 +339,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; }};return new Promise((resolve) => {@@ -478,10 +486,36 @@ ${prompt}`;}onData?.(stripped);+ // 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)) {+ if (selfClearingTimer) { clearTimeout(selfClearingTimer); selfClearingTimer = null; }+ console.log(`✅ TUI run ${runId} provider signal cleared — generating again`);+ }+const fallbackSignal = detectImmediateFallbackSignal(stripped)|| detectTerminalModelError(stripped)|| detectTerminalRequestTimeout(stripped);- if (fallbackSignal) {+ // Branch on the SIGNAL's own grace window, never on gate state: the+ // detector buffers ~512 chars, so a banner keeps matching for many chunks+ // after it has scrolled off. Reading gate state here would let one of+ // those stale matches fall through to an immediate kill the moment the+ // 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())) {+ console.log(`⏳ TUI run ${runId} holding for a self-clearing provider signal (${Math.round(fallbackSignal.graceMs / 1000)}s): ${fallbackSignal.message}`);+ selfClearingTimer = setTimeout(() => {+ selfClearingTimer = null;+ const expired = selfClearingGate.takeExpired(Date.now());+ if (finalized || !expired) return;+ finishWithFallbackSignal(expired).catch((err) => {+ console.error(`❌ TUI run ${runId} deferred fallback-signal handling failed: ${err?.message || err}`);+ });+ }, fallbackSignal.graceMs);+ }+ } else if (fallbackSignal) {// Fire-and-forget like every other finish() call from this PTY// callback; finish() itself never rejects and the salvage read can't// throw, so the catch is belt-and-braces for a callback boundary.@@ -511,6 +545,13 @@ ${prompt}`;// natural process exit or an explicit Stop. Unattended pipeline runs// keep the snappy idle threshold for throughput.if (isExternalSessionAttached(runId)) return;+ // A run waiting out a provider handshake is silent by design, and the+ // only thing on screen is the banner. Idle-completing here would+ // finalize SUCCESS and scrape that error screen as the answer — the+ // bogus-response failure this file guards against elsewhere. Bounded+ // twice over: the gate closes on the first sign of generation, and its+ // own timer resolves the deadline regardless.+ if (selfClearingGate.armed) return;const idle = Date.now() - lastOutputAt;if (idle >= idleThresholdMs) {if (requiresResponseFileForIdleCompletion) return;diff --git a/server/lib/tuiPromptRunner.test.js b/server/lib/tuiPromptRunner.test.jsindex 32dcccd73c..b451a7fe53 100644--- a/server/lib/tuiPromptRunner.test.js+++ b/server/lib/tuiPromptRunner.test.js@@ -779,6 +779,64 @@ describe('executeTuiRun', () => {}));});+ // ── agy account-eligibility banner: a WAIT, not a verdict ─────────────────+ // The banner paints while agy's `loadCodeAssist` handshake is still retrying+ // and the CLI generates normally once it settles, so a self-clearing signal+ // arms a grace window instead of killing the PTY on sight.+ const ELIGIBILITY_BANNER =+ "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly.";++ it('holds a run open for the eligibility banner and resumes when agy starts generating', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date'] });+ const provider = { id: 'antigravity', type: 'tui', command: 'agy', tuiPromptDelayMs: 50, tuiOneShotIdleMs: 500 };+ const onComplete = vi.fn();+ const promise = executeTuiRun({ runId: 'run-eligibility-ok', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete, timeout: 600000 });+ await flushAsync();++ const pty = ptyInstances[0];+ pty.emitData(ELIGIBILITY_BANNER);+ await vi.advanceTimersByTimeAsync(5000);+ // The old behavior killed the PTY within a second of the banner.+ expect(pty.kill).not.toHaveBeenCalled();++ // agy settles its handshake and paints its in-flight chrome.+ pty.emitData('Generating...\nesc to cancel');+ await vi.advanceTimersByTimeAsync(70000);+ await flushAsync();++ expect(runnerMocks.finalizeRunRecord).not.toHaveBeenCalledWith(expect.objectContaining({+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),+ }));+ 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 };+ const onComplete = vi.fn();+ const promise = executeTuiRun({ runId: 'run-eligibility-stuck', provider, prompt: 'do thing big enough to clear the prompt guard', workspacePath: TEST_WORKSPACE, onData: undefined, onComplete, timeout: 600000 });+ await flushAsync();++ const pty = ptyInstances[0];+ pty.emitData(ELIGIBILITY_BANNER);+ // 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);+ await flushAsync();++ await promise;+ expect(runnerMocks.finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({+ runId: 'run-eligibility-stuck',+ success: false,+ exitCode: 1,+ error: expect.stringContaining('account eligibility'),+ extras: expect.objectContaining({ completionReason: 'fallback-signal' }),+ }));+ });+it('early-fails with reason "fallback-signal" when the model id is rejected (Bedrock invalid identifier) instead of idling to a bogus-scrape success', async () => {const provider = { id: 'claude', type: 'tui', command: 'claude' };const onComplete = vi.fn();diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex a1c09d0158..461cf01e5b 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -47,6 +47,7 @@ import {PASTE_MARKER_POLL_MS,countPasteMarkers,createWorkActivityTracker,+ createSelfClearingSignalGate,createMergeQueueTracker,createReviewLoopTracker,createBackgroundShellTracker,@@ -304,6 +305,10 @@ export async function spawnTuiAgent({let finalized = false;let immediateFallbackAnalysis = null;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();// 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.@@ -739,6 +744,24 @@ export async function spawnTuiAgent({// there is no reason to shrink it on the way out.};+ // The single fail-over verdict, reached from two places: a signal with no grace+ // window (immediate) and a grace window that expired without recovery. Sharing+ // it keeps the deferred path provably identical to the immediate one.+ //+ // `immediateFallbackAnalysis` is set HERE and not at arm time on purpose — it is+ // read at finalize by resolveErrorAnalysis, so stamping it when the window opens+ // would tag a run that went on to RECOVER with the banner as its error.+ const failOverToFallback = (analysis) => {+ immediateFallbackAnalysis = analysis;+ appendLine(`⚡ Provider fallback signal: ${analysis.message}`);+ return finish({+ success: false,+ exitCode: 1,+ error: analysis.message || 'Provider requires fallback',+ reason: 'fallback-signal'+ });+ };+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@@ -826,16 +849,26 @@ export async function spawnTuiAgent({// path. We still spool the raw stream to raw.txt for error analysis// on failure, and we detect early "command not found" so a missing// 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)) {+ appendLine(`✅ Provider signal cleared — ${tuiConfig.command} is generating again; continuing the run`);+ }+const fallbackSignal = detectImmediateFallbackSignal(stripped);- if (fallbackSignal) {- immediateFallbackAnalysis = fallbackSignal;- appendLine(`⚡ Provider fallback signal: ${fallbackSignal.message}`);- await finish({- success: false,- exitCode: 1,- error: fallbackSignal.message || 'Provider requires fallback',- reason: 'fallback-signal'- });+ // Branch on the SIGNAL's own grace window, never on gate state: the+ // detector buffers ~512 chars, so a banner keeps matching for many chunks+ // after it has scrolled off. Reading gate state here would let one of those+ // stale matches fall through to an immediate kill the moment the 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, now)) {+ appendLine(`⏳ Provider signal (self-clearing): ${fallbackSignal.message} — holding the session up to ${Math.round(fallbackSignal.graceMs / 1000)}s for it to clear`);+ }+ } else if (fallbackSignal) {+ await failOverToFallback(fallbackSignal);return;}@@ -1347,7 +1380,26 @@ export async function spawnTuiAgent({}, READY_POLL_INTERVAL_MS);const idleTimer = setInterval(() => {- if (!promptSentAt || finalized) return;+ if (finalized) return;+ // Resolve an expired grace window. Checked BEFORE the promptSentAt gate+ // below: the banner can paint during startup too, and a run stalled there+ // would otherwise hold the window forever.+ const expired = selfClearingGate.takeExpired(Date.now());+ if (expired) {+ // setInterval can't await, and an unhandled rejection here would crash the+ // process (the callback-boundary hazard CLAUDE.md calls out).+ failOverToFallback(expired).catch((err) =>+ emitLog('error', `TUI agent ${agentId} deferred fallback finish failed: ${err?.message || err}`, { agentId }));+ return;+ }+ // A session waiting out a provider handshake is silent by definition — but it+ // is NOT idle, and letting the reaper finalize it would be far worse than the+ // premature kill this window replaced: with no `.agent-done` sentinel the+ // 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;+ 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 can// sit in a silent reflow/commit window with no PTY output yet, whichdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex c3e3ac9122..805e865f11 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -1656,14 +1656,87 @@ describe('spawnTuiAgent runtime', () => {);});- it('fails immediately when Antigravity reports that account eligibility is still being verified', async () => {+ // ── Antigravity account-eligibility banner: a WAIT, not a verdict ───────────+ // The banner paints while agy's `loadCodeAssist` handshake is still retrying;+ // the CLI's own log shows the session authenticated fine and generating+ // normally once it settles. Killing on sight cost every agy CoS run from+ // 2026-08-07 on (5/5, each dead 3–5s in). So the signal now arms a+ // SELF_CLEARING_SIGNAL_GRACE_MS window instead of finalizing immediately.+ const ELIGIBILITY_BANNER =+ "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly.";++ // Drive agy to a submitted prompt, which is where the banner really appears+ // (agent-09824620: composer up, paste lands, THEN the banner paints). Starting+ // from a bare spawn instead would let the 45s tui-not-ready deadline finalize+ // the run before the grace window is ever reached, masking what's under test.+ const driveAgyToSubmittedPrompt = async () => {runSpawn({ tuiConfig: agyTuiConfig });await flushMicrotasks();+ // Shell turns paste mode off to run the command, agy turns it back on at+ // alt-screen entry, then its composer footer says the input box is live.+ await capturedOnData(Buffer.from(`${PASTE_OFF}Antigravity CLI 1.1.12\n`));+ await flushMicrotasks();+ await capturedOnData(Buffer.from(`${PASTE_ON}Welcome to the Antigravity CLI.\n Signing in...\n`));+ await flushMicrotasks();+ await capturedOnData(Buffer.from(`>\n${AGY_COMPOSER_FOOTER}Gemini 3.6 Flash · high`));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(400);+ await flushMicrotasks();+ expect(pasteCount()).toBe(1);+ // Echo the prompt back the way a real TUI renders it into the input buffer,+ // so paste verification passes and the submit Enter goes out (issue #2192).+ await capturedOnData(Buffer.from('do the thing\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(4000); // past PASTE_TO_ENTER_FALLBACK_MS (3500ms)+ await flushMicrotasks();+ };++ it('holds the session open when Antigravity reports that account eligibility is still being verified', async () => {+ await driveAgyToSubmittedPrompt();++ await capturedOnData(Buffer.from(ELIGIBILITY_BANNER));+ await flushMicrotasks();+ // The old behavior finalized here, within a second of the banner.+ await vi.advanceTimersByTimeAsync(30000);+ await flushMicrotasks();++ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();+ });++ it('resumes the run when the eligibility banner clears and agy starts generating', async () => {+ await driveAgyToSubmittedPrompt();- await capturedOnData(Buffer.from(- "We're finishing verifying your account eligibility. This usually takes a moment. Please try again shortly."- ));+ await capturedOnData(Buffer.from(ELIGIBILITY_BANNER));await flushMicrotasks();+ // agy settles its handshake and paints its in-flight chrome.+ await capturedOnData(Buffer.from('Generating...\nesc to cancel'));+ await flushMicrotasks();++ // Past the grace deadline — the run must NOT be failed over to a fallback.+ await vi.advanceTimersByTimeAsync(70000);+ await flushMicrotasks();++ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalledWith(+ expect.objectContaining({ completionReason: 'fallback-signal' })+ );+ });++ it('falls back once the eligibility banner outlasts its grace window with no generation', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ await driveAgyToSubmittedPrompt();++ await capturedOnData(Buffer.from(ELIGIBILITY_BANNER));+ await flushMicrotasks();+ // Only idle composer chrome repaints — no sign of life.+ await capturedOnData(Buffer.from('> ? for shortcuts'));+ await flushMicrotasks();++ await vi.advanceTimersByTimeAsync(70000);+ vi.useRealTimers();+ await completeDone;expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(expect.objectContaining({