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
refactor: extract withAbortTimeout helper for duplicated peer-fetch timeout boilerplate (#1839)
[._.]/ Adam Eivy00c62cd9fccb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c75a9c7669..e11a7eb8a6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,6 +26,7 @@## Internal+- **Extracted a shared `withAbortTimeout` helper for the duplicated peer-fetch timeout boilerplate** — the `new AbortController()` + `setTimeout(abort)` + `finally{clearTimeout}` triple was hand-rolled at 12 federation/probe call sites (4 in `instances.js`, plus `peerSocketRelay`, `peerSync`, `peerCosSync`×2, `peerSyncAssets`, `peerSyncPush`, `peerMediaLibrarySync`, `sidecarSync`). It can't reuse `fetchWithTimeout` because `peerFetch` needs the Tailnet-insecure HTTPS agent. The new `server/lib/abortTimeout.js` `withAbortTimeout(timeoutMs, fn)` runs `fn(signal)` under a timed `AbortController` and always clears the timer on settle — covering both the headers-only idiom (peer-sync pulls/pushes, body separately size-capped) and the whole-operation idiom (`probePeer` shares one signal across three parallel fetches and their body reads). The `peerFetch` call stays in each module (so existing test mocks/assertions are unchanged); behavior-preserving. (#1839)- **Replaced aiToolkit runner monkey-patching with declared extension points** — `server/index.js` previously reached into the toolkit runner's private surface, overwriting `executeCliRun`/`executeTuiRun` and re-wrapping `stopRun`/`isRunActive`/`deleteRun` to consult an ad-hoc `_portosActiveRuns` map, plus inlining a 34-line update-marker IIFE in bootstrap. The toolkit runner (`server/lib/aiToolkit/runner.js`) now exposes `setCliRunner()`/`setTuiRunner()` and an external-run registry (`registerExternalRun`/`unregisterExternalRun`/`hasExternalRun`) that its own `stopRun`/`isRunActive`/`deleteRun` consult first — so the host registers its CLI/TUI runners through a documented contract instead of mutating private props, and adding a new lifecycle method no longer requires a matching monkey-patch. `server/services/runner.js` tracks its child processes via the registry, and the update-marker read/validate/record/cleanup lifecycle moved into a unit-tested `processUpdateMarker()` in `server/services/updateChecker.js`. Behavior-preserving; the aiToolkit override contract (`server/lib/aiToolkit/CLAUDE.md`) is updated to match. (#1834)- **Decomposed two remaining large files: `server/routes/meatspace.js` + `server/services/videoGen/local.js`** — the 1,069-line `meatspace.js` router (14 health sub-domains, each backed by its own service import) is split one concern per file (`meatspaceCoreRoutes.js` overview/config/birth-date/death-clock/LEV, `meatspaceAlcoholRoutes.js`, `meatspaceNicotineRoutes.js`, `meatspaceHealthRoutes.js` blood/body/BP/workouts/epigenetic/eyes, `meatspacePostRoutes.js` POST drills + training + memory builder, `meatspaceCalendarRoutes.js` life calendar/activities/events, `meatspaceExportRoutes.js` MortalLoom export), assembled by a thin `meatspace.js` barrel that mounts each under `/api/meatspace` — the same pattern `routes/cos.js`/`routes/brain.js` use; the split is wiring-only (the 70-route surface is byte-identical, verified). The 1,805-line `videoGen/local.js` had its BYOV runtime management (venv/helper-script path constants, `BYOV_RUNTIME_INFO`, install/ready/fingerprint probes) extracted to `videoGen/runtimes.js` and its render-history I/O (`loadHistory`/`saveHistory`) to `videoGen/history.js`; `local.js` keeps generation + post-processing and re-exports the extracted surface so every existing deep import (`from '../videoGen/local.js'`) keeps resolving unchanged (all 30 prior exports preserved, verified). (#1833)- **Decomposed `server/routes/brain.js` (1,149-line router covering 13 sub-domains)** — the monolithic Brain router that mixed capture/inbox, four entity CRUD collections + memories, digest/review, settings/summary, links + buckets, graph, federation sync, and the daily log is now split one concern per file (`brainCapture.js`, `brainCrud.js`, `brainDigest.js`, `brainSettings.js`, `brainLinks.js`, `brainGraph.js`, `brainSync.js`, `brainDailyLog.js`), assembled by a thin `brain.js` barrel that mounts each sub-router under `/api/brain` — the same pattern `routes/cos.js` already uses. The split is wiring-only: route paths, ordering (literal-before-`:id` routes stay within their owning sub-router), validation, and the barrel's default export are unchanged, so `server/index.js` and the existing `brain.test.js` (105 tests) pass without edits. (#1832)diff --git a/server/lib/README.md b/server/lib/README.mdindex 7481a05242..a4e7cec82d 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -150,6 +150,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `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. || `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). 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. |diff --git a/server/lib/abortTimeout.js b/server/lib/abortTimeout.jsnew file mode 100644index 0000000000..3ca65f1c0c--- /dev/null+++ b/server/lib/abortTimeout.js@@ -0,0 +1,24 @@+// Generic AbortController + timeout lifecycle helper.+//+// `peerFetch` (and Node's `fetch` generally) has no built-in timeout, so callers+// repeatedly hand-rolled the `new AbortController()` + `setTimeout(abort)` ++// `finally{clearTimeout}` triple. `withAbortTimeout` encapsulates that lifecycle+// so the call sites only express what they actually care about: "run this, with+// this signal, bounded to this many ms."++/**+ * Run `fn(signal)` under an `AbortController` that fires after `timeoutMs`,+ * always clearing the timer once `fn` settles (resolve OR reject). `fn`'s return+ * value (or rejection) passes straight through. The timeout bounds the whole+ * callback, so a caller decides what it covers by what it awaits inside `fn` —+ * just the fetch, or the fetch plus its body read.+ */+export async function withAbortTimeout(timeoutMs, fn) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ return await fn(controller.signal);+ } finally {+ clearTimeout(timer);+ }+}diff --git a/server/lib/abortTimeout.test.js b/server/lib/abortTimeout.test.jsnew file mode 100644index 0000000000..d00081bdd0--- /dev/null+++ b/server/lib/abortTimeout.test.js@@ -0,0 +1,28 @@+import { describe, it, expect } from 'vitest';+import { withAbortTimeout } from './abortTimeout.js';++describe('withAbortTimeout', () => {+ it('passes a live signal to fn and leaves it un-aborted when fn settles in time', async () => {+ let captured;+ const result = await withAbortTimeout(10_000, async (signal) => {+ captured = signal;+ return 'ok';+ });+ expect(result).toBe('ok');+ expect(captured).toBeInstanceOf(AbortSignal);+ expect(captured.aborted).toBe(false);+ });++ it('aborts the signal when fn outlives the timeout', async () => {+ const aborted = await withAbortTimeout(20, (signal) => new Promise((resolve) => {+ signal.addEventListener('abort', () => resolve(signal.aborted));+ }));+ expect(aborted).toBe(true);+ });++ it('propagates the rejection from fn (and still clears the timer)', async () => {+ await expect(+ withAbortTimeout(10_000, async () => { throw new Error('boom'); })+ ).rejects.toThrow('boom');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex ce34d43d3f..a99ca861d0 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -137,6 +137,7 @@ export * from './processEnv.js';export * from './pythonSetup.js';// === Networking ===+export * from './abortTimeout.js';export * from './fetchWithTimeout.js';export * from './requestAbort.js';export * from './httpClient.js';diff --git a/server/services/instances.js b/server/services/instances.jsindex 3155ce2d8b..8ec078e1c4 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -15,6 +15,7 @@ import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';import { DEFAULT_PEER_PORT } from '../lib/ports.js';import { peerBaseUrl } from '../lib/peerUrl.js';import { peerFetch } from '../lib/peerHttpClient.js';+import { withAbortTimeout } from '../lib/abortTimeout.js';import { getSelfHost } from '../lib/peerSelfHost.js';import { autoSubscribePeerToAllRecords } from './sharing/recordEvents.js';@@ -557,8 +558,6 @@ export function enqueueReciprocalSync(peerId) {export async function probePeer(peer) {const baseUrl = peerBaseUrl(peer);- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);const previousStatus = peer.status;let status, lastHealth, lastSeen, remoteInstanceId, remoteVersion, remoteApps, remoteSyncSeqs;@@ -574,12 +573,14 @@ export async function probePeer(peer) {const forPeerQs = typeof ourInstanceId === 'string' && ourInstanceId && ourInstanceId !== UNKNOWN_INSTANCE_ID? `?forPeer=${encodeURIComponent(ourInstanceId)}`: '';- try {+ // One shared abort signal spans all three parallel fetches AND their body+ // reads, so a single PROBE_TIMEOUT_MS bounds the whole probe.+ await withAbortTimeout(PROBE_TIMEOUT_MS, async (signal) => {// Fetch health details, apps, and sync status in parallelconst [healthRes, appsRes, syncRes] = await Promise.all([- peerFetch(`${baseUrl}/api/system/health/details`, { signal: controller.signal }, peer),- peerFetch(`${baseUrl}/api/apps`, { signal: controller.signal }, peer).catch(() => null),- peerFetch(`${baseUrl}/api/instances/sync-status${forPeerQs}`, { signal: controller.signal }, peer).catch(() => null)+ peerFetch(`${baseUrl}/api/system/health/details`, { signal }, peer),+ peerFetch(`${baseUrl}/api/apps`, { signal }, peer).catch(() => null),+ peerFetch(`${baseUrl}/api/instances/sync-status${forPeerQs}`, { signal }, peer).catch(() => null)]);if (!healthRes.ok) {const err = new Error(`HTTP ${healthRes.status}`);@@ -604,15 +605,13 @@ export async function probePeer(peer) {if (syncRes?.ok) {remoteSyncSeqs = await syncRes.json().catch(() => null);}- } catch (err) {+ }).catch((err) => {console.log(`⚠️ Probe failed for ${baseUrl}: ${classifyProbeError(err, peer)}`);status = 'offline';authRequired = err?.httpStatus === 401 || err?.httpStatus === 403;lastHealth = peer.lastHealth; // preserve last knownlastSeen = peer.lastSeen;- } finally {- clearTimeout(timeout);- }+ });const stored = await withData(async (data) => {const entry = data.peers.find(p => p.id === peer.id);@@ -695,18 +694,10 @@ export async function queryPeer(id, apiPath) {if (!peer) return { error: 'Peer not found' };const url = `${peerBaseUrl(peer)}${apiPath}`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);-- try {- const res = await peerFetch(url, { signal: controller.signal }, peer);- const json = await res.json();- return { success: true, data: json };- } catch (err) {- return { error: `Failed to query peer: ${err.message}` };- } finally {- clearTimeout(timeout);- }+ return withAbortTimeout(PROBE_TIMEOUT_MS, async (signal) => {+ const res = await peerFetch(url, { signal }, peer);+ return { success: true, data: await res.json() };+ }).catch((err) => ({ error: `Failed to query peer: ${err.message}` }));}// --- Announce (Bidirectional Registration) ---@@ -798,9 +789,7 @@ async function announceSelf(peer) {const selfHost = getSelfHost();const url = `${peerBaseUrl(peer)}/api/instances/peers/announce`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);- try {+ await withAbortTimeout(PROBE_TIMEOUT_MS, async (signal) => {const res = await peerFetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -810,7 +799,7 @@ async function announceSelf(peer) {name: data.self.name,host: selfHost}),- signal: controller.signal+ signal}, peer);if (res.ok) {console.log(`🌐 Announced self to ${url}`);@@ -818,11 +807,9 @@ async function announceSelf(peer) {} else {console.log(`🌐 Announce to ${url} failed: HTTP ${res.status}`);}- } catch (err) {+ }).catch((err) => {console.log(`🌐 Announce to ${url} unreachable: ${err.message}`);- } finally {- clearTimeout(timeout);- }+ });}export async function connectPeer(id) {@@ -1013,9 +1000,7 @@ export async function requestReciprocalSync(peer, categories, { fullSync } = {})// caller didn't communicate a full-sync state at all (legacy direct callers).if (!sanitized && fullSync === undefined) return { ok: false, reason: 'no-categories' };const url = `${peerBaseUrl(peer)}/api/instances/peers/sync-categories`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);- try {+ return withAbortTimeout(PROBE_TIMEOUT_MS, async (signal) => {const res = await peerFetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -1025,7 +1010,7 @@ export async function requestReciprocalSync(peer, categories, { fullSync } = {})// the all-on syncCategories map we sent. syncCategories defaults to {} so// the receiver's required-object schema still parses a fullSync-only send.body: JSON.stringify({ instanceId: self.instanceId, syncCategories: sanitized || {}, fullSync: fullSync === true }),- signal: controller.signal+ signal}, peer);if (res.ok) {const enabledList = sanitized ? Object.keys(sanitized).filter(k => sanitized[k]).join(',') : '';@@ -1034,11 +1019,7 @@ export async function requestReciprocalSync(peer, categories, { fullSync } = {})}// 404 = peer predates this endpoint; not an error worth surfacing loudly.return { ok: false, reason: `http-${res.status}` };- } catch (err) {- return { ok: false, reason: err.message };- } finally {- clearTimeout(timeout);- }+ }).catch((err) => ({ ok: false, reason: err.message }));}async function markDirection(peerId, direction) {diff --git a/server/services/peerSocketRelay.js b/server/services/peerSocketRelay.jsindex 6913914f0c..64ca945da0 100644--- a/server/services/peerSocketRelay.js+++ b/server/services/peerSocketRelay.js@@ -9,6 +9,7 @@ import { io } from 'socket.io-client';import { instanceEvents } from './instanceEvents.js';import { peerBaseUrl } from '../lib/peerUrl.js';import { peerFetch, peerSocketOptionsFor } from '../lib/peerHttpClient.js';+import { withAbortTimeout } from '../lib/abortTimeout.js';// Map<peerId, { socket, agents: Map<agentId, agent>, peer }>const peerConnections = new Map();@@ -102,11 +103,8 @@ export function connectToPeer(peer) {async function fetchPeerAgents(conn) {const { peer } = conn;const url = `${peerBaseUrl(peer)}/api/cos/agents`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), CONNECT_TIMEOUT_MS);-- try {- const res = await peerFetch(url, { signal: controller.signal }, peer);+ await withAbortTimeout(CONNECT_TIMEOUT_MS, async (signal) => {+ const res = await peerFetch(url, { signal }, peer);if (!res.ok) return;const data = await res.json();const agents = data.running || data.agents || [];@@ -119,11 +117,9 @@ async function fetchPeerAgents(conn) {agents: Array.from(conn.agents.values())});console.log(`🔗 Peer ${peer.name}: ${agents.length} active agent(s)`);- } catch {+ }).catch(() => {// Silent — agents will populate via socket events- } finally {- clearTimeout(timeout);- }+ });}/**diff --git a/server/services/sharing/peerCosSync.js b/server/services/sharing/peerCosSync.jsindex 99e5272a7f..2ccb935159 100644--- a/server/services/sharing/peerCosSync.js+++ b/server/services/sharing/peerCosSync.js@@ -17,6 +17,7 @@ import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';import { getPeers } from '../instances.js';import {@@ -239,10 +240,8 @@ export async function syncCosHistoryFromPeer(peer) {cosHistorySweepInFlight.add(peer.instanceId);try {const url = `${peerBaseUrl(peer)}/api/peer-sync/cos-history-manifest`;- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);- const res = await peerFetch(url, { signal: controller.signal, maxBytes: COS_HISTORY_MANIFEST_MAX_BYTES }, peer)- .finally(() => clearTimeout(timeoutId))+ const res = await withAbortTimeout(ASSET_PULL_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes: COS_HISTORY_MANIFEST_MAX_BYTES }, peer)).catch(() => null);if (!res || !res.ok) return { pulled: 0, skipped: 'unreachable' };const declaredLen = Number(res.headers?.get?.('content-length'));@@ -459,10 +458,8 @@ export async function syncCosTasksFromPeer(peer) {cosTasksSweepInFlight.add(peer.instanceId);try {const url = `${peerBaseUrl(peer)}/api/peer-sync/cos-tasks`;- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);- const res = await peerFetch(url, { signal: controller.signal, maxBytes: COS_TASKS_MAX_BYTES }, peer)- .finally(() => clearTimeout(timeoutId))+ const res = await withAbortTimeout(ASSET_PULL_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes: COS_TASKS_MAX_BYTES }, peer)).catch(() => null);if (!res || !res.ok) return { merged: 0, skipped: 'unreachable' };const declaredLen = Number(res.headers?.get?.('content-length'));diff --git a/server/services/sharing/peerMediaLibrarySync.js b/server/services/sharing/peerMediaLibrarySync.jsindex 41125c6024..505dc95859 100644--- a/server/services/sharing/peerMediaLibrarySync.js+++ b/server/services/sharing/peerMediaLibrarySync.js@@ -17,6 +17,7 @@ import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';import { sanitizeAssetFilename } from './buckets.js';import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';import { getPeers } from '../instances.js';@@ -228,10 +229,8 @@ export async function syncMediaLibraryFromPeer(peer) {librarySweepInFlight.add(peer.instanceId);try {const url = `${peerBaseUrl(peer)}/api/peer-sync/library-manifest`;- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);- const res = await peerFetch(url, { signal: controller.signal, maxBytes: MEDIA_LIBRARY_MANIFEST_MAX_BYTES }, peer)- .finally(() => clearTimeout(timeoutId))+ const res = await withAbortTimeout(ASSET_PULL_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes: MEDIA_LIBRARY_MANIFEST_MAX_BYTES }, peer)).catch(() => null);if (!res || !res.ok) return { pulled: 0, skipped: 'unreachable' };// Enforce the manifest cap before buffering the body. peerFetch's `maxBytes`diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 840720dab0..3c48b80e9e 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -22,6 +22,7 @@*/import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';import { withBaseHashFlushBatch } from '../../lib/conflictJournal.js';import { recordEvents, registerSubscriptionAdapter } from './recordEvents.js';import { getInstanceId, getPeers, enqueueReciprocalSync, UNKNOWN_INSTANCE_ID } from '../instances.js';@@ -779,14 +780,12 @@ export async function pullRecordFromPeer(peerId, recordKind, recordId) {// so without this a stalled peer would hang the pull (and the UI action)// indefinitely. Mirrors the push path; an abort rejects → caught as null →// 'peer-unreachable'.- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), PUSH_TIMEOUT_MS);// maxBytes caps the HTTPS shim's in-memory buffering (see lib/httpClient.js);// a buggy/misbehaving peer streaming an oversized body is aborted mid-stream// rather than buffered whole. The shim rejects with an "exceed" Error.let tooLarge = false;- const res = await peerFetch(url, { signal: controller.signal, maxBytes: RECORD_PAYLOAD_MAX_BYTES }, peer)- .finally(() => clearTimeout(timeoutId))+ const res = await withAbortTimeout(PUSH_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes: RECORD_PAYLOAD_MAX_BYTES }, peer)).catch((err) => {if (err?.message?.includes('exceed')) {tooLarge = true; // HTTPS shim tripped the cap — same condition as the Content-Length checkdiff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex bc24a89623..951ecb39c0 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -17,6 +17,7 @@ import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';import { getOrComputeImageSha256, sidecarGenParamsHash } from '../../lib/assetHash.js';import { generateThumbnail } from '../../lib/ffmpeg.js';import { sanitizeRecordForWire } from '../../lib/syncWire.js';@@ -652,13 +653,11 @@ export async function pullMissingAssetsFromPeer(senderInstanceId, missingAssets)* runs. `label` is the filename used in log lines.*/export async function fetchCappedAssetBuffer(peer, url, label, maxBytes, { allowEmpty = false } = {}) {- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);// maxBytes propagates into the HTTPS shim's streaming cap (see// server/lib/httpClient.js); the plain-HTTP path falls back to the// post-resolve content-length checks below (serve-static always sets it).- const res = await peerFetch(url, { signal: controller.signal, maxBytes }, peer)- .finally(() => clearTimeout(timeoutId))+ const res = await withAbortTimeout(ASSET_PULL_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes }, peer)).catch((err) => {if (err?.message?.includes('exceed')) {console.log(`⚠️ peerSync: ${label} exceeded asset size cap — ${err.message}`);diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.jsindex 27ec82daec..3ce149e562 100644--- a/server/services/sharing/peerSyncPush.js+++ b/server/services/sharing/peerSyncPush.js@@ -15,6 +15,7 @@ import { isStr } from '../../lib/storyBible.js';import { isPlainObject } from '../../lib/objects.js';import { peerBaseUrl } from '../../lib/peerUrl.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';import { sanitizeRecordForWire } from '../../lib/syncWire.js';import { setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';import { sanitizeAssetFilename } from './buckets.js';@@ -219,23 +220,20 @@ export async function pushRecordToPeer(sub, options = {}) {}const url = `${peerBaseUrl(peer)}/api/peer-sync/push`;- // peerFetch wraps node-fetch with the Tailnet-insecure agent. fetchWithTimeout- // can't be reused here because it always calls global fetch (no custom-client- // hook), so the timeout is enforced inline with an AbortController so a- // hung peer can't keep the push promise pending forever and block subsequent- // debounced pushes for the same sub.+ // withAbortTimeout aborts after PUSH_TIMEOUT_MS so a hung peer can't keep the+ // push promise pending forever and block subsequent debounced pushes for the+ // same sub. (The shared `fetchWithTimeout` helper can't be reused — it always+ // calls global fetch with no custom-client hook for the insecure agent.)const postPayload = async (body) => {- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), PUSH_TIMEOUT_MS);- return peerFetch(url, {+ return withAbortTimeout(PUSH_TIMEOUT_MS, (signal) => peerFetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify(body),- signal: controller.signal,- }, peer).catch((err) => {+ signal,+ }, peer)).catch((err) => {console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);return null;- }).finally(() => clearTimeout(timeoutId));+ });};let res = await postPayload(payload);// Set when the older-peer retry below strips `manuscriptReview`: the retrydiff --git a/server/services/sharing/sidecarSync.js b/server/services/sharing/sidecarSync.jsindex 2662d9250e..7c380ebd35 100644--- a/server/services/sharing/sidecarSync.js+++ b/server/services/sharing/sidecarSync.js@@ -23,6 +23,7 @@ import { imageSidecarName, sanitizeAssetFilename } from './buckets.js';import { sidecarGenParamsHash } from '../../lib/assetHash.js';import { isPlainObject } from '../../lib/objects.js';import { peerFetch } from '../../lib/peerHttpClient.js';+import { withAbortTimeout } from '../../lib/abortTimeout.js';import { getPeers } from '../instances.js';import { peerBaseUrl } from '../../lib/peerUrl.js';@@ -85,10 +86,8 @@ export async function pullSidecarForImage(peer, base, imageFilename) {const sidecarName = imageSidecarName(safeName);const url = `${base}/data/images/${encodeURIComponent(sidecarName)}`;// Abort a hung connection after the timeout — mirrors the image pull worker.- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), SIDECAR_PULL_TIMEOUT_MS);- const res = await peerFetch(url, { signal: controller.signal, maxBytes: SIDECAR_MAX_BYTES }, peer)- .finally(() => clearTimeout(timeoutId))+ const res = await withAbortTimeout(SIDECAR_PULL_TIMEOUT_MS, (signal) =>+ peerFetch(url, { signal, maxBytes: SIDECAR_MAX_BYTES }, peer)).catch(() => null);if (!res || !res.ok) return false;// Require a trustworthy content-length and refuse over-cap BEFORE buffering.