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
defer CoS TUI idle reap while the machine is offline
Adam Eivy47e1de78efe3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b4b2b7ed77..3003c58838 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@- **[issue-3180] Agents no longer run in the PortOS folder when your app's repository path is wrong** — picking an app as the workspace (in a CoS task, or Settings → Providers → Run Prompt) and asking the agent to create a file could put the file in the PortOS directory instead of your app. If the app's Repository Path was empty, mistyped, or pointed somewhere that no longer exists, PortOS quietly fell back to its own folder and said nothing, so the run looked like it had worked. Now PortOS names the directory it chose for every run and in the CoS task log; a run whose workspace doesn't exist stops with a message telling you which path to fix; and a CoS task whose app has no usable Repository Path is blocked before the agent starts, rather than turned loose in the PortOS checkout. A path saved as `~/Projects/MyApp` is also accepted. Troubleshooting steps — including why `PORTOS_WORKSPACE_ROOTS` is unrelated to this — are in `docs/TROUBLESHOOTING.md`.- **[issue-3193] OpenCode agents now run in the app you selected, not the PortOS folder** — even with a correct Repository Path, agents on an OpenCode provider wrote their files into the PortOS directory and reported the PortOS path as their working folder. OpenCode decides where it is by reading an environment variable that describes the folder PortOS itself was started in, rather than the folder it was actually handed, so the workspace you picked was quietly ignored — only on OpenCode, which is why Codex, Claude Code, and Gemini looked fine. PortOS now sets that variable to the real working directory everywhere it starts an agent, a provider run, a TUI session, or a terminal. Troubleshooting steps for telling this apart from a mistyped Repository Path are in `docs/TROUBLESHOOTING.md`.- **[issue-3180] Agent terminals on Windows get a working environment** — the environment filter for agent shell sessions was written for macOS/Linux and dropped variables Windows needs, including `Path` itself (Windows spells it mixed-case, which the filter didn't match), plus `SystemRoot`, `ComSpec`, `TEMP`, and the per-user `APPDATA` folders where the coding CLIs keep their configuration and credentials. Windows sessions now keep those while still withholding API keys and tokens.+- **A brief internet outage no longer kills a working CoS agent.** When the machine lost its connection, a running agent's terminal went quiet — it couldn't reach the model — and after a few minutes the idle watchdog mistook that silence for a hung or finished agent and reaped it, throwing away in-progress work. PortOS now checks whether the machine is actually online before reaping an idle agent: while the connection is down, the reap is deferred and the agent is left alone to resume the moment the network returns (with a short grace so it isn't reaped in the instant between reconnecting and picking back up). Genuinely stuck agents on a healthy connection are still reaped on the same schedule as before, and the long absolute run-time ceiling still bounds an agent kept alive through a very long outage.- **An agent killed by a server restart now picks up where it left off instead of starting over.** Restarting PortOS kills every running agent mid-edit, and the task went back in the queue for a brand-new agent that built a fresh worktree from `main` — so hours of in-progress work sat on disk, untouched, while the replacement redid it from scratch. PortOS now records what the interrupted run left behind and hands the retry its actual working directory: its commits, its uncommitted edits, and its untracked files, exactly as they were. The retry is told up front that it's continuing someone else's run and to check `git status`, the commit log, and whether a PR was already opened or merged before writing any code. Work that already landed is still never resumed onto, and if the leftover folder can't be handed over for any reason the retry starts clean rather than failing to start.## Image generationdiff --git a/server/lib/README.md b/server/lib/README.mdindex 5c91cdae4c..4df171bfd3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -180,6 +180,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). || `abortTimeout.js` | `withAbortTimeout(timeoutMs, fn)` — runs `fn(signal)` under an `AbortController` that aborts after `timeoutMs` and always clears the timer on settle. Generic lifecycle helper for callers that need the insecure-agent `peerFetch` (so can't use `fetchWithTimeout`) or one signal across parallel fetches. || `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |+| `connectivity.js` | `isMachineOnline({timeoutMs?, hosts?})` — internet-reachability probe: bare TCP `connect` to public anycast resolvers on :443 (no DNS, no HTTP), resolves `true` on the first connect and `false` only after all fail; never rejects. Used by the CoS TUI idle reaper (`agentTuiSpawning.js`) so a dropped connection isn't mistaken for a hung/finished agent. || `safeUrlFetch.js` | SSRF-guarded public-URL fetch: `isPublicHttpUrlSafe`/`assertPublicHttpUrl` (scheme + blocked-host-literal via `catalogValidation.isBlockedIngestHost` + DNS-resolve), plus `fetchPublicText`/`fetchPublicBinary` (timeout, redirect revalidation, size cap) and `buildPinnedLookup`/`buildPinnedDispatcher` (the connect-time IP pin that closes the DNS-rebinding TOCTOU). Reuse instead of copying the SSRF guard for any "fetch this remote thing the user pointed us at" flow. || `pinterestFeed.js` | Pure Pinterest board RSS helpers: `normalizePinterestFeedUrl(input)` (board URL or `.rss` → `{ feedUrl, boardUrl }`, host-gated) + `parsePinterestRss(xml)` (per-pin `pinUrl`/`imageUrl`/title/description, 736x size upgrade). Feeds the mood-board Pinterest importer. || `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes* (keyed off `res` close + `writableEnded`). Plus `anyAbortSignal(signals)` — combine several signals into one (native `AbortSignal.any` with a Node-18 fallback). |diff --git a/server/lib/connectivity.js b/server/lib/connectivity.jsnew file mode 100644index 0000000000..2525843388--- /dev/null+++ b/server/lib/connectivity.js@@ -0,0 +1,58 @@+/**+ * Internet-reachability probe.+ *+ * A liveness signal answering "does this machine currently have internet?" —+ * used by the CoS TUI idle reaper so a dropped connection doesn't get mistaken+ * for a hung or finished agent (a silenced TUI looks identical either way).+ *+ * This is deliberately a bare TCP *connect* to well-known anycast endpoints on+ * :443 — NOT a DNS lookup (we dial IPs directly, so a broken resolver can't read+ * as an outage) and NOT an HTTP/TLS exchange (we only need "can packets leave").+ * It never rejects: callers use it as a gate, and a probe that failed to run is+ * not proof of anything, so the promise always resolves to a boolean.+ */++import net from 'net';++// Two independent public resolvers so one operator blocking a single IP (or one+// resolver having a blip) doesn't read as a full outage — reachable if EITHER+// connects.+export const DEFAULT_PROBE_HOSTS = [+ { host: '1.1.1.1', port: 443 }, // Cloudflare+ { host: '8.8.8.8', port: 443 }, // Google+];++export const DEFAULT_PROBE_TIMEOUT_MS = 3000;++// Resolve when a single host connects; reject when it errors or times out.+// Always tears the socket down (listeners + fd) on every terminal path.+function probeHost({ host, port }, timeoutMs) {+ return new Promise((resolve, reject) => {+ const socket = net.connect({ host, port });+ const done = (ok) => {+ socket.removeAllListeners();+ socket.destroy();+ ok ? resolve() : reject(new Error('unreachable'));+ };+ socket.setTimeout(timeoutMs);+ socket.once('connect', () => done(true));+ socket.once('timeout', () => done(false));+ socket.once('error', () => done(false));+ });+}++/**+ * Resolve `true` as soon as ANY probe host connects; resolve `false` only after+ * every probe has errored or timed out. Fast even when fully offline (a dead+ * network errors/times out quickly per host). Never rejects.+ *+ * @param {{ timeoutMs?: number, hosts?: Array<{host:string,port:number}> }} [opts]+ * @returns {Promise<boolean>}+ */+export function isMachineOnline({ timeoutMs = DEFAULT_PROBE_TIMEOUT_MS, hosts = DEFAULT_PROBE_HOSTS } = {}) {+ if (!Array.isArray(hosts) || hosts.length === 0) return Promise.resolve(false);+ // Promise.any resolves on the first fulfilled probe and rejects (AggregateError)+ // only when every probe fails — exactly the "true on first connect, false only+ // after all fail" contract. The reject handler swallows it so we never throw.+ return Promise.any(hosts.map((h) => probeHost(h, timeoutMs))).then(() => true, () => false);+}diff --git a/server/lib/connectivity.test.js b/server/lib/connectivity.test.jsnew file mode 100644index 0000000000..dff9a2502b--- /dev/null+++ b/server/lib/connectivity.test.js@@ -0,0 +1,67 @@+import { describe, it, expect, afterEach } from 'vitest';+import net from 'net';+import { isMachineOnline } from './connectivity.js';++// Spin up a real loopback TCP server so the "connects" path is exercised+// without hitting the public internet; a closed loopback port gives a fast,+// deterministic "refused" for the failure path.+function listenOnEphemeralPort() {+ return new Promise((resolve) => {+ const server = net.createServer((socket) => socket.end());+ server.listen(0, '127.0.0.1', () => resolve({ server, port: server.address().port }));+ });+}++async function findClosedPort() {+ // Bind then immediately release so nothing is listening on the returned port.+ const { server, port } = await listenOnEphemeralPort();+ await new Promise((r) => server.close(r));+ return port;+}++describe('isMachineOnline', () => {+ const servers = [];+ afterEach(async () => {+ while (servers.length) {+ const s = servers.pop();+ await new Promise((r) => s.close(r));+ }+ });++ it('resolves true when a probe host connects', async () => {+ const { server, port } = await listenOnEphemeralPort();+ servers.push(server);+ const online = await isMachineOnline({ hosts: [{ host: '127.0.0.1', port }], timeoutMs: 1000 });+ expect(online).toBe(true);+ });++ it('resolves false when every probe host fails', async () => {+ const closed = await findClosedPort();+ const online = await isMachineOnline({ hosts: [{ host: '127.0.0.1', port: closed }], timeoutMs: 1000 });+ expect(online).toBe(false);+ });++ it('resolves true if ANY host connects even when another fails', async () => {+ const { server, port } = await listenOnEphemeralPort();+ servers.push(server);+ const closed = await findClosedPort();+ const online = await isMachineOnline({+ hosts: [{ host: '127.0.0.1', port: closed }, { host: '127.0.0.1', port }],+ timeoutMs: 1000,+ });+ expect(online).toBe(true);+ });++ it('resolves false (never rejects) for an empty host list', async () => {+ await expect(isMachineOnline({ hosts: [] })).resolves.toBe(false);+ });++ it('resolves false within the timeout for an unreachable (non-routable) host', async () => {+ // 192.0.2.1 is TEST-NET-1 (RFC 5737) — guaranteed non-routable, so the+ // connect never completes and must resolve false via the timeout path.+ const start = Date.now();+ const online = await isMachineOnline({ hosts: [{ host: '192.0.2.1', port: 443 }], timeoutMs: 300 });+ expect(online).toBe(false);+ expect(Date.now() - start).toBeLessThan(3000);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex c173dfed8f..cd178c8831 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -166,6 +166,7 @@ export * from './ytdlp.js';// === Networking ===export * from './abortTimeout.js';+export * from './connectivity.js';export * from './fetchWithTimeout.js';export * from './requestAbort.js';export * from './httpClient.js';diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 1a2ab881d7..08851353fa 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -29,6 +29,7 @@ import { shellQuote } from '../lib/shellQuote.js';import { resolveCliModel, buildEffortArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';+import { isMachineOnline } from '../lib/connectivity.js';import { isAntigravityCommand } from '../lib/antigravity.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,@@ -80,6 +81,22 @@ const DEFAULT_TUI_MIN_RUNTIME_MS = 15000;// meaningfully weakening the idle-reap protection once input truly stops.const PASTE_INPUT_GRACE_MS = 15000;+// Connectivity gate for the idle reaper. When the machine loses internet, a+// live TUI goes silent (it can't reach the model) in a way that's+// indistinguishable from a hung or finished agent to the idle timer — so an+// outage would reap an agent that's only blocked on the network. We keep a+// cheap reachability reading fresh only in the LEAD window right before the+// idle deadline and DEFER the reap while offline. `RECHECK_MS` throttles probes+// to at most one per interval; `LEAD_MS` is how far before the (possibly+// extended) reap deadline probing begins — so a healthy, chatty agent is never+// probed and a drifting one has a confirmed reading in hand at its reap tick,+// without probing for the whole window. This does NOT weaken the hung-agent+// safety net: a stuck agent on a healthy connection still reaps on schedule,+// and the max-runtime backstop still bounds an agent kept alive through a long+// outage.+const CONNECTIVITY_RECHECK_MS = 10000;+const CONNECTIVITY_PROBE_LEAD_MS = 20000;+// Output buffering/spooling (createOutputSpooler) and failure-analysis /// worktree-inspection helpers (readFileTail, worktreeHasChanges,// captureWorktreeDiff, resolveErrorAnalysis, RAW_TAIL_ANALYSIS_BYTES) live in@@ -230,6 +247,7 @@ export async function spawnTuiAgent({cleanupWorktreeFn,isTruthyMetaFn,leanMode = false,+ checkOnlineFn = isMachineOnline,}) {const outputFile = join(agentDir, 'output.txt');// Raw PTY bytes spool to disk continuously rather than accumulate in-memory.@@ -336,6 +354,36 @@ export async function spawnTuiAgent({let lastOutputAt = Date.now();let sessionId = null;+ // Idle-reaper connectivity gate (see CONNECTIVITY_* constants). `online`+ // starts optimistically true so the happy path reaps on schedule without+ // waiting on a probe; it only ever flips to false once a probe confirms an+ // outage, at which point the idle reaper defers. Probing is started by the+ // idle timer only in the LEAD window before the reap deadline (not the whole+ // idle window), so a confirmed reading is in hand at the reap tick and a busy+ // agent is never probed.+ const connectivity = { online: true, checking: false, lastCheckAt: 0, loggedOffline: false };+ const refreshConnectivity = () => {+ if (connectivity.checking) return;+ if (Date.now() - connectivity.lastCheckAt < CONNECTIVITY_RECHECK_MS) return;+ connectivity.checking = true;+ connectivity.lastCheckAt = Date.now();+ Promise.resolve()+ .then(() => checkOnlineFn())+ .then((online) => {+ if (finalized) return;+ // A probe that failed to RUN (threw) is not proof of an outage — only+ // an explicit `false` result flips us offline; anything else stays online.+ const nowOnline = online !== false;+ // Reconnect grace: on the offline→online transition, give the CLI a+ // fresh idle window to notice the network is back and resume before the+ // reaper can fire — otherwise we'd reap in the gap before it repaints.+ if (nowOnline && connectivity.online === false) lastOutputAt = Date.now();+ connectivity.online = nowOnline;+ })+ .catch(() => {})+ .finally(() => { connectivity.checking = false; });+ };+// Bounded post-paste accumulator. Lives only while pasteEnterTimer is// running (a few seconds at most), so the in-memory cost is bounded by// however much the TUI emits during the paste-marker window — typically@@ -1141,7 +1189,26 @@ export async function spawnTuiAgent({: reviewLoop.active? Math.max(tuiConfig.idleTimeoutMs, REVIEW_LOOP_IDLE_TIMEOUT_MS): tuiConfig.idleTimeoutMs;+ // Once within the LEAD window of the (possibly extended) reap deadline, keep+ // a reachability reading fresh (throttled, non-blocking) so the gate below+ // can read it synchronously and won't reap an agent that's only silent+ // because the machine lost internet. Gating on the effective deadline (not a+ // fixed lead off the base window) keeps a long merge-queue/review-loop idle+ // from probing for its whole 15-min window.+ if (idle >= effectiveIdleTimeoutMs - CONNECTIVITY_PROBE_LEAD_MS) refreshConnectivity();if (idle >= effectiveIdleTimeoutMs) {+ // An internet outage silences a live TUI exactly like a hung or finished+ // agent looks to this timer. If a recent probe says we're offline, DEFER+ // the reap — the agent is only blocked on the network and resumes when it+ // returns. (The max-runtime backstop still bounds a very long outage.)+ if (!connectivity.online) {+ if (!connectivity.loggedOffline) {+ emitLog('info', `📡 TUI agent ${agentId} idle past its window but the machine appears offline — deferring reap until connectivity returns`, { agentId });+ connectivity.loggedOffline = true;+ }+ return;+ }+ connectivity.loggedOffline = false;// Reaped AFTER the extended merge-queue grace elapsed: the orchestrator// almost certainly died mid-merge with PRs opened/merged-but-uncleaned.// Surface it as a needs-manual-finish FAILURE rather than the silentdiff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 576ba99df1..9fcace03f8 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -402,6 +402,10 @@ describe('spawnTuiAgent runtime', () => {cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),isTruthyMetaFn: (v) => !!v};+ // Default the connectivity probe to "online" so the idle reaper behaves+ // exactly as before for every existing test — no real network I/O. The+ // outage tests below inject their own resolver.+ const checkOnlineFn = overrides.checkOnlineFn ?? vi.fn().mockResolvedValue(true);return spawnTuiAgent({agentId,task,@@ -414,6 +418,7 @@ describe('spawnTuiAgent runtime', () => {agentDir,executionId,laneName,+ checkOnlineFn,...helpers,});}@@ -785,14 +790,11 @@ describe('spawnTuiAgent runtime', () => {//// Drives the same PTY sequence as the idle-no-changes test: prompt echo →// submit → an ADVANCING work counter → idle out, with a clean worktree.- async function driveIdleWithWorkOnCleanTree(overrides) {- vi.mocked(gitService.getStatus).mockResolvedValue({ clean: true, files: [] });- vi.mocked(gitService.getDiff).mockResolvedValue('');-- let resolveComplete;- const completeDone = new Promise((r) => { resolveComplete = r; });- vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });-+ // Shared PTY choreography: boot banner → prompt echo (paste verify) → submit+ // Enter → an ADVANCING work counter (sets workActivity.active and+ // lastOutputAt > promptSentAt). Leaves fake timers running at the second+ // counter; callers add their own tail (idle advance + git/finalize/assertions).+ async function driveToSubmittedAndWorking(overrides = {}) {runSpawn(overrides);await flushMicrotasks();@@ -811,6 +813,17 @@ describe('spawnTuiAgent runtime', () => {await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));await vi.advanceTimersByTimeAsync(800);await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));+ }++ async function driveIdleWithWorkOnCleanTree(overrides) {+ vi.mocked(gitService.getStatus).mockResolvedValue({ clean: true, files: [] });+ vi.mocked(gitService.getDiff).mockResolvedValue('');++ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ await driveToSubmittedAndWorking(overrides);await vi.advanceTimersByTimeAsync(21000);vi.useRealTimers();@@ -891,6 +904,73 @@ describe('spawnTuiAgent runtime', () => {);});+ // ── 1d. Connectivity-aware idle reaper ──────────────────────────────────────+ // When the machine loses internet, a live TUI goes silent (it can't reach the+ // model) exactly like a hung or finished agent looks to the idle timer — so an+ // outage would reap an agent that's only blocked on the network. The reaper is+ // the ONLY liveness signal for a genuinely hung TUI, so it isn't removed —+ // it's gated on a reachability probe and DEFERS while offline.+ const OFFLINE_TUI_CONFIG = {+ command: 'codex',+ args: [],+ commandLine: 'codex',+ promptDelayMs: 100,+ // A larger idle window than the fast default so the lead probe+ // (idleTimeoutMs/2, capped) resolves on an earlier 5s tick than the reap+ // tick — mirroring how a real 3-minute window spans many probe ticks.+ idleTimeoutMs: 15000,+ maxRuntimeMs: 3600000,+ };++ async function driveToIdleSilence({ checkOnlineFn, silenceMs = 45000 }) {+ await driveToSubmittedAndWorking({ tuiConfig: OFFLINE_TUI_CONFIG, checkOnlineFn });+ // Go silent well past the 15s idle window (several 5s ticks) so the lead+ // probe fires and resolves before the reap tick.+ await vi.advanceTimersByTimeAsync(silenceMs);+ await flushMicrotasks();+ }++ it('idle reaper DEFERS while the machine is offline (does not reap an agent that lost internet)', async () => {+ const checkOnlineFn = vi.fn().mockResolvedValue(false);+ await driveToIdleSilence({ checkOnlineFn });++ expect(checkOnlineFn).toHaveBeenCalled(); // the reachability probe fired+ expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled(); // …and the reap was deferred+ });++ it('idle reaper still reaps on the SAME window when online (deferral is outage-specific, not a timing artifact)', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ // dirty tree (default git mock) → idle-complete success+ await driveToIdleSilence({ checkOnlineFn: vi.fn().mockResolvedValue(true) });+ vi.useRealTimers();+ await completeDone;++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ success: true, completionReason: 'idle-complete' })+ );+ });++ it('idle reaper resumes reaping once connectivity RETURNS (deferral is not permanent)', async () => {+ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ // Offline for the first probe, then the connection comes back. The reap is+ // deferred through the outage, then fires after the reconnect grace window.+ const checkOnlineFn = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);+ await driveToIdleSilence({ checkOnlineFn, silenceMs: 90000 });+ vi.useRealTimers();+ await completeDone;++ expect(checkOnlineFn.mock.calls.length).toBeGreaterThan(1); // probed again after the outage+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ success: true, completionReason: 'idle-complete' })+ );+ });+// ── 1c. Absolute wall-clock backstop reaps a busy-but-stuck agent ───────────// The idle reaper resets on every PTY chunk, so an agent whose working counter// keeps repainting through a stalled provider retry never idles out and would