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: echo-proof work signal (advancing counter) + gate the one-shot runner too
[._.]/ Adam Eivy32b02ab4d5e3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d8cc9e0fde..d90d5e1535 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -80,6 +80,6 @@- **TUI agents no longer leave the prompt sitting unsent in the input box** — CoS agents that run inside a terminal-UI provider (Claude Code, Codex) bracketed-paste their task prompt and then send a single Enter to submit it. On a large multi-line prompt that one `\r` could arrive while the TUI was still reflowing the paste and get swallowed — so the prompt sat typed-but-unsubmitted, the agent did no work, idled out after 3 minutes, and was (wrongly) recorded as a successful run. You'd see it only by opening the Shell tab and hitting Enter yourself. The submit Enter now fires a few times spaced ~700ms apart so one lands after the paste settles; re-sending is safe because once the prompt submits the input box is empty and a bare Enter is a no-op. Applies to both the long-running agent path and the one-shot TUI runner. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`, `server/lib/tuiPromptRunner.js`)-- **A TUI agent that never started working is no longer recorded as a success** — Two follow-ups to the unsent-prompt fix above. First, the paste-commit fast path that submits the prompt the moment Claude Code finishes ingesting it was effectively dead: it scanned the raw terminal stream for the `[Pasted text #N]` marker, but Claude Code draws that marker with cursor-positioning codes between every word, so the literal text never matched and *every* run fell back to a blind 3.5-second timer. The matcher now runs against the cleaned text, so the fast path fires again on large pastes (short prompts still use the timer, and the multi-Enter safety net covers both). Second, a run that idled out without ever submitting its prompt was still marked **successful** — the idle check only confirmed the terminal had repainted *something*, and the status bar repaints constantly even with an unsent prompt. The agent now must show a real sign of work (a "thinking"/working indicator after the paste) before an idle-out counts as done; an idle-out with no such activity is recorded as a **failure** instead, so a no-op run can't masquerade as completed. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`, `server/lib/tuiPromptRunner.js`)+- **A TUI agent that never started working is no longer recorded as a success** — Two follow-ups to the unsent-prompt fix above. First, the paste-commit fast path that submits the prompt the moment Claude Code finishes ingesting it was effectively dead: it scanned the raw terminal stream for the `[Pasted text #N]` marker, but Claude Code draws that marker with cursor-positioning codes between every word, so the literal text never matched and *every* run fell back to a blind 3.5-second timer. The matcher now runs against the cleaned text, so the fast path fires again on large pastes (short prompts still use the timer, and the multi-Enter safety net covers both). Second, a run that idled out without ever submitting its prompt was still marked **successful** — the idle check only confirmed the terminal had repainted *something*, and the status bar repaints constantly even with an unsent prompt. A run now must show a real sign of work — the terminal's elapsed-time working counter actually advancing — before an idle-out counts as done; an idle-out with no such activity is recorded as a **failure** instead, so a no-op run can't masquerade as completed. Both fixes apply to the long-running agent path and the one-shot TUI runner. (`server/lib/tuiHandshake.js`, `server/services/agentTuiSpawning.js`, `server/lib/tuiPromptRunner.js`)- **`calendarSync` test no longer depends on the developer's machine state** — the "throws 401 when Google OAuth is not configured" test read the REAL Google credentials/tokens off disk, so on a machine with OAuth configured it failed with a `GaxiosError` (400 invalid_grant) instead of the pinned 401. The auth client is now mocked to the not-configured state. (`server/services/calendarSync.test.js`)diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex 1440c2cbb6..2d1f67864e 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -62,28 +62,64 @@ export function detectPasteMarker(strippedText) {// its banner/status line continuously even with an UNSUBMITTED prompt sitting in// the input box, so "any PTY output after the paste" cannot distinguish real// work from chrome churn — that conflation is what finalized a never-submitted-// agent as `success: idle-complete` (issue #1229). These patterns fire only once-// a request is in flight and never appear on the idle/stuck input screen:-// - an elapsed-time working counter — `(1s · …` (Claude Code) / `(57s • …`-// (Codex). The most model-agnostic signal; present in both, absent when stuck.-// - `esc to interrupt` — the live-request interrupt hint (Codex; some Claude).-// - `thinking` — Claude Code's working spinner caption.-// Verified against real transcripts: working runs hit these thousands of times;-// the two confirmed stuck runs (`agent-92ed2c56`, `agent-30a3ab56`) hit them-// zero times. Heuristic by nature (spinner captions rotate across versions), so-// it gates only the FALLBACK idle-complete path — the authoritative success-// signal remains the `.agent-done` sentinel.-export const WORK_ACTIVITY_PATTERN = /\(\s*\d+s\b|esc to interrupt|\bthinking\b/i;+// agent as `success: idle-complete` (issue #1229).+//+// We key on the TUI's elapsed-time WORKING COUNTER — `(1s · …` (Claude Code) /+// `(57s • …` (Codex) — which renders only while a request is in flight and+// INCREMENTS as the model works. This is the most model-agnostic signal (present+// in both providers, absent on the stuck screen) AND it is echo-proof: the prompt+// is echoed into the input box BEFORE submission, so word-matching `thinking` or+// `esc to interrupt` could be tripped by a task description that merely contains+// those words (flagged in review of #1229). A literal `(5s` in a prompt is a+// single fixed value; the live counter passes through MANY distinct values, so we+// require ≥ MIN_WORK_COUNTER_SAMPLES distinct second-counts before trusting it.+// Verified against real transcripts: the working run cycled through ~29 counter+// values; the two confirmed stuck runs (`agent-92ed2c56`, `agent-30a3ab56`) had+// none. Heuristic by nature, so it gates only the FALLBACK idle-complete path —+// the authoritative success signal remains the `.agent-done` sentinel.+export const WORK_COUNTER_PATTERN = /\(\s*(\d+)\s*s\b/g;+export const MIN_WORK_COUNTER_SAMPLES = 2;/**- * True when `strippedText` shows the model is actively working on a submitted- * prompt (see WORK_ACTIVITY_PATTERN). Callers MUST pass ANSI-stripped output.+ * Extract every elapsed-second value from the TUI working counter in+ * `strippedText` (e.g. `(1s · …` → 1, `(57s • …` → 57). Callers MUST pass+ * ANSI-stripped output. Returns an array (possibly empty); non-string input+ * yields `[]`.** @param {string} strippedText — ANSI-stripped output (a chunk or accumulator).- * @returns {boolean}+ * @returns {number[]}+ */+export function extractWorkCounterSeconds(strippedText) {+ if (typeof strippedText !== 'string' || !strippedText) return [];+ const out = [];+ // Fresh matcher state per call — a module-level /g regex carries lastIndex+ // across calls and would skip matches on the next invocation.+ const re = new RegExp(WORK_COUNTER_PATTERN.source, 'g');+ let m;+ while ((m = re.exec(strippedText)) !== null) out.push(Number(m[1]));+ return out;+}++/**+ * Stateful tracker for the "model is actively working" signal. Feed it each+ * ANSI-stripped post-paste chunk via `observe()`; it becomes (and stays)+ * `active` once it has seen ≥ MIN_WORK_COUNTER_SAMPLES DISTINCT elapsed-second+ * counter values — i.e. the working counter actually advanced, which a static+ * echoed prompt cannot fake. Shared by both TUI consumers so the echo-proof+ * detection logic can't drift between them.+ *+ * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}*/-export function detectWorkActivity(strippedText) {- return typeof strippedText === 'string' && WORK_ACTIVITY_PATTERN.test(strippedText);+export function createWorkActivityTracker() {+ const seconds = new Set();+ const isActive = () => seconds.size >= MIN_WORK_COUNTER_SAMPLES;+ return {+ observe(strippedText) {+ for (const s of extractWorkCounterSeconds(strippedText)) seconds.add(s);+ return isActive();+ },+ get active() { return isActive(); },+ };}// A SINGLE Enter after a large bracketed paste is unreliable: the TUI can stilldiff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex e82d32f651..53cc8c7639 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -6,8 +6,10 @@ import {PASTE_MARKER_POLL_MS,PASTE_MARKER_PATTERN,detectPasteMarker,- WORK_ACTIVITY_PATTERN,- detectWorkActivity,+ WORK_COUNTER_PATTERN,+ MIN_WORK_COUNTER_SAMPLES,+ extractWorkCounterSeconds,+ createWorkActivityTracker,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,SUBMIT_ENTER_ATTEMPTS,@@ -97,31 +99,55 @@ describe('tuiHandshake — paste timing constants', () => {expect(detectPasteMarker('[Pasted text #1 +3 lines]')).toBe(true);});- it('detectWorkActivity recognizes a model actively processing a submitted prompt', () => {- // Elapsed working counter — model-agnostic (Claude Code + Codex).- expect(detectWorkActivity('(1s · thinking with high effort)')).toBe(true);- expect(detectWorkActivity('(57s • esc to interrupt)')).toBe(true);- expect(detectWorkActivity('(0s · Churning…)')).toBe(true);- // Codex live-request interrupt hint.- expect(detectWorkActivity('Working (12s · esc to interrupt)')).toBe(true);- // Claude Code working caption.- expect(detectWorkActivity('✻ thinking with high effort')).toBe(true);- });-- it('detectWorkActivity returns false for the stuck/idle input screen (no work signal)', () => {- // The chrome present on a never-submitted-prompt screen (from the #1229- // false-success transcript): footer + echoed prompt + effort indicator.- expect(detectWorkActivity('⏵⏵ bypass permissions on (shift+tab to cycle)')).toBe(false);- expect(detectWorkActivity('● high · /effort')).toBe(false);- expect(detectWorkActivity('paste again to expand')).toBe(false);- expect(detectWorkActivity('Begin working on the task now.')).toBe(false);- expect(detectWorkActivity('Opus 4.8 │ agent-92ed2c56')).toBe(false);- expect(detectWorkActivity('')).toBe(false);- expect(detectWorkActivity(null)).toBe(false);- });-- it('WORK_ACTIVITY_PATTERN is exported as a RegExp for caller reuse', () => {- expect(WORK_ACTIVITY_PATTERN).toBeInstanceOf(RegExp);+ it('extractWorkCounterSeconds parses the TUI elapsed working counter', () => {+ // Claude Code: `(1s · …`; Codex: `(57s • …`.+ expect(extractWorkCounterSeconds('(1s · thinking with high effort)')).toEqual([1]);+ expect(extractWorkCounterSeconds('(57s • esc to interrupt)')).toEqual([57]);+ expect(extractWorkCounterSeconds('(0s · Churning…)')).toEqual([0]);+ // Multiple counters in one buffer (e.g. an accumulated screen).+ expect(extractWorkCounterSeconds('(1s) … (2s) … (3s)')).toEqual([1, 2, 3]);+ // No counter → empty; non-string → empty (guard).+ expect(extractWorkCounterSeconds('● high · /effort')).toEqual([]);+ expect(extractWorkCounterSeconds('')).toEqual([]);+ expect(extractWorkCounterSeconds(null)).toEqual([]);+ });++ it('extractWorkCounterSeconds is stateless across calls (no lastIndex carryover)', () => {+ // A module-level /g regex would skip matches on the 2nd call; assert it doesn't.+ expect(extractWorkCounterSeconds('(4s)')).toEqual([4]);+ expect(extractWorkCounterSeconds('(4s)')).toEqual([4]);+ });++ it('createWorkActivityTracker activates only after the counter ADVANCES (echo-proof)', () => {+ const tracker = createWorkActivityTracker();+ expect(tracker.active).toBe(false);+ // A single counter value — e.g. a literal `(5s` echoed from the prompt text —+ // must NOT activate. This is the #1229 review fix: word/single-value matching+ // could be tripped by the echoed prompt before submission.+ expect(tracker.observe('please respond within (5s) of receiving this')).toBe(false);+ expect(tracker.observe('still (5s) (5s) repainted chrome')).toBe(false);+ expect(tracker.active).toBe(false);+ // A second DISTINCT value — the live counter actually advanced — activates.+ expect(tracker.observe('(6s · thinking)')).toBe(true);+ expect(tracker.active).toBe(true);+ // Stays active once tripped.+ expect(tracker.observe('● high · /effort')).toBe(true);+ });++ it('createWorkActivityTracker stays inactive on pure stuck/idle chrome', () => {+ const tracker = createWorkActivityTracker();+ // The exact chrome from the #1229 false-success transcript (no counter).+ tracker.observe('⏵⏵ bypass permissions on (shift+tab to cycle)');+ tracker.observe('● high · /effort');+ tracker.observe('paste again to expand');+ tracker.observe('Begin working on the task now.');+ tracker.observe('Opus 4.8 │ agent-92ed2c56');+ expect(tracker.active).toBe(false);+ });++ it('pins work-activity detection constants', () => {+ expect(WORK_COUNTER_PATTERN).toBeInstanceOf(RegExp);+ expect(MIN_WORK_COUNTER_SAMPLES).toBe(2);});it('pins provider-default constants', () => {diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex ad7c3ff22b..c5414f9baf 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -44,6 +44,7 @@ import {DEFAULT_TUI_PROMPT_DELAY_MS,PASTE_MARKER_POLL_MS,detectPasteMarker,+ createWorkActivityTracker,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,scheduleSubmitEnters,@@ -208,6 +209,11 @@ ${prompt}`;// path dead (issue #1229). Lives only during the paste→Enter window; nulled// when detection resolves or the run finalizes.let postPasteStripped = null;+ // Echo-proof "model is actively working" tracker (working counter advancing).+ // Gates the inline-output idle-complete fallback so a never-submitted one-shot+ // prompt can't be scraped as a successful response (issue #1229) — the same+ // guard the agent path uses; the authoritative path here is the response file.+ const workActivity = createWorkActivityTracker();let firstOutputAt = null;let lastOutputAt = startTime;let firstResponseAt = null;@@ -308,6 +314,7 @@ ${prompt}`;const stripped = streamingStrip(text);if (stripped) {if (postPasteStripped !== null) postPasteStripped += stripped;+ if (promptSentAt && !workActivity.active) workActivity.observe(stripped);outputBuffer += stripped;if (outputBuffer.length > OUTPUT_BUFFER_HEADROOM) {outputBuffer = outputBuffer.slice(-OUTPUT_BUFFER_CAP);@@ -351,7 +358,21 @@ ${prompt}`;if (isExternalSessionAttached(runId)) return;const idle = Date.now() - lastOutputAt;if (idle >= idleThresholdMs) {- finish({ success: true, exitCode: 0, reason: 'idle-complete' });+ // Mirror the agent path's #1229 guard: idle-complete is the inline-+ // output fallback (the response file is authoritative), so only trust+ // it as success when the model actually worked (working counter+ // advanced). Pure chrome churn from a never-submitted prompt would+ // otherwise let the screen-scrape fallback masquerade as a response.+ if (workActivity.active) {+ finish({ success: true, exitCode: 0, reason: 'idle-complete' });+ } else {+ finish({+ success: false,+ exitCode: 1,+ error: 'TUI run idled out with no sign of work — the prompt likely never submitted (no working indicator after paste) and no response file was written.',+ reason: 'idle-no-activity',+ });+ }}}, 1000);}diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex e96ef343e6..a54f3a9d26 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -28,7 +28,7 @@ import {READY_IDLE_THRESHOLD_MS,PASTE_MARKER_POLL_MS,detectPasteMarker,- detectWorkActivity,+ createWorkActivityTracker,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,scheduleSubmitEnters,@@ -207,13 +207,14 @@ export async function spawnTuiAgent({let sentinelIngested = false;let hasStartedWorking = false;let promptSentAt = null;- // True once we've seen evidence the model is actively processing the SUBMITTED- // prompt (working counter / interrupt hint / "thinking" — see detectWorkActivity).+ // Tracks evidence the model is actively processing the SUBMITTED prompt — the+ // TUI's elapsed working counter advancing through ≥2 distinct values (see+ // createWorkActivityTracker; echo-proof, unlike word-matching the prompt text).// Distinct from `hasStartedWorking`, which flips on ANY post-spawn PTY output- // including pure banner/status-line chrome. This flag is what gates the+ // including pure banner/status-line chrome. `tracker.active` is what gates the// fallback idle-complete path from finalizing a never-submitted prompt as// success (issue #1229).- let sawWorkActivity = false;+ const workActivity = createWorkActivityTracker();let firstOutputAt = null;let lastOutputAt = Date.now();let lastLine = '';@@ -538,11 +539,9 @@ export async function spawnTuiAgent({if (postPasteBuffer !== null && stripped) postPasteBuffer += stripped;// Once the prompt is submitted, watch for proof the model is actually// working. The TUI repaints chrome continuously even with an unsent prompt,- // so we can't trust mere PTY activity — only a working indicator confirms- // the prompt left the input box. Gates idle-complete (issue #1229).- if (promptSentAt && !sawWorkActivity && stripped && detectWorkActivity(stripped)) {- sawWorkActivity = true;- }+ // so we can't trust mere PTY activity — only the working counter advancing+ // confirms the prompt left the input box. Gates idle-complete (issue #1229).+ if (promptSentAt && stripped && !workActivity.active) workActivity.observe(stripped);lastOutputAt = Date.now();if (firstOutputAt === null) firstOutputAt = lastOutputAt;@@ -718,10 +717,10 @@ export async function spawnTuiAgent({// prompt that just idled out. `lastOutputAt > promptSentAt` only proves// the TUI repainted SOMETHING — banner/status chrome churns even with the// prompt sitting unsent. Only finalize as success when we actually saw the- // model working (sawWorkActivity); otherwise this is the #1229 failure mode- // (prompt never submitted, zero work done) and must be recorded as a+ // model working (workActivity.active); otherwise this is the #1229 failure+ // mode (prompt never submitted, zero work done) and must be recorded as a// FAILURE so the orchestrator doesn't treat a no-op run as done.- if (sawWorkActivity) {+ if (workActivity.active) {finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });});diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex e34c532b5d..14187ff5d7 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -348,12 +348,14 @@ describe('spawnTuiAgent runtime', () => {await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();- // Feed a PTY chunk AFTER the paste that proves the model is actually- // WORKING — an elapsed working counter (`(1s · …`). This both sets- // lastOutputAt > promptSentAt AND trips sawWorkActivity, which the idle- // gate now requires before finalizing as success (issue #1229 — pure- // chrome churn must NOT count as completion; see the no-activity test below).+ // Feed PTY chunks AFTER the paste that prove the model is actually WORKING —+ // the elapsed working counter ADVANCING through two distinct values. This+ // sets lastOutputAt > promptSentAt AND trips the work-activity tracker, which+ // the idle gate now requires before finalizing as success (issue #1229 — pure+ // chrome churn, or a single echoed counter value, must NOT count; see the+ // no-activity test below).await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));+ await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));// Advance past DEFAULT_TUI_MIN_RUNTIME_MS (15 000ms) + idleTimeoutMs (50ms).// The idle setInterval ticks every 5 000ms; at the >=15s tick the@@ -398,7 +400,8 @@ describe('spawnTuiAgent runtime', () => {// Post-paste output, but ONLY chrome that repaints with an unsent prompt —// the input footer + effort indicator from the real #1229 stuck transcript.- // None of this is a work-activity signal, so sawWorkActivity stays false.+ // None of this advances the working counter, so the work-activity tracker+ // stays inactive.await capturedOnData(Buffer.from('⏵⏵ bypass permissions on (shift+tab to cycle)\n'));await capturedOnData(Buffer.from('● high · /effort\n'));@@ -710,6 +713,7 @@ describe('spawnTuiAgent runtime', () => {await vi.advanceTimersByTimeAsync(2000);await flushMicrotasks();await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));+ await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));await vi.advanceTimersByTimeAsync(21000);vi.useRealTimers();await completeDone;