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 (codex): use input recency, not socket attachment, as the guard
Adam Eivy9931b0caa97f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 97b381d640..82d45f9837 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,7 +2,7 @@## CoS Agents-- **A live agent TUI you're actively watching in the Shell page no longer gets reaped mid-paste.** The idle-timeout reaper only tracks `lastOutputAt` (PTY output), not client input, so pasting a large multi-line command into a running agent's session could sit in a silent reflow/commit window with no echo yet — indistinguishable from "idle" to the 5s poll. If the session happened to already be near its idle threshold, the reaper killed the PTY out from under the viewer, showing "[Session removed externally]" with the paste seemingly vanishing. The long-running CoS-agent idle timer in `agentTuiSpawning.js` now checks a new `shell.js` export, `isSessionViewed()`, before reaping — true whenever any socket is bound to the session — and skips the reap entirely whenever a Shell viewer is attached. (The existing `isExternalSessionAttached()`, which the one-shot `tuiPromptRunner.js` idle-watch already uses, only covers sessions registered via `registerExternalSession` and would never have fired for a regular agent-tui session, so a plain reuse of it would have been a no-op guard.) (`server/services/shell.js`, `server/services/agentTuiSpawning.js`)+- **A live agent TUI no longer gets reaped mid-paste.** The idle-timeout reaper only tracked `lastOutputAt` (PTY output), not client input, so pasting a large multi-line command into a running agent's session could sit in a silent reflow/commit window with no echo yet — indistinguishable from "idle" to the 5s poll. If the session happened to already be near its idle threshold, the reaper killed the PTY mid-paste, showing "[Session removed externally]" in the Shell page. The idle timer in `agentTuiSpawning.js` now also checks a new `shell.js` export, `getLastInputAt()`, and skips the reap while input arrived within the last 15s. This is deliberately keyed on input *recency*, not "is a Shell viewer attached": a regular (non-external) session's socket stays bound after its viewer navigates away — only external one-shot `tuiPromptRunner.js` runs get released via `shell:release-views` — so an attachment-based guard would have permanently suppressed idle-complete for any agent glanced at once in the Shell UI. (`server/services/shell.js`, `server/services/agentTuiSpawning.js`)- **Swarm claim-issue runs now write the completion sentinel so the task actually finishes.** In `/do:next --swarm` mode the orchestrator ships every issue via a PR and never touches the working tree, so it was skipping the `.agent-done` completion sentinel — leaving the CoS task hanging with no summary as if the run never ended. Phase C of the swarm directive now explicitly instructs the orchestrator to write the sentinel (with a run summary of the issues claimed, their PRs, and merge outcomes) after the serialized merges, while still skipping the per-agent `/simplify`/push steps. (`server/services/cosTaskGenerator.js`)- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time, declaring the provider's configured models (plus the model being run) under `provider.ollama.models` with bare ids — the exact shape OpenCode's `@ai-sdk/openai-compatible` provider validates `--model ollama/<id>` against. Applied across every OpenCode spawn path (CoS CLI/TUI agents, the toolkit CLI/TUI runners, and the light fire-and-collect CLI run), and a migration backfills existing installs' `data/providers.json` so a configured model's map is persisted too. Fixes the TUI eval path for local Ollama models.- **[issue-2191] TUI agents with zero file changes are now marked failed instead of silently succeeding.** A TUI agent that idled out after showing working indicators but made no uncommitted file changes was previously finalized as `success: idle-complete` — deleting the worktree and any evidence of what happened. Now the idle-complete path checks `git status` in the worktree: if the tree is clean, it finalizes as `failure: idle-no-changes` with the TUI buffer tail as error context. Any uncommitted diff is also captured to `worktree-diff.txt` in the agent archive dir before cleanup, so post-mortems can see what (if anything) was left behind.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex f00193400d..593f54540e 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -61,6 +61,13 @@ import { execFile } from 'child_process';// Agent-specific timing/lifecycle constants (not shared with the one-shot// runner — agents stay alive much longer and write a sentinel file when done).const DEFAULT_TUI_MIN_RUNTIME_MS = 15000;+// Grace window after the last input written to the session (human paste via+// the Shell page, or our own auto-paste) before the idle reaper is allowed to+// fire again. Covers a large bracketed paste sitting in a silent reflow/commit+// window with no PTY output yet — comfortably above the paste-to-enter+// handshake windows in tuiHandshake.js (PASTE_DEADLINE_MS=10s) without+// meaningfully weakening the idle-reap protection once input truly stops.+const PASTE_INPUT_GRACE_MS = 15000;// Tail-read window for raw.txt at failure analysis. analyzeAgentFailure only// inspects the last ~200 lines, so reading the whole file (which has no upper// bound for long-running agents) would reintroduce the OOM risk the disk@@ -1043,13 +1050,21 @@ export async function spawnTuiAgent({const idleTimer = setInterval(() => {if (!promptSentAt || finalized) return;- // Don't reap a session a human is actively watching in the Shell page —- // they may be mid-paste or reading output. A big bracketed paste can sit- // in a silent reflow/commit window with no PTY output yet, which looks- // identical to "idle" to this timer otherwise (issue: paste into a live- // agent TUI got reaped mid-paste, same class of bug as #2074/#2084 but for- // an attached viewer instead of a merge-queue/review-loop wait).- if (sessionId && shellService.isSessionViewed(sessionId)) 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, which+ // looks identical to "idle" to this timer otherwise (same class of bug+ // as #2074/#2084, but for a live paste instead of a merge-queue/+ // review-loop wait). Gated on INPUT RECENCY, not "is a socket attached" —+ // a regular (non-external) Shell session keeps its socket bound after the+ // viewer navigates away (only external one-shot runs get released via+ // `shell:release-views`), so "attached" would permanently suppress+ // idle-complete for any agent glanced at once in the Shell UI. Recency+ // naturally expires once nobody is actually interacting.+ if (sessionId) {+ const lastInputAt = shellService.getLastInputAt(sessionId);+ if (lastInputAt && Date.now() - lastInputAt < PASTE_INPUT_GRACE_MS) return;+ }const runtime = Date.now() - promptSentAt;const idle = Date.now() - lastOutputAt;if (runtime < DEFAULT_TUI_MIN_RUNTIME_MS) return;diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 9586cf1e5f..66367268a8 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -9,7 +9,7 @@ vi.mock('./shell.js', () => ({killSession: vi.fn(),getSession: vi.fn(),getSessionProcess: vi.fn(),- isSessionViewed: vi.fn().mockReturnValue(false)+ getLastInputAt: vi.fn().mockReturnValue(null)}));vi.mock('./cosEvents.js', () => ({@@ -398,10 +398,10 @@ describe('spawnTuiAgent runtime', () => {vi.mocked(gitService.getStatus).mockResolvedValue({ clean: false, files: [{ path: 'file.txt', status: 'M' }] });vi.mocked(gitService.getDiff).mockResolvedValue('diff content here');- // Reset viewer-attached state: no Shell viewer bound by default. The- // viewer-attached test overrides this — clearAllMocks doesn't undo a+ // Reset input-recency state: no input recorded by default. The+ // recent-input test overrides this — clearAllMocks doesn't undo a// mockReturnValue override, so it must be reset explicitly here.- vi.mocked(shellService.isSessionViewed).mockReturnValue(false);+ vi.mocked(shellService.getLastInputAt).mockReturnValue(null);});afterEach(() => {@@ -485,14 +485,18 @@ describe('spawnTuiAgent runtime', () => {);});- // ── 1b. Idle timer must not reap a session a human is actively viewing ──────+ // ── 1b. Idle timer must not reap a session that just received real input ────// A large bracketed paste into a live agent TUI can sit in a silent// reflow/commit window with no PTY output yet, which looks identical to- // "idle" to this timer. If a viewer is attached (Shell page open on this- // session), the idle reaper must not fire at all — mirrors the guard- // tuiPromptRunner.js already has for its one-shot idle-watch timer.- it('idle timer does not reap when isSessionViewed returns true', async () => {- vi.mocked(shellService.isSessionViewed).mockReturnValue(true);+ // "idle" to this timer. While input keeps arriving recently (within+ // PASTE_INPUT_GRACE_MS), the idle reaper must not fire — gated on input+ // RECENCY rather than "is a socket attached", since a regular Shell session+ // keeps its socket bound after the viewer navigates away (only external+ // one-shot runs release on `shell:release-views`), which would otherwise+ // permanently suppress idle-complete for any agent glanced at once (caught+ // in review — see shell.test.js for the isolated getLastInputAt coverage).+ it('idle timer does not reap while getLastInputAt reports recent input', async () => {+ vi.mocked(shellService.getLastInputAt).mockImplementation(() => Date.now());runSpawn();await flushMicrotasks();diff --git a/server/services/shell.js b/server/services/shell.jsindex 10e5c7a2ff..e93951bb0b 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -343,19 +343,6 @@ export function isExternalSessionAttached(sessionId) {return !!(session && session.external && session.socket);}-/**- * True when ANY socket is currently attached to this session — an interactive- * Shell viewer or an external TUI-run viewer. Broader than- * `isExternalSessionAttached`, which only covers sessions registered via- * `registerExternalSession` (the one-shot tuiPromptRunner path); this one also- * covers regular sessions (agent-tui, plain interactive shells) viewed via- * `attachSession`, which never sets `external`.- */-export function isSessionViewed(sessionId) {- const session = shellSessions.get(sessionId);- return !!(session && session.socket);-}-/*** Public "stopped viewing" signal — the client emits this when it leaves the* Shell page (the SocketProvider socket persists across navigations, so a plain@@ -479,12 +466,25 @@ export function getSessionProcess(sessionId) {export function writeToSession(sessionId, data) {const session = shellSessions.get(sessionId);if (session) {+ session.lastInputAt = Date.now();session.pty.write(data);return true;}return false;}+/**+ * When input was last written to this session (human paste/keystrokes via+ * `shell:input`, or an internal writer like the CoS agent's auto-paste) — or+ * `null` if none yet. Unlike a socket-attached check, this recency naturally+ * expires once nobody is actually interacting, so it can't get stuck forever+ * the way "is a socket bound" can for a regular (non-external) session whose+ * viewer navigated away without disconnecting.+ */+export function getLastInputAt(sessionId) {+ return shellSessions.get(sessionId)?.lastInputAt || null;+}+/*** Resize a shell session*/diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex b4400e5b1a..b9f68df52f 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -475,36 +475,23 @@ describe('registerExternalSession / unregisterExternalSession', () => {expect(shell.isExternalSessionAttached(shellId)).toBe(false);});- it('isSessionViewed is true for a plain interactive/agent-tui session with a bound viewer (unlike isExternalSessionAttached)', () => {- // The gap isExternalSessionAttached has: it only ever returns true for- // sessions registered via registerExternalSession (external: true) — a- // regular createShellSession session (what CoS agent-tui sessions use)- // never sets `external`, so isExternalSessionAttached is permanently- // false for it even with a live viewer attached. isSessionViewed covers- // both cases by keying purely on whether a socket is bound.+ it('getLastInputAt tracks writeToSession recency, independent of socket attachment', () => {+ // Deliberately NOT keyed on socket attachment (unlike isExternalSessionAttached):+ // a regular (non-external) session's socket stays bound after its viewer+ // navigates away — only external one-shot runs get released via+ // shell:release-views — so an "is a socket attached" signal would never+ // naturally expire for those. Input recency does expire on its own once+ // nobody is actually writing to the session.const owner = makeSocket('owner');const shellId = shell.createShellSession(owner);- expect(shell.isSessionViewed(shellId)).toBe(true); // createShellSession binds the creating socket- expect(shell.isExternalSessionAttached(shellId)).toBe(false); // still false — not an external session+ expect(shell.getLastInputAt(shellId)).toBeNull(); // no input yet- shell.detachSocketSessions(owner);- expect(shell.isSessionViewed(shellId)).toBe(false);+ const before = Date.now();+ expect(shell.writeToSession(shellId, 'hello\n')).toBe(true);+ expect(shell.getLastInputAt(shellId)).toBeGreaterThanOrEqual(before);- const viewer = makeSocket('viewer');- shell.attachSession(shellId, viewer);- expect(shell.isSessionViewed(shellId)).toBe(true);- expect(shell.isExternalSessionAttached(shellId)).toBe(false); // attachSession never sets external either-- shell.detachSocketSessions(viewer);- expect(shell.isSessionViewed(shellId)).toBe(false);-- // Never true for unknown ids.- expect(shell.isSessionViewed('missing')).toBe(false);-- // Still true for an external (TUI-run) session with a viewer — isSessionViewed is a superset.- const runId = shell.registerExternalSession('run-viewed', makeFakePty(), {});- shell.attachSession(runId, viewer);- expect(shell.isSessionViewed(runId)).toBe(true);+ // Never null-coalesced weirdly for unknown ids.+ expect(shell.getLastInputAt('missing')).toBeNull();});it('releases a watched run when the same socket attaches to another session', () => {