Skip to content

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

fix: recover federation sync after stalled response bodies (#8244)

[._.]/ Adam Eivy60620de186c4
diff --git a/server/lib/README.md b/server/lib/README.md
index 6ea2084aca..fd6bd1b285 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -434,7 +434,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `xPostMedia.js` | Pure x.com/twitter.com post helpers: `parseXPostUrl(input)` (post URL → `{ statusId, canonicalUrl }`, host-gated) + `buildSyndicationUrl`/`syndicationToken` (Twitter's public unauthenticated tweet-syndication endpoint) + `extractXPostMedia(json)` (→ `{ images, video }`). Feeds the mood-board X post 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). |
| `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. |
-| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary). |
+| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary); `readPeerBody(response, method, { idleTimeoutMs? })` bounds native response body stalls and reports `PEER_BODY_IDLE_TIMEOUT`. |
| `peerProbeDiagnostics.js` | Classify federated peer probe failures (`local_refused` / `tunnel_dial` / `probe_http` / timeout / auth / DNS) so Instances UI and logs can tell a dead local forward from a tunnel dial miss from a PortOS health-details failure; messages stay redacted (no full `tc…` capabilities). |
| `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. |
| `peerUrl.js` | Build the base URL for a peer. |
diff --git a/server/lib/peerHttpClient.js b/server/lib/peerHttpClient.js
index 37f88b01a9..952cb16178 100644
--- a/server/lib/peerHttpClient.js
+++ b/server/lib/peerHttpClient.js
@@ -82,6 +82,52 @@ export async function peerFetch(url, options = {}, peer = null) {
return url.startsWith('https://') ? httpsFetch(url, finalOptions) : fetch(url, finalOptions);
}
+export const PEER_BODY_IDLE_TIMEOUT = 'PEER_BODY_IDLE_TIMEOUT';
+
+/**
+ * Consume a peer response with a deadline between received body chunks. Native
+ * fetch resolves at headers; HTTPS already buffers under the caller's request
+ * timeout, so its response methods keep their existing behavior.
+ */
+export async function readPeerBody(response, method, { idleTimeoutMs = 60000 } = {}) {
+ if (!response.body) return response[method]();
+
+ const reader = response.body.getReader();
+ const chunks = [];
+ let timer;
+ let rejectIdle;
+ const idle = new Promise((_, reject) => { rejectIdle = reject; });
+ const resetIdle = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => rejectIdle(Object.assign(
+ new Error('Peer response body stalled'), { code: PEER_BODY_IDLE_TIMEOUT }
+ )), idleTimeoutMs);
+ };
+ resetIdle();
+ try {
+ await Promise.race([
+ (async () => {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value.byteLength) {
+ chunks.push(value);
+ resetIdle();
+ }
+ }
+ })(),
+ idle,
+ ]);
+ return new Response(Buffer.concat(chunks))[method]();
+ } finally {
+ clearTimeout(timer);
+ // Cancel a stalled native fetch to release its socket; do not let transport
+ // cleanup hold the sync lock after the deadline has already fired.
+ reader.cancel().catch(() => {});
+ reader.releaseLock();
+ }
+}
+
function normalizeHeaders(headers) {
if (!headers) return {};
if (typeof headers[Symbol.iterator] === 'function') return Object.fromEntries(new Headers(headers));
diff --git a/server/lib/peerHttpClient.test.js b/server/lib/peerHttpClient.test.js
index 660e793b22..a594364bc2 100644
--- a/server/lib/peerHttpClient.test.js
+++ b/server/lib/peerHttpClient.test.js
@@ -80,6 +80,8 @@ import {
peerSocketOptions,
peerSocketOptionsFor,
peerFetch,
+ readPeerBody,
+ PEER_BODY_IDLE_TIMEOUT,
peerAuthHeaders,
__resetSelfInstanceIdForTests,
} from './peerHttpClient.js';
@@ -306,6 +308,56 @@ describe('peerHttpClient', () => {
});
});
+ describe('response body idle deadline', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it.each(['json', 'arrayBuffer'])('keeps progressing %s bytes intact beyond the header budget', async (method) => {
+ vi.useFakeTimers();
+ let stream;
+ const bytes = method === 'json'
+ ? Buffer.from(JSON.stringify({ text: 'aé🙂z' }))
+ : Buffer.from([0, 255, 128, 1, 254]);
+ const response = new Response(new ReadableStream({ start(controller) { stream = controller; } }));
+ const result = readPeerBody(response, method);
+ // Each chunk arrives inside 60s, while the total exceeds both the 15s
+ // header budget and the initial body deadline. Split UTF-8 bytes too.
+ for (const byte of bytes) {
+ await vi.advanceTimersByTimeAsync(40000);
+ stream.enqueue(Uint8Array.of(byte));
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ stream.close();
+ const value = await result;
+ expect(method === 'json' ? value : Buffer.from(value)).toEqual(
+ method === 'json' ? { text: 'aé🙂z' } : bytes
+ );
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('cancels a stalled body at the idle boundary and releases its reader', async () => {
+ vi.useFakeTimers();
+ const cancel = vi.fn();
+ const response = new Response(new ReadableStream({ cancel }));
+ const result = readPeerBody(response, 'json');
+ const rejected = expect(result).rejects.toMatchObject({ code: PEER_BODY_IDLE_TIMEOUT });
+ await vi.advanceTimersByTimeAsync(59999);
+ expect(cancel).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ await rejected;
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(response.body.locked).toBe(false);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('preserves buffered HTTPS binary and bad-JSON response behavior', async () => {
+ const bytes = Buffer.from([0, 255, 128]);
+ const response = { arrayBuffer: async () => bytes, json: async () => JSON.parse('{') };
+ expect(await readPeerBody(response, 'arrayBuffer')).toEqual(bytes);
+ await expect(readPeerBody(response, 'json')).rejects.toBeInstanceOf(SyntaxError);
+ await expect(readPeerBody(new Response('{'), 'json')).rejects.toBeInstanceOf(SyntaxError);
+ });
+ });
+
describe('peerAuthHeaders', () => {
it('returns an empty object when the peer has no credential', () => {
expect(peerAuthHeaders(null)).toEqual({});
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index e6bb79c236..8188175909 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -15,7 +15,7 @@ import { instanceEvents } from './instanceEvents.js';
import { getPeers, peerLogLabel, resolveEffectiveCategories, updatePeer } from './instances.js';
import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
-import { peerFetch } from '../lib/peerHttpClient.js';
+import { peerFetch, readPeerBody, PEER_BODY_IDLE_TIMEOUT } from '../lib/peerHttpClient.js';
import * as brainSync from './brainSync.js';
import { BRAIN_ENTITY_TYPES } from './brainStorage.js';
import * as brainSyncLog from './brainSyncLog.js';
@@ -102,18 +102,21 @@ async function withCursors(fn) {
// it outright (#5663). `peerFetch` also carries the peer HTTPS agent, so a
// self-signed tailnet peer no longer fails TLS validation on these pulls.
//
-// The timeout bounds the peerFetch call and nothing after it, so the JSON
-// decode of an already-received body can't be aborted — the same shape
-// `fetchWithTimeout` had here. (Over HTTPS the budget does still cover the
-// download itself, because the insecure-agent shim buffers the whole body
-// before it resolves; that is a property of that transport, not of this call.)
-// Contract is unchanged: null on transport failure, non-2xx, or bad JSON.
+// Headers retain their 15s budget. HTTP body reads get a separate 60s idle
+// deadline so large, progressing downloads may finish; HTTPS is already
+// buffered within the request budget. Body stalls must reach the cycle's
+// failure path instead of becoming a successful no-op.
+function handlePeerBodyError(error) {
+ if (error.code === PEER_BODY_IDLE_TIMEOUT) throw error;
+ return null;
+}
+
async function fetchPeer(peer, path) {
const url = `${peerBaseUrl(peer)}${path}`;
const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal }, peer))
.catch(() => null);
if (!res?.ok) return null;
- return res.json().catch(() => null);
+ return readPeerBody(res, 'json').catch(handlePeerBodyError);
}
/**
@@ -132,18 +135,17 @@ async function syncImageFromPeer(peer, avatarPath) {
if (exists) return;
const url = `${peerBaseUrl(peer)}${avatarPath}`;
- // Same `peerFetch` hop and the same timeout scope as fetchPeer. Non-critical
- // either way: a failure just retries next cycle.
+ // Use the same request and body-idle budgets as JSON snapshots.
const res = await withAbortTimeout(FETCH_TIMEOUT_MS, (signal) => peerFetch(url, { signal }, peer))
.catch(() => null);
if (!res?.ok) return;
- await res.arrayBuffer()
+ await readPeerBody(res, 'arrayBuffer')
.then(async (bytes) => {
await ensureDir(PATHS.images);
await writeFileGuarded(localPath, Buffer.from(bytes));
console.log(`🔄 Synced avatar image: ${filename}`);
})
- .catch(() => {});
+ .catch(handlePeerBodyError);
}
// --- Status ---
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index 012247ad23..cba9b0b449 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -1,3 +1,5 @@
+import http from 'node:http';
+import { once } from 'node:events';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock all dependencies
@@ -88,7 +90,8 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn(async () => ({})),
ensureDir: vi.fn().mockResolvedValue(),
atomicWrite: vi.fn().mockResolvedValue(),
- PATHS: { data: '/mock/data' },
+ writeFileGuarded: vi.fn().mockResolvedValue(),
+ PATHS: { data: '/mock/data', images: '/mock/data/images' },
dataPath: (name) => `/mock/data/${name}`
}));
vi.mock('../lib/asyncMutex.js', () => ({
@@ -101,6 +104,7 @@ vi.mock('../lib/peerHttpClient.js', async (importOriginal) => {
return { ...actual, peerFetch: vi.fn(actual.peerFetch) };
});
vi.mock('fs/promises', () => ({
+ access: vi.fn().mockRejectedValue(new Error('missing')),
writeFile: vi.fn().mockResolvedValue(),
rename: vi.fn().mockResolvedValue()
}));
@@ -119,7 +123,7 @@ vi.mock('./brainTombstoneGc.js', () => ({
sweepBrainTombstones: vi.fn().mockResolvedValue({ pruned: 0 }),
}));
-import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
+import { readJSONFile, atomicWrite, writeFileGuarded } from '../lib/fileUtils.js';
import { sweepTombstones } from './sharing/tombstoneGc.js';
import { sweepBrainTombstones } from './brainTombstoneGc.js';
import { getPeers } from './instances.js';
@@ -141,6 +145,7 @@ import {
BRAIN_TOMBSTONE_SWEEP_INTERVAL_MS,
} from './syncOrchestrator.js';
+const nativeFetch = globalThis.fetch;
const mockFetch = vi.fn();
describe('syncOrchestrator', () => {
@@ -186,6 +191,77 @@ describe('syncOrchestrator', () => {
});
describe('syncWithPeer', () => {
+ it('records a stalled HTTP body failure, settles progress, and allows the next sync', async () => {
+ const server = http.createServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.flushHeaders();
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const peer = { ...mockPeer, address: '127.0.0.1', port: server.address().port,
+ syncCategories: { brain: true, memory: false } };
+ let headersReceived;
+ const received = new Promise(resolve => { headersReceived = resolve; });
+ mockFetch.mockImplementationOnce(async (...args) => {
+ const response = await nativeFetch(...args);
+ headersReceived();
+ return response;
+ });
+ try {
+ const sync = syncWithPeer(peer);
+ const rejected = expect(sync).rejects.toMatchObject({ code: 'PEER_BODY_IDLE_TIMEOUT' });
+ await received;
+ await vi.advanceTimersByTimeAsync(60000);
+ await rejected;
+ expect(atomicWrite).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({
+ [peer.instanceId]: expect.objectContaining({ lastSyncError: 'Peer response body stalled' })
+ }));
+ expect(instanceEvents.emit).toHaveBeenCalledWith('sync:progress', expect.objectContaining({
+ phase: 'complete', peerId: peer.instanceId, error: 'Peer response body stalled'
+ }));
+ mockFetch.mockResolvedValue({ ok: true, json: async () => ({ changes: [], hasMore: false }) });
+ await syncWithPeer(peer);
+ expect(instanceEvents.emit.mock.calls.filter(([, event]) => event.phase === 'start')).toHaveLength(2);
+ expect(instanceEvents.emit).toHaveBeenLastCalledWith('sync:progress', expect.objectContaining({
+ phase: 'complete', error: null
+ }));
+ } finally {
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+ }
+ });
+
+ it('reports an avatar body stall without persisting partial image bytes', async () => {
+ const { applyRemote } = await import('./dataSync.js');
+ applyRemote.mockResolvedValue({ applied: true, count: 1 });
+ mockFetch.mockImplementation(async (url) => {
+ if (url.includes('/data/images/')) return new Response(new ReadableStream({}));
+ return { ok: true, json: async () => ({ data: { avatarPath: '/data/images/example.png' }, checksum: 'avatar' }) };
+ });
+ const peer = { ...mockPeer, syncCategories: { brain: false, memory: false, character: true } };
+ const sync = syncWithPeer(peer);
+ await vi.advanceTimersByTimeAsync(60000);
+ await sync;
+ expect(writeFileGuarded).not.toHaveBeenCalled();
+ expect(instanceEvents.emit).toHaveBeenLastCalledWith('sync:progress', expect.objectContaining({
+ phase: 'complete', error: 'character: Peer response body stalled'
+ }));
+ applyRemote.mockResolvedValue({ applied: false, count: 0 });
+ });
+
+ it.each([
+ ['non-success response', () => new Response('unavailable', { status: 503 })],
+ ['malformed JSON', () => new Response('{')],
+ ])('retains the no-op behavior for a %s', async (_name, response) => {
+ mockFetch.mockImplementation(async () => response());
+ const result = await syncWithPeer({ ...mockPeer, syncCategories: { brain: true, memory: false } });
+ expect(result.brain.totalApplied).toBe(0);
+ expect(applyBrainChanges).not.toHaveBeenCalled();
+ expect(instanceEvents.emit).toHaveBeenLastCalledWith('sync:progress', expect.objectContaining({
+ phase: 'complete', error: null
+ }));
+ });
+
it('skips peers without instanceId', async () => {
await syncWithPeer({ ...mockPeer, instanceId: undefined });
expect(mockFetch).not.toHaveBeenCalled();