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: add fetch timeouts, fix data races, and harden error handling

Adam Eivy4ba96a5cc83f
diff --git a/server/lib/fetchWithTimeout.js b/server/lib/fetchWithTimeout.js
new file mode 100644
index 0000000000..d0756275cd
--- /dev/null
+++ b/server/lib/fetchWithTimeout.js
@@ -0,0 +1,14 @@
+/**
+ * Fetch wrapper with AbortController timeout.
+ *
+ * @param {string} url
+ * @param {RequestInit} [options]
+ * @param {number} [timeoutMs=15000] - Timeout in milliseconds
+ * @returns {Promise<Response>}
+ */
+export async function fetchWithTimeout(url, options = {}, timeoutMs = 15000) {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
+ return fetch(url, { ...options, signal: controller.signal })
+ .finally(() => clearTimeout(timeoutId));
+}
diff --git a/server/services/agentActionExecutor.js b/server/services/agentActionExecutor.js
index b0f559e5ef..e21366f2c4 100644
--- a/server/services/agentActionExecutor.js
+++ b/server/services/agentActionExecutor.js
@@ -134,7 +134,7 @@ async function executeComment(client, agent, params) {
console.log(`🤖 AI generating comment for "${agent.name}" on post ${postId}`);
const post = await client.getPost(postId);
const commentsResponse = await client.getComments(postId);
- const comments = commentsResponse.comments || commentsResponse || [];
+ const comments = Array.isArray(commentsResponse.comments) ? commentsResponse.comments : Array.isArray(commentsResponse) ? commentsResponse : [];
const contentConfig = agent.aiConfig?.content || agent.aiConfig;
if (parentId) {
@@ -330,7 +330,7 @@ async function executeMonitor(client, agent, schedule, params) {
});
if (suspended) break;
- const allComments = commentsResponse.comments || commentsResponse || [];
+ const allComments = Array.isArray(commentsResponse.comments) ? commentsResponse.comments : Array.isArray(commentsResponse) ? commentsResponse : [];
totalComments += allComments.length;
const otherComments = allComments.filter(c => {
diff --git a/server/services/cos.js b/server/services/cos.js
index 41b47ad6ac..1f54bb21a6 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -77,27 +77,36 @@ let initialStartup = false;
// Lightweight index mapping agentId → YYYY-MM-DD date bucket (~50KB vs 16MB full cache)
// Lazy-loaded from data/cos/agents/index.json on first access
let agentIndex = null;
+let agentIndexPromise = null;
const INDEX_FILE = join(AGENTS_DIR, 'index.json');
-// Load agent index from disk (lazy init)
+// Load agent index from disk (lazy init, singleton promise prevents concurrent migrations)
async function loadAgentIndex() {
if (agentIndex) return agentIndex;
+ if (agentIndexPromise) return agentIndexPromise;
- if (!existsSync(AGENTS_DIR)) {
- await mkdir(AGENTS_DIR, { recursive: true });
- }
+ agentIndexPromise = (async () => {
+ if (!existsSync(AGENTS_DIR)) {
+ await mkdir(AGENTS_DIR, { recursive: true });
+ }
- if (existsSync(INDEX_FILE)) {
- const content = await readFile(INDEX_FILE, 'utf-8').catch(() => '{}');
- const parsed = safeJSONParse(content, {});
- agentIndex = new Map(Object.entries(parsed));
- console.log(`📂 Loaded agent index: ${agentIndex.size} entries`);
- } else {
- // No index yet — run migration from flat dirs to date buckets
- agentIndex = await migrateAgentsToDateBuckets();
- }
+ if (existsSync(INDEX_FILE)) {
+ const content = await readFile(INDEX_FILE, 'utf-8').catch(() => '{}');
+ const parsed = safeJSONParse(content, {});
+ agentIndex = new Map(Object.entries(parsed));
+ console.log(`📂 Loaded agent index: ${agentIndex.size} entries`);
+ } else {
+ // No index yet — run migration from flat dirs to date buckets
+ agentIndex = await migrateAgentsToDateBuckets();
+ }
+
+ return agentIndex;
+ })().catch(err => {
+ agentIndexPromise = null;
+ throw err;
+ });
- return agentIndex;
+ return agentIndexPromise;
}
// Persist agent index to disk (atomic write via temp file + rename)
@@ -208,16 +217,21 @@ async function migrateAgentsToDateBuckets() {
continue;
}
- await rename(agentDir, targetDir).catch(async (err) => {
+ await rename(agentDir, targetDir).catch(async (renameErr) => {
// rename can fail across filesystems — fall back to copy+delete
- console.log(`⚠️ Rename failed for ${agentId}, using copy: ${err.message}`);
- await mkdir(targetDir, { recursive: true });
- const files = await readdir(agentDir);
- for (const file of files) {
- const content = await readFile(join(agentDir, file));
- await writeFile(join(targetDir, file), content);
+ console.log(`⚠️ Rename failed for ${agentId}, using copy: ${renameErr.message}`);
+ try {
+ await mkdir(targetDir, { recursive: true });
+ const files = await readdir(agentDir);
+ for (const file of files) {
+ const content = await readFile(join(agentDir, file));
+ await writeFile(join(targetDir, file), content);
+ }
+ await rm(agentDir, { recursive: true });
+ } catch (copyErr) {
+ console.error(`❌ Copy fallback failed for ${agentId}: ${copyErr.message}`);
+ throw copyErr;
}
- await rm(agentDir, { recursive: true });
});
index.set(agentId, dateStr);
diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.js
index a6691b7862..1b93dab85e 100644
--- a/server/services/cosRunnerClient.js
+++ b/server/services/cosRunnerClient.js
@@ -6,6 +6,7 @@
*/
import { io } from 'socket.io-client';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
const COS_RUNNER_URL = process.env.COS_RUNNER_URL || 'http://localhost:5558';
@@ -21,7 +22,7 @@ export function initCosRunnerConnection() {
socket = io(COS_RUNNER_URL, {
reconnection: true,
- reconnectionAttempts: Infinity,
+ reconnectionAttempts: 10,
reconnectionDelay: 1000
});
@@ -38,6 +39,10 @@ export function initCosRunnerConnection() {
if (handler) handler();
});
+ socket.on('connect_error', (err) => {
+ console.error(`🔌 CoS Runner connection error: ${err.message}`);
+ });
+
// Forward events to registered handlers
socket.on('agent:output', (data) => {
const handler = eventHandlers.get('agent:output');
@@ -88,7 +93,7 @@ export function onCosRunnerEvent(event, handler) {
* Check if CoS Runner is available
*/
export async function isRunnerAvailable() {
- const response = await fetch(`${COS_RUNNER_URL}/health`).catch(() => null);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/health`, {}, 10000).catch(() => null);
if (!response || !response.ok) return false;
return true;
}
@@ -97,7 +102,7 @@ export async function isRunnerAvailable() {
* Get runner health status
*/
export async function getRunnerHealth() {
- const response = await fetch(`${COS_RUNNER_URL}/health`).catch(() => null);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/health`, {}, 10000).catch(() => null);
if (!response || !response.ok) {
return { available: false, error: 'Runner not available' };
}
@@ -156,7 +161,7 @@ export async function spawnAgentViaRunner(options) {
* Get list of active agents from runner
*/
export async function getActiveAgentsFromRunner() {
- const response = await fetch(`${COS_RUNNER_URL}/agents`);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/agents`, {}, 10000);
if (!response.ok) {
throw new Error('Failed to get agents');
}
@@ -167,9 +172,9 @@ export async function getActiveAgentsFromRunner() {
* Terminate an agent via the runner (graceful SIGTERM with SIGKILL fallback)
*/
export async function terminateAgentViaRunner(agentId) {
- const response = await fetch(`${COS_RUNNER_URL}/terminate/${agentId}`, {
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/terminate/${agentId}`, {
method: 'POST'
- });
+ }, 30000);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to terminate agent');
@@ -181,9 +186,9 @@ export async function terminateAgentViaRunner(agentId) {
* Force kill an agent via the runner (immediate SIGKILL)
*/
export async function killAgentViaRunner(agentId) {
- const response = await fetch(`${COS_RUNNER_URL}/kill/${agentId}`, {
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/kill/${agentId}`, {
method: 'POST'
- });
+ }, 30000);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to kill agent');
@@ -195,7 +200,7 @@ export async function killAgentViaRunner(agentId) {
* Get process stats for an agent
*/
export async function getAgentStatsFromRunner(agentId) {
- const response = await fetch(`${COS_RUNNER_URL}/agents/${agentId}/stats`);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/agents/${agentId}/stats`, {}, 10000);
if (!response.ok) {
return null;
}
@@ -206,9 +211,9 @@ export async function getAgentStatsFromRunner(agentId) {
* Terminate all agents via the runner
*/
export async function terminateAllAgentsViaRunner() {
- const response = await fetch(`${COS_RUNNER_URL}/terminate-all`, {
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/terminate-all`, {
method: 'POST'
- });
+ }, 30000);
if (!response.ok) {
throw new Error('Failed to terminate agents');
}
@@ -219,7 +224,7 @@ export async function terminateAllAgentsViaRunner() {
* Get agent output from runner
*/
export async function getAgentOutputFromRunner(agentId) {
- const response = await fetch(`${COS_RUNNER_URL}/agents/${agentId}/output`);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/agents/${agentId}/output`, {}, 10000);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to get agent output');
@@ -275,7 +280,7 @@ export async function executeCliRunViaRunner(options) {
* Get list of active runs from runner
*/
export async function getActiveRunsFromRunner() {
- const response = await fetch(`${COS_RUNNER_URL}/runs`);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs`, {}, 10000);
if (!response.ok) {
throw new Error('Failed to get runs');
}
@@ -286,7 +291,7 @@ export async function getActiveRunsFromRunner() {
* Check if a run is active in the runner
*/
export async function isRunActiveInRunner(runId) {
- const response = await fetch(`${COS_RUNNER_URL}/runs/${runId}/active`);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs/${runId}/active`, {}, 10000);
if (!response.ok) {
return false;
}
@@ -298,7 +303,7 @@ export async function isRunActiveInRunner(runId) {
* Get run output from runner
*/
export async function getRunOutputFromRunner(runId) {
- const response = await fetch(`${COS_RUNNER_URL}/runs/${runId}/output`);
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs/${runId}/output`, {}, 10000);
if (!response.ok) {
return null;
}
@@ -310,9 +315,9 @@ export async function getRunOutputFromRunner(runId) {
* Stop a run via the runner
*/
export async function stopRunViaRunner(runId) {
- const response = await fetch(`${COS_RUNNER_URL}/runs/${runId}/stop`, {
+ const response = await fetchWithTimeout(`${COS_RUNNER_URL}/runs/${runId}/stop`, {
method: 'POST'
- });
+ }, 30000);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || 'Failed to stop run');
diff --git a/server/services/memory.js b/server/services/memory.js
index a506dd6e91..abad97d985 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -201,17 +201,17 @@ export async function createMemory(data, embedding = null) {
* Get a memory by ID
*/
export async function getMemory(id) {
- const memory = await loadMemory(id);
- if (!memory) return null;
+ return withMemoryLock(async () => {
+ const memory = await loadMemory(id);
+ if (!memory) return null;
- // Update access stats
- await withMemoryLock(async () => {
+ // Update access stats
memory.accessCount += 1;
memory.lastAccessed = new Date().toISOString();
await saveMemory(memory);
- });
- return memory;
+ return memory;
+ });
}
/**
@@ -251,9 +251,11 @@ export async function getMemories(options = {}) {
const sortBy = options.sortBy || 'createdAt';
const sortOrder = options.sortOrder || 'desc';
memories.sort((a, b) => {
- const aVal = a[sortBy] || 0;
- const bVal = b[sortBy] || 0;
- return sortOrder === 'desc' ? (bVal > aVal ? 1 : -1) : (aVal > bVal ? 1 : -1);
+ const aRaw = a[sortBy];
+ const bRaw = b[sortBy];
+ const aVal = typeof aRaw === 'string' ? aRaw : (aRaw ?? 0);
+ const bVal = typeof bRaw === 'string' ? bRaw : (bRaw ?? 0);
+ return sortOrder === 'desc' ? (bVal > aVal ? 1 : bVal < aVal ? -1 : 0) : (aVal > bVal ? 1 : aVal < bVal ? -1 : 0);
});
// Paginate