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: migrate 19 fetch+AbortController sites to fetchWithTimeout helper
Adam Eivyd6397fbff113
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c2ae63aef7..0236e57f2e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,7 @@## Changed+- **Refactor: 19 files now use `fetchWithTimeout` instead of hand-rolled `AbortController + setTimeout + fetch + clearTimeout` blocks.** Net 75 lines deleted across `server/services/{browserService, calendarApiSync, digital-twin-helpers, feeds, insightsService, lmStudioManager, memoryClassifier, memoryEmbeddings, messageApiSync, messagePlaywrightSync, messageTokenExtractor, pm2Standardizer, syncOrchestrator, visionTest}.js`, `server/services/voice/{bootstrap, health, stt}.js`, and `server/integrations/{moltbook, moltworld}/api.js`. The helper at `server/lib/fetchWithTimeout.js` already existed and was tested — most call sites just hadn't been migrated. Each file also extracts its magic timeout numbers (3000, 10000, 30000, 60000, 120000, 180000, 300000) to named constants like `HEALTH_TIMEOUT_MS`, `GRAPH_API_TIMEOUT_MS`, `MODEL_LOAD_TIMEOUT_MS`, `DEFAULT_AI_TIMEOUT_MS` so the request lifecycle stops being four scattered statements per call. `browserService.js` additionally hoists three duplicate dynamic `await import('child_process')` / `await import('util')` blocks (one per PM2 helper) to a single top-level import + `execFileAsync` / `PM2_SHELL` constants, and `messageApiSync.js` lifts a per-401 dynamic `await import('./messageTokenExtractor.js')` to a top-level import. All 2633 server tests still pass.- **Vite dev proxy splits `/data` into per-subpath rules.** Replaced the single catch-all `/data` proxy with explicit `/data/images`, `/data/videos`, and `/data/video-thumbnails` entries so app-managed `data/` directories (CoS state, plans, etc.) are served by Vite from disk instead of being silently round-tripped to the API server. File: `client/vite.config.js`.- **Send to Video carries the source image's prompts.** Clicking "Send to Video" on an Image Gen result, gallery card, or lightbox — or the same action from Media History — now pre-populates the Video Gen prompt and negative prompt from the source image's metadata. Previously only the source image filename was passed, leaving the user to retype or paste the prompt to keep the same scene direction. The flow piggybacks on the existing `?sourceImageFile=` query-param hand-off: `?prompt=` and `?negativePrompt=` are added when the source has them, and `VideoGen.jsx` reads both on first render and re-syncs on subsequent navigations (mirroring the existing source-image effect). Files: `client/src/pages/ImageGen.jsx`, `client/src/pages/MediaHistory.jsx`, `client/src/pages/VideoGen.jsx`.diff --git a/server/integrations/moltbook/api.js b/server/integrations/moltbook/api.jsindex d5926d5655..47f1d33f93 100644--- a/server/integrations/moltbook/api.js+++ b/server/integrations/moltbook/api.js@@ -9,8 +9,10 @@import { checkRateLimit, recordAction, syncFromExternal } from './rateLimits.js';import { solveChallenge } from './challengeSolver.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';const API_BASE = 'https://www.moltbook.com/api/v1';+const MOLTBOOK_TIMEOUT_MS = 10000;/*** Infer the rate-limited action type from a Moltbook API endpoint@@ -44,17 +46,14 @@ async function handleVerification(data, apiKey, aiConfig) {console.log(`🔐 Submitting verification: code=${code} answer=${answer}`);- const verifyController = new AbortController();- const verifyTimeoutId = setTimeout(() => verifyController.abort(), 10000);- const resp = await fetch(`${API_BASE}/verify`, {+ const resp = await fetchWithTimeout(`${API_BASE}/verify`, {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${apiKey}`},- body: JSON.stringify({ verification_code: code, answer }),- signal: verifyController.signal- }).finally(() => clearTimeout(verifyTimeoutId));+ body: JSON.stringify({ verification_code: code, answer })+ }, MOLTBOOK_TIMEOUT_MS);const result = await resp.json().catch(() => ({}));if (resp.ok && result.success !== false) {@@ -84,9 +83,7 @@ async function request(endpoint, options = {}, aiConfig) {console.log(`📚 Moltbook API: ${options.method || 'GET'} ${endpoint}`);let response;- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 10000);- const fetchResult = await fetch(url, { ...config, signal: controller.signal }).then(r => ({ ok: true, response: r }), e => ({ ok: false, error: e })).finally(() => clearTimeout(timeoutId));+ const fetchResult = await fetchWithTimeout(url, config, MOLTBOOK_TIMEOUT_MS).then(r => ({ ok: true, response: r }), e => ({ ok: false, error: e }));if (!fetchResult.ok) {console.error(`❌ Moltbook API unreachable: ${fetchResult.error.message}`);diff --git a/server/integrations/moltworld/api.js b/server/integrations/moltworld/api.jsindex 86a9c400b6..2c9ca093e3 100644--- a/server/integrations/moltworld/api.js+++ b/server/integrations/moltworld/api.js@@ -9,8 +9,10 @@*/import { checkRateLimit, recordAction, syncFromExternal } from './rateLimits.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';const API_BASE = 'https://moltworld.io';+const MOLTWORLD_TIMEOUT_MS = 10000;/*** Infer the rate-limited action type from a Moltworld API endpoint@@ -38,9 +40,7 @@ async function request(endpoint, options = {}) {console.log(`🌍 Moltworld API: ${options.method || 'GET'} ${endpoint}`);- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 10000);- const fetchResult = await fetch(url, { ...config, signal: controller.signal }).then(r => ({ ok: true, response: r }), e => ({ ok: false, error: e })).finally(() => clearTimeout(timeoutId));+ const fetchResult = await fetchWithTimeout(url, config, MOLTWORLD_TIMEOUT_MS).then(r => ({ ok: true, response: r }), e => ({ ok: false, error: e }));if (!fetchResult.ok) {console.error(`❌ Moltworld API unreachable: ${fetchResult.error.message}`);diff --git a/server/services/browserService.js b/server/services/browserService.jsindex 2335c5b377..0fe686a8cc 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -5,9 +5,19 @@*/import { readFile, writeFile, readdir, stat } from 'fs/promises';+import { execFile } from 'child_process';+import { promisify } from 'util';import { join } from 'path';import { EventEmitter } from 'events';import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';++const execFileAsync = promisify(execFile);+const PM2_SHELL = process.platform === 'win32';+const PM2_SETTLE_MS = 1500;+const HEALTH_TIMEOUT_MS = 3000;+const NAVIGATE_TIMEOUT_MS = 10000;+const LOGS_TIMEOUT_MS = 5000;const CONFIG_FILE = join(PATHS.data, 'browser-config.json');const ECOSYSTEM_FILE = join(PATHS.root, 'ecosystem.config.cjs');@@ -66,11 +76,7 @@ export async function getHealthStatus() {: config.cdpHost;const healthUrl = `http://${connectHost}:${config.healthPort}/health`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 3000);-- const response = await fetch(healthUrl, { signal: controller.signal }).catch(() => null);- clearTimeout(timeout);+ const response = await fetchWithTimeout(healthUrl, {}, HEALTH_TIMEOUT_MS).catch(() => null);if (!response || !response.ok) {return {@@ -100,16 +106,12 @@ export async function getHealthStatus() {// ---------- PM2 process management ----------async function pm2Action(action, args) {- const { execFile } = await import('child_process');- const { promisify } = await import('util');- const execFileAsync = promisify(execFile);-console.log(`🌐 Browser PM2 ${action}: portos-browser`);- await execFileAsync('pm2', [action, ...args], { shell: process.platform === 'win32' });+ await execFileAsync('pm2', [action, ...args], { shell: PM2_SHELL });console.log(`✅ Browser PM2 ${action} complete`);// Give PM2 a moment to settle- await new Promise(resolve => setTimeout(resolve, 1500));+ await new Promise(resolve => setTimeout(resolve, PM2_SETTLE_MS));const status = await getHealthStatus();browserEvents.emit('status:changed', status);@@ -132,11 +134,7 @@ export async function restartBrowser() {// ---------- PM2 status (process-level) ----------export async function getProcessStatus() {- const { execFile } = await import('child_process');- const { promisify } = await import('util');- const execFileAsync = promisify(execFile);-- const { stdout } = await execFileAsync('pm2', ['jlist'], { shell: process.platform === 'win32' });+ const { stdout } = await execFileAsync('pm2', ['jlist'], { shell: PM2_SHELL });const processes = safeJSONParse(stdout, [], { allowArray: true });const browserProc = processes.find(p => p.name === 'portos-browser');@@ -160,13 +158,9 @@ export async function getProcessStatus() {// ---------- Logs ----------export async function getRecentLogs(lines = 50) {- const { execFile } = await import('child_process');- const { promisify } = await import('util');- const execFileAsync = promisify(execFile);-const { stdout, stderr } = await execFileAsync('pm2', ['logs', 'portos-browser', '--nostream', '--lines', String(lines)], {- timeout: 5000,- shell: process.platform === 'win32'+ timeout: LOGS_TIMEOUT_MS,+ shell: PM2_SHELL}).catch(() => ({ stdout: '', stderr: '' }));return { stdout: stdout || '', stderr: stderr || '' };@@ -178,11 +172,7 @@ export async function navigateToUrl(url) {const config = await loadConfig();const newTabUrl = `http://${config.cdpHost}:${config.cdpPort}/json/new?${encodeURIComponent(url)}`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 10000);-- const response = await fetch(newTabUrl, { method: 'PUT', signal: controller.signal });- clearTimeout(timeout);+ const response = await fetchWithTimeout(newTabUrl, { method: 'PUT' }, NAVIGATE_TIMEOUT_MS);if (!response.ok) {const text = await response.text().catch(() => '');@@ -200,11 +190,7 @@ export async function getOpenPages() {const config = await loadConfig();const listUrl = `http://${config.cdpHost}:${config.cdpPort}/json/list`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 3000);-- const response = await fetch(listUrl, { signal: controller.signal }).catch(() => null);- clearTimeout(timeout);+ const response = await fetchWithTimeout(listUrl, {}, HEALTH_TIMEOUT_MS).catch(() => null);if (!response || !response.ok) {return [];@@ -225,11 +211,7 @@ export async function getCdpVersion() {const config = await loadConfig();const versionUrl = `http://${config.cdpHost}:${config.cdpPort}/json/version`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 3000);-- const response = await fetch(versionUrl, { signal: controller.signal }).catch(() => null);- clearTimeout(timeout);+ const response = await fetchWithTimeout(versionUrl, {}, HEALTH_TIMEOUT_MS).catch(() => null);if (!response || !response.ok) return null;return response.json();diff --git a/server/services/calendarApiSync.js b/server/services/calendarApiSync.jsindex ca7b2a7e86..d63ca49020 100644--- a/server/services/calendarApiSync.js+++ b/server/services/calendarApiSync.js@@ -1,7 +1,10 @@import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { getToken, clearTokenCache } from './messageTokenExtractor.js';+const GRAPH_API_TIMEOUT_MS = 30000;+function makeExternalId(id) {const hash = crypto.createHash('md5').update(id).digest('hex').slice(0, 12);return `api-cal-${hash}`;@@ -76,13 +79,9 @@ export async function syncOutlookCalendarApi(account, _cache, io, options = {})page++;io?.emit('calendar:sync:event', { accountId: account.id, current: events.length, page });- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 30000);-- const response = await fetch(url, {- headers: { Authorization: `Bearer ${token}`, Prefer: 'outlook.body-content-type="Text"' },- signal: controller.signal- }).finally(() => clearTimeout(timeout));+ const response = await fetchWithTimeout(url, {+ headers: { Authorization: `Bearer ${token}`, Prefer: 'outlook.body-content-type="Text"' }+ }, GRAPH_API_TIMEOUT_MS);if (!response.ok) {const text = await response.text().catch(() => '');diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.jsindex 0b8b0d883a..df0f0bb6c8 100644--- a/server/services/digital-twin-helpers.js+++ b/server/services/digital-twin-helpers.js@@ -1,6 +1,9 @@import { v4 as uuidv4 } from '../lib/uuid.js';import { existsSync } from 'fs';import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';++const DEFAULT_AI_TIMEOUT_MS = 300000;export const DIGITAL_TWIN_DIR = PATHS.digitalTwin;@@ -51,31 +54,22 @@ export async function ensureSoulDir() {* Call any AI provider (API or CLI) with a prompt and return the response text.*/export async function callProviderAI(provider, model, prompt, { temperature = 0.3, max_tokens = 4000 } = {}) {- const timeout = provider.timeout || 300000;+ const timeout = provider.timeout || DEFAULT_AI_TIMEOUT_MS;if (provider.type === 'api') {const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeout);-- const response = await fetch(`${provider.endpoint}/chat/completions`, {+ const response = await fetchWithTimeout(`${provider.endpoint}/chat/completions`, {method: 'POST',headers,- signal: controller.signal,body: JSON.stringify({model,messages: [{ role: 'user', content: prompt }],temperature,max_tokens})- }).catch((err) => {- clearTimeout(timer);- return { ok: false, _fetchError: err.name === 'AbortError' ? 'AI request timed out' : err.message };- });-- clearTimeout(timer);+ }, timeout).catch((err) => ({ ok: false, _fetchError: err.name === 'AbortError' ? 'AI request timed out' : err.message }));if (response._fetchError) {return { error: response._fetchError };diff --git a/server/services/feeds.js b/server/services/feeds.jsindex af38a95eea..e6e8c7b4e0 100644--- a/server/services/feeds.js+++ b/server/services/feeds.js@@ -13,6 +13,7 @@ import { join } from 'path';import dns from 'dns/promises';import net from 'net';import { PATHS, createCachedStore } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';const FEEDS_FILE = join(PATHS.data, 'feeds.json');const MAX_ITEMS_PER_FEED = 100;@@ -387,14 +388,12 @@ async function fetchFeedXml(url) {// Resolve DNS and block private/loopback/link-local IPs (prevents rebinding attacks)if (!await isHostSafe(parsed.hostname)) return null;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);- const res = await fetch(url, {- signal: controller.signal,+ const feedHeaders = { 'User-Agent': 'PortOS Feed Reader/1.0', Accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml' };++ const res = await fetchWithTimeout(url, {redirect: 'manual',- headers: { 'User-Agent': 'PortOS Feed Reader/1.0', Accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml' }- }).catch(() => null);- clearTimeout(timeout);+ headers: feedHeaders+ }, FETCH_TIMEOUT_MS).catch(() => null);// Handle redirects manually to validate each redirect targetif (res?.status >= 300 && res?.status < 400) {@@ -404,14 +403,10 @@ async function fetchFeedXml(url) {if (!['http:', 'https:'].includes(redirectUrl.protocol)) return null;if (!await isHostSafe(redirectUrl.hostname)) return null;// Follow the validated redirect- const controller2 = new AbortController();- const timeout2 = setTimeout(() => controller2.abort(), FETCH_TIMEOUT_MS);- const res2 = await fetch(redirectUrl.href, {- signal: controller2.signal,+ const res2 = await fetchWithTimeout(redirectUrl.href, {redirect: 'error',- headers: { 'User-Agent': 'PortOS Feed Reader/1.0', Accept: 'application/rss+xml, application/atom+xml, application/xml, text/xml' }- }).catch(() => null);- clearTimeout(timeout2);+ headers: feedHeaders+ }, FETCH_TIMEOUT_MS).catch(() => null);if (!res2?.ok) return null;return res2.text();}diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex dd85400cfa..47d82a0883 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -21,6 +21,9 @@ import { getTasteProfile } from './taste-questionnaire.js';import { getActiveProvider, getProviderById } from './providers.js';import { getCorrelationData } from './appleHealthQuery.js';import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';++const DEFAULT_AI_TIMEOUT_MS = 300000;const MARKER_BY_RSID = new Map(CURATED_MARKERS.map(m => [m.rsid, m]));@@ -163,28 +166,22 @@ function getLatestBloodValues(tests) {* API-type providers only. Returns { text } on success, { error } on failure.*/async function callProviderAISimple(provider, model, prompt, { temperature = 0.3, max_tokens = 1000 } = {}) {- const timeout = provider.timeout || 300000;+ const timeout = provider.timeout || DEFAULT_AI_TIMEOUT_MS;if (provider.type === 'api') {const headers = { 'Content-Type': 'application/json' };if (provider.apiKey) headers['Authorization'] = `Bearer ${provider.apiKey}`;- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeout);-- const response = await fetch(`${provider.endpoint}/chat/completions`, {+ const response = await fetchWithTimeout(`${provider.endpoint}/chat/completions`, {method: 'POST',headers,- signal: controller.signal,body: JSON.stringify({model,messages: [{ role: 'user', content: prompt }],temperature,max_tokens})- });-- clearTimeout(timer);+ }, timeout);if (!response.ok) {const errorText = await response.text().catch(() => 'Unknown error');diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex bc6c47ae8b..c5f737dab0 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -6,6 +6,7 @@*/import { cosEvents } from './cosEvents.js'+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'const AVAILABILITY_CACHE_TTL_MS = 30_000@@ -38,17 +39,15 @@ const status = {*/async function lmStudioRequest(endpoint, options = {}) {const url = `${config.baseUrl}${endpoint}`- const controller = new AbortController()- const timeoutId = setTimeout(() => controller.abort(), options.timeout || config.timeout)+ const { timeout, headers, ...rest } = options- const response = await fetch(url, {- ...options,- signal: controller.signal,+ const response = await fetchWithTimeout(url, {+ ...rest,headers: {'Content-Type': 'application/json',- ...options.headers+ ...headers}- }).finally(() => clearTimeout(timeoutId))+ }, timeout || config.timeout)if (!response.ok) {throw new Error(`LM Studio API error: ${response.status} ${response.statusText}`)diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.jsindex 91fe48ac66..7edba194ba 100644--- a/server/services/memoryClassifier.js+++ b/server/services/memoryClassifier.js@@ -10,8 +10,13 @@ import { existsSync } from 'fs';import { join } from 'path';import { getStageTemplate } from './promptService.js';import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { getMemories } from './memoryBackend.js';+const MODEL_LIST_TIMEOUT_MS = 5000;+const MODEL_LOAD_TIMEOUT_MS = 120000;+const HEALTH_CHECK_TIMEOUT_MS = 5000;+const MEMORY_CONFIG_FILE = join(PATHS.data, 'memory-classifier-config.json');// Default configuration@@ -185,12 +190,9 @@ function getBaseUrl(endpoint) {async function ensureLLMModelLoaded(config) {const baseUrl = getBaseUrl(config.endpoint);- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 5000);- const listResponse = await fetch(`${baseUrl}/api/v0/models`, {- method: 'GET',- signal: controller.signal- }).catch(() => null).finally(() => clearTimeout(timeoutId));+ const listResponse = await fetchWithTimeout(`${baseUrl}/api/v0/models`, {+ method: 'GET'+ }, MODEL_LIST_TIMEOUT_MS).catch(() => null);if (!listResponse?.ok) return null;@@ -216,14 +218,11 @@ async function ensureLLMModelLoaded(config) {console.log(`📦 Auto-loading LLM model: ${preferred.id}`);- const loadController = new AbortController();- const loadTimeout = setTimeout(() => loadController.abort(), 120000);- const loadResponse = await fetch(`${baseUrl}/api/v1/models/load`, {+ const loadResponse = await fetchWithTimeout(`${baseUrl}/api/v1/models/load`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ model: preferred.id }),- signal: loadController.signal- }).catch(err => ({ ok: false, _err: err.message })).finally(() => clearTimeout(loadTimeout));+ body: JSON.stringify({ model: preferred.id })+ }, MODEL_LOAD_TIMEOUT_MS).catch(err => ({ ok: false, _err: err.message }));if (!loadResponse.ok) {const errText = loadResponse._err || await loadResponse.text?.().catch(() => 'unknown error') || 'unknown error';@@ -244,10 +243,7 @@ async function callLLM(prompt, config) {const loadedModel = await ensureLLMModelLoaded(config);const modelToUse = loadedModel || config.model;- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), config.timeout);-- const response = await fetch(config.endpoint, {+ const response = await fetchWithTimeout(config.endpoint, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -267,9 +263,8 @@ async function callLLM(prompt, config) {],temperature: 0.1,max_tokens: 2000- }),- signal: controller.signal- }).finally(() => clearTimeout(timeoutId));+ })+ }, config.timeout);if (!response.ok) {const error = await response.text().catch(() => 'Unknown error');@@ -412,13 +407,11 @@ export async function isAvailable() {if (!config.enabled) return false;// Quick health check- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 5000);-- const response = await fetch(config.endpoint.replace('/chat/completions', '/models'), {- method: 'GET',- signal: controller.signal- }).catch(() => null).finally(() => clearTimeout(timeoutId));+ const response = await fetchWithTimeout(+ config.endpoint.replace('/chat/completions', '/models'),+ { method: 'GET' },+ HEALTH_CHECK_TIMEOUT_MS+ ).catch(() => null);return response?.ok === true;}diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex 2b0b7d7e34..9ae7e7076b 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -8,6 +8,10 @@import { DEFAULT_MEMORY_CONFIG } from './memoryBackend.js';import { getProviderById } from './providers.js';import { getConfig as getCosConfig } from './cos.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';++const MODEL_LIST_TIMEOUT_MS = 10000;+const MODEL_LOAD_TIMEOUT_MS = 60000;// Cache for embedding config (loaded from CoS config)let embeddingConfig = null;@@ -29,14 +33,9 @@ async function ensureEmbeddingModelLoaded(config) {if (modelEnsured) return;const baseUrl = getBaseUrl(config);- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 10000);// Query LM Studio's native API for all downloaded models- const response = await fetch(`${baseUrl}/api/v0/models`, {- signal: controller.signal- });- clearTimeout(timeout);+ const response = await fetchWithTimeout(`${baseUrl}/api/v0/models`, {}, MODEL_LIST_TIMEOUT_MS);if (!response.ok) return;@@ -67,15 +66,11 @@ async function ensureEmbeddingModelLoaded(config) {const modelToLoad = candidates[0];console.log(`📦 Auto-loading embedding model: ${modelToLoad.id}`);- const loadController = new AbortController();- const loadTimeout = setTimeout(() => loadController.abort(), 60000);- const loadResponse = await fetch(`${baseUrl}/api/v1/models/load`, {+ const loadResponse = await fetchWithTimeout(`${baseUrl}/api/v1/models/load`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ model: modelToLoad.id }),- signal: loadController.signal- });- clearTimeout(loadTimeout);+ body: JSON.stringify({ model: modelToLoad.id })+ }, MODEL_LOAD_TIMEOUT_MS);if (loadResponse.ok) {config.embeddingModel = modelToLoad.id;diff --git a/server/services/messageApiSync.js b/server/services/messageApiSync.jsindex c84661e2fc..8084abc006 100644--- a/server/services/messageApiSync.js+++ b/server/services/messageApiSync.js@@ -6,7 +6,10 @@import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';-import { getToken } from './messageTokenExtractor.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { getToken, clearTokenCache } from './messageTokenExtractor.js';++const GRAPH_API_TIMEOUT_MS = 30000;function makeExternalId(prefix, id) {// For API sync, use a stable ID from the API response@@ -53,20 +56,15 @@ export async function syncOutlookApi(account, cache, io, options = {}) {page++;io?.emit('messages:sync:progress', { accountId: account.id, current: messages.length, total: maxMessages, page });- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 30000);-- const response = await fetch(url, {- headers: { Authorization: `Bearer ${token}`, Prefer: 'outlook.body-content-type="Text"' },- signal: controller.signal- }).finally(() => clearTimeout(timeout));+ const response = await fetchWithTimeout(url, {+ headers: { Authorization: `Bearer ${token}`, Prefer: 'outlook.body-content-type="Text"' }+ }, GRAPH_API_TIMEOUT_MS);if (!response.ok) {const text = await response.text().catch(() => '');console.log(`📧 API sync failed (${response.status}): ${text.slice(0, 200)}`);if (response.status === 401) {// Token expired — clear cache so next sync re-extracts- const { clearTokenCache } = await import('./messageTokenExtractor.js');clearTokenCache('outlook');return null; // Fall back to Playwright}diff --git a/server/services/messagePlaywrightSync.js b/server/services/messagePlaywrightSync.jsindex 13aba3ae92..6b259d67d9 100644--- a/server/services/messagePlaywrightSync.js+++ b/server/services/messagePlaywrightSync.js@@ -3,8 +3,11 @@ import { join } from 'path';import crypto from 'crypto';import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { loadConfig } from './browserService.js';+const DEFAULT_CDP_TIMEOUT_MS = 10000;+const SELECTORS_FILE = join(PATHS.messages, 'selectors.json');const OUTLOOK_URL = 'https://outlook.office.com/mail/';@@ -32,10 +35,8 @@ async function getCdpConnectHost() {async function cdpFetch(path, options = {}) {const { host, port } = await getCdpConnectHost();const url = `http://${host}:${port}${path}`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), options.timeout || 10000);- const response = await fetch(url, { ...options, signal: controller.signal }).finally(() => clearTimeout(timeout));- return response;+ const { timeout, ...rest } = options;+ return fetchWithTimeout(url, rest, timeout || DEFAULT_CDP_TIMEOUT_MS);}export async function getPages() {diff --git a/server/services/messageTokenExtractor.js b/server/services/messageTokenExtractor.jsindex be0f40258b..c3858c74e8 100644--- a/server/services/messageTokenExtractor.js+++ b/server/services/messageTokenExtractor.js@@ -10,6 +10,9 @@import { getPages, evaluateOnPage } from './messagePlaywrightSync.js';import { safeJSONParse } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';++const TOKEN_VALIDATION_TIMEOUT_MS = 15000;// Per-provider token cache: { token, decoded, cachedAt }const tokenCache = new Map();@@ -264,13 +267,9 @@ export async function testApi(provider, token, top = 5) {const url = urls[provider];if (!url) return { success: false, error: `No API URL for provider: ${provider}` };- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), 15000);-- const response = await fetch(url, {- headers: { Authorization: `Bearer ${token}` },- signal: controller.signal- }).finally(() => clearTimeout(timeout));+ const response = await fetchWithTimeout(url, {+ headers: { Authorization: `Bearer ${token}` }+ }, TOKEN_VALIDATION_TIMEOUT_MS);if (!response.ok) {const text = await response.text().catch(() => '');diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.jsindex 2694333d5e..e0f93ff0ba 100644--- a/server/services/pm2Standardizer.js+++ b/server/services/pm2Standardizer.js@@ -6,8 +6,10 @@ import { promisify } from 'util';import { getActiveProvider, getProviderById } from './providers.js';import { spawn } from 'child_process';import { safeJSONParse } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';const execAsync = promisify(exec);+const DEFAULT_PM2_AI_TIMEOUT_MS = 180000;/*** Gather all config files for standardization analysis@@ -222,20 +224,17 @@ async function executeApiAnalysis(provider, prompt) {headers['Authorization'] = `Bearer ${provider.apiKey}`;}- const timeoutMs = provider.timeout || 180000;- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), timeoutMs);+ const timeoutMs = provider.timeout || DEFAULT_PM2_AI_TIMEOUT_MS;- const response = await fetch(`${provider.endpoint}/chat/completions`, {+ const response = await fetchWithTimeout(`${provider.endpoint}/chat/completions`, {method: 'POST',headers,- signal: controller.signal,body: JSON.stringify({model: provider.defaultModel,messages: [{ role: 'user', content: prompt }],temperature: 0.1})- }).finally(() => clearTimeout(timer));+ }, timeoutMs);if (!response.ok) {throw new Error(`API error: ${response.status}`);diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex a61784e5a5..87dc8f683b 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -18,6 +18,7 @@ import * as brainSyncLog from './brainSyncLog.js';import * as memorySync from './memorySync.js';import * as dataSync from './dataSync.js';import { getBackendName } from './memoryBackend.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';const CURSORS_FILE = dataPath('instances_sync_cursors.json');const SYNC_INTERVAL_MS = 60000;@@ -59,16 +60,12 @@ async function withCursors(fn) {async function fetchPeer(peer, path) {const url = `${peerBaseUrl(peer)}${path}`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);try {- const res = await fetch(url, { signal: controller.signal });+ const res = await fetchWithTimeout(url, {}, FETCH_TIMEOUT_MS);if (!res.ok) return null;return await res.json();} catch {return null;- } finally {- clearTimeout(timeout);}}@@ -88,10 +85,8 @@ async function syncImageFromPeer(peer, avatarPath) {if (exists) return;const url = `${peerBaseUrl(peer)}${avatarPath}`;- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);try {- const res = await fetch(url, { signal: controller.signal });+ const res = await fetchWithTimeout(url, {}, FETCH_TIMEOUT_MS);if (!res.ok) return;const buffer = Buffer.from(await res.arrayBuffer());await ensureDir(PATHS.images);@@ -99,8 +94,6 @@ async function syncImageFromPeer(peer, avatarPath) {console.log(`🔄 Synced avatar image: ${filename}`);} catch {// Non-critical — avatar will sync on next cycle- } finally {- clearTimeout(timeout);}}diff --git a/server/services/visionTest.js b/server/services/visionTest.jsindex fb71b16aab..aa202496ac 100644--- a/server/services/visionTest.js+++ b/server/services/visionTest.js@@ -10,8 +10,11 @@ import { existsSync } from 'fs';import { join, extname } from 'path';import { getProviderById } from './providers.js';import { PATHS } from '../lib/fileUtils.js';+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';const SCREENSHOTS_DIR = PATHS.screenshots;+const DEFAULT_VISION_TIMEOUT_MS = 60000;+const VISION_HEALTH_TIMEOUT_MS = 5000;/*** Get MIME type from file extension@@ -58,11 +61,8 @@ async function loadImageAsBase64(imagePath) {* @param {number} options.timeout - Request timeout in ms* @returns {Promise<Object>} - API response*/-async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, timeout = 60000 }) {- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), timeout);-- const response = await fetch(`${endpoint}/chat/completions`, {+async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, timeout = DEFAULT_VISION_TIMEOUT_MS }) {+ const response = await fetchWithTimeout(`${endpoint}/chat/completions`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -89,9 +89,8 @@ async function callVisionAPI({ endpoint, apiKey, model, imageDataUrl, prompt, ti],max_tokens: 500,temperature: 0.1- }),- signal: controller.signal- }).finally(() => clearTimeout(timeoutId));+ })+ }, timeout);if (!response.ok) {const errorText = await response.text().catch(() => 'Unknown error');@@ -164,7 +163,7 @@ export async function testVision({ imagePath, prompt, expectedContent, providerImodel: testModel,imageDataUrl,prompt,- timeout: provider.timeout || 60000+ timeout: provider.timeout || DEFAULT_VISION_TIMEOUT_MS});const responseContent = apiResponse.choices?.[0]?.message?.content || '';@@ -288,13 +287,9 @@ export async function checkVisionHealth(providerId = 'lmstudio') {}// Check if endpoint is reachable- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 5000);-- const response = await fetch(`${provider.endpoint}/models`, {- headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {},- signal: controller.signal- }).catch(() => null).finally(() => clearTimeout(timeoutId));+ const response = await fetchWithTimeout(`${provider.endpoint}/models`, {+ headers: provider.apiKey ? { 'Authorization': `Bearer ${provider.apiKey}` } : {}+ }, VISION_HEALTH_TIMEOUT_MS).catch(() => null);if (!response?.ok) {return { available: false, error: 'API endpoint not reachable' };diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.jsindex 13ba13be5b..d853c7ff22 100644--- a/server/services/voice/bootstrap.js+++ b/server/services/voice/bootstrap.js@@ -10,6 +10,7 @@ import { PATHS } from '../../lib/fileUtils.js';import { execPm2, getAppStatus } from '../pm2.js';import { expandPath, piperVoiceTildePath, voiceHome, IS_WIN, PIPER_BIN_NAME } from './config.js';import { isToolCapable, isReasoningModel } from './llm.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';export const pexec = promisify(execFile);@@ -135,12 +136,9 @@ const waitForWhisper = async (host, port, timeoutMs = 8000) => {while (Date.now() < deadline) {const remaining = deadline - Date.now();const probeTimeout = Math.max(1, Math.min(1000, remaining));- const ctrl = new AbortController();- const t = setTimeout(() => ctrl.abort(), probeTimeout);- const ok = await fetch(url, { method: 'GET', signal: ctrl.signal })+ const ok = await fetchWithTimeout(url, { method: 'GET' }, probeTimeout).then(() => true)- .catch(() => false)- .finally(() => clearTimeout(t));+ .catch(() => false);if (ok) return true;const sleep = Math.min(250, Math.max(0, deadline - Date.now()));if (sleep > 0) await new Promise((r) => setTimeout(r, sleep));diff --git a/server/services/voice/health.js b/server/services/voice/health.jsindex ba48d27cd7..c2d5710699 100644--- a/server/services/voice/health.js+++ b/server/services/voice/health.js@@ -6,6 +6,7 @@ import { join } from 'path';import { getVoiceConfig, expandPath, voiceHome } from './config.js';import { readyState as kokoroReadyState } from './tts-kokoro.js';import { which } from './bootstrap.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';const PROBE_TIMEOUT_MS = 1500;const CACHE_TTL_MS = 3000;@@ -13,10 +14,8 @@ let cache = null;const probe = async (url) => {const started = Date.now();- const controller = new AbortController();- const t = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);try {- const res = await fetch(url, { method: 'GET', signal: controller.signal });+ const res = await fetchWithTimeout(url, { method: 'GET' }, PROBE_TIMEOUT_MS);const latencyMs = Date.now() - started;if (!res.ok) return { ok: false, state: 'bad_status', status: res.status, latencyMs };return { ok: true, status: res.status, latencyMs };@@ -26,8 +25,6 @@ const probe = async (url) => {if (name === 'AbortError') return { ok: false, state: 'timeout', latencyMs: Date.now() - started };if (code === 'ECONNREFUSED') return { ok: false, state: 'down', error: code };return { ok: false, state: 'error', error: err?.message || String(err) };- } finally {- clearTimeout(t);}};diff --git a/server/services/voice/stt.js b/server/services/voice/stt.jsindex 78ac2ce49d..9f9bbeefb2 100644--- a/server/services/voice/stt.js+++ b/server/services/voice/stt.js@@ -2,6 +2,7 @@// Docs: https://github.com/ggerganov/whisper.cpp/tree/master/examples/serverimport { getVoiceConfig } from './config.js';+import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';const STT_TIMEOUT_MS = 30_000;@@ -39,23 +40,16 @@ export const transcribe = async (audio, opts = {}) => {form.append('prompt', cfg.stt.vocabularyPrompt || DEFAULT_STT_PROMPT);const started = Date.now();- // Combine the internal timeout with the caller's abort signal so barge-in- // can tear down an in-flight whisper request. If the caller's signal is- // already aborted, short-circuit without hitting the network.+ // fetchWithTimeout composes our timeout with the caller's abort signal so+ // barge-in can tear down an in-flight whisper request. If the caller's+ // signal is already aborted, short-circuit without hitting the network.if (opts.signal?.aborted) throw new Error('transcribe aborted');- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), STT_TIMEOUT_MS);- const onCallerAbort = () => controller.abort();- opts.signal?.addEventListener?.('abort', onCallerAbort, { once: true });- const res = await fetch(`${endpoint}/inference`, {+ const res = await fetchWithTimeout(`${endpoint}/inference`, {method: 'POST',body: form,- signal: controller.signal,- }).finally(() => {- clearTimeout(timer);- opts.signal?.removeEventListener?.('abort', onCallerAbort);- });+ signal: opts.signal,+ }, STT_TIMEOUT_MS);if (!res.ok) {const body = await res.text().catch(() => '');