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

perf: fix N+1 queries and add caching optimizations

Adam Eivy57eddd5ee40a
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index 2ea27faff4..df283cda10 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect } from 'react';
+import { useState, useEffect, useCallback, useMemo } from 'react';
import {
Brain,
RefreshCw,
@@ -34,11 +34,7 @@ export default function LearningTab() {
errors: false
});
- useEffect(() => {
- loadData();
- }, []);
-
- const loadData = async () => {
+ const loadData = useCallback(async () => {
setLoading(true);
const [learningData, performanceData, skippedData, durationsData] = await Promise.all([
api.getCosLearning().catch(() => null),
@@ -51,41 +47,54 @@ export default function LearningTab() {
setSkipped(skippedData);
setDurations(durationsData);
setLoading(false);
- };
+ }, []);
+
+ useEffect(() => {
+ loadData();
+ }, [loadData]);
- const handleBackfill = async () => {
+ const handleBackfill = useCallback(async () => {
setBackfilling(true);
const result = await api.backfillCosLearning().catch(() => null);
if (result?.success) {
await loadData();
}
setBackfilling(false);
- };
+ }, [loadData]);
- const toggleSection = (section) => {
+ const toggleSection = useCallback((section) => {
setExpandedSections(prev => ({ ...prev, [section]: !prev[section] }));
- };
+ }, []);
- const getSuccessRateColor = (rate) => {
+ // Memoize helper functions to prevent re-creation on each render
+ const getSuccessRateColor = useCallback((rate) => {
if (rate >= 80) return 'text-port-success';
if (rate >= 60) return 'text-port-warning';
return 'text-port-error';
- };
+ }, []);
- const getSuccessRateBg = (rate) => {
+ const getSuccessRateBg = useCallback((rate) => {
if (rate >= 80) return 'bg-port-success';
if (rate >= 60) return 'bg-port-warning';
return 'bg-port-error';
- };
+ }, []);
- const formatDuration = (ms) => {
+ const formatDuration = useCallback((ms) => {
if (!ms) return '—';
const minutes = Math.round(ms / 60000);
if (minutes < 60) return `${minutes}m`;
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return `${hours}h ${mins}m`;
- };
+ }, []);
+
+ // Memoize sorted durations to avoid re-sorting on each render
+ const sortedDurations = useMemo(() => {
+ if (!durations) return [];
+ return Object.entries(durations)
+ .filter(([key]) => key !== '_overall')
+ .sort((a, b) => b[1].avgDurationMs - a[1].avgDurationMs);
+ }, [durations]);
if (loading) {
return (
@@ -376,23 +385,20 @@ export default function LearningTab() {
</tr>
</thead>
<tbody>
- {Object.entries(durations)
- .filter(([key]) => key !== '_overall')
- .sort((a, b) => b[1].avgDurationMs - a[1].avgDurationMs)
- .map(([taskType, data], idx) => (
- <tr key={idx} className="border-t border-port-border">
- <td className="p-3 text-gray-300 truncate max-w-[200px]">{taskType}</td>
- <td className="p-3 text-right text-cyan-400 font-mono">
- {formatDuration(data.avgDurationMs)}
- </td>
- <td className="p-3 text-right text-gray-500 hidden sm:table-cell">
- {data.completed}
- </td>
- <td className={`p-3 text-right font-mono hidden sm:table-cell ${getSuccessRateColor(data.successRate)}`}>
- {data.successRate}%
- </td>
- </tr>
- ))}
+ {sortedDurations.map(([taskType, data], idx) => (
+ <tr key={idx} className="border-t border-port-border">
+ <td className="p-3 text-gray-300 truncate max-w-[200px]">{taskType}</td>
+ <td className="p-3 text-right text-cyan-400 font-mono">
+ {formatDuration(data.avgDurationMs)}
+ </td>
+ <td className="p-3 text-right text-gray-500 hidden sm:table-cell">
+ {data.completed}
+ </td>
+ <td className={`p-3 text-right font-mono hidden sm:table-cell ${getSuccessRateColor(data.successRate)}`}>
+ {data.successRate}%
+ </td>
+ </tr>
+ ))}
</tbody>
</table>
</div>
diff --git a/client/src/hooks/useSocket.js b/client/src/hooks/useSocket.js
index 2b7b733fcf..2acf048447 100644
--- a/client/src/hooks/useSocket.js
+++ b/client/src/hooks/useSocket.js
@@ -1,30 +1,26 @@
import { useEffect, useState } from 'react';
-import { io } from 'socket.io-client';
-
-let socket = null;
+import socket from '../services/socket';
+/**
+ * Hook to access the shared socket instance and track connection status.
+ * Uses the singleton socket from services/socket.js to avoid duplicate connections.
+ */
export function useSocket() {
- const [connected, setConnected] = useState(false);
+ const [connected, setConnected] = useState(socket.connected);
useEffect(() => {
- if (!socket) {
- // Connect to the server - use relative path for Tailscale compatibility
- socket = io({
- path: '/socket.io',
- transports: ['websocket', 'polling']
- });
+ const handleConnect = () => setConnected(true);
+ const handleDisconnect = () => setConnected(false);
- socket.on('connect', () => {
- setConnected(true);
- });
+ socket.on('connect', handleConnect);
+ socket.on('disconnect', handleDisconnect);
- socket.on('disconnect', () => {
- setConnected(false);
- });
- }
+ // Set initial state
+ setConnected(socket.connected);
return () => {
- // Don't disconnect on component unmount - keep socket alive
+ socket.off('connect', handleConnect);
+ socket.off('disconnect', handleDisconnect);
};
}, []);
diff --git a/server/services/history.js b/server/services/history.js
index 55f690d4fe..b3547a1e64 100644
--- a/server/services/history.js
+++ b/server/services/history.js
@@ -10,6 +10,11 @@ const DATA_DIR = join(__dirname, '../../data');
const HISTORY_FILE = join(DATA_DIR, 'history.json');
const MAX_ENTRIES = 500;
+// In-memory cache with TTL
+let historyCache = null;
+let cacheTimestamp = 0;
+const CACHE_TTL_MS = 2000; // 2 second cache TTL
+
async function ensureDataDir() {
if (!existsSync(DATA_DIR)) {
await mkdir(DATA_DIR, { recursive: true });
@@ -17,14 +22,24 @@ async function ensureDataDir() {
}
async function loadHistory() {
+ // Return cached data if still valid
+ const now = Date.now();
+ if (historyCache && (now - cacheTimestamp) < CACHE_TTL_MS) {
+ return historyCache;
+ }
+
await ensureDataDir();
if (!existsSync(HISTORY_FILE)) {
- return { entries: [] };
+ historyCache = { entries: [] };
+ cacheTimestamp = now;
+ return historyCache;
}
const content = await readFile(HISTORY_FILE, 'utf-8');
- return JSON.parse(content);
+ historyCache = JSON.parse(content);
+ cacheTimestamp = now;
+ return historyCache;
}
async function saveHistory(data) {
@@ -33,6 +48,9 @@ async function saveHistory(data) {
if (data.entries.length > MAX_ENTRIES) {
data.entries = data.entries.slice(-MAX_ENTRIES);
}
+ // Update cache with new data
+ historyCache = data;
+ cacheTimestamp = Date.now();
await writeFile(HISTORY_FILE, JSON.stringify(data, null, 2));
}
diff --git a/server/services/memory.js b/server/services/memory.js
index 04cff48d4f..c8b15837db 100644
--- a/server/services/memory.js
+++ b/server/services/memory.js
@@ -182,6 +182,7 @@ export async function createMemory(data, embedding = null) {
relatedMemories: data.relatedMemories || [],
sourceTaskId: data.sourceTaskId || null,
sourceAgentId: data.sourceAgentId || null,
+ sourceAppId: data.sourceAppId || null,
embedding: embedding || null,
embeddingModel: embedding ? DEFAULT_MEMORY_CONFIG.embeddingModel : null,
confidence: data.confidence ?? 0.8,
@@ -206,7 +207,8 @@ export async function createMemory(data, embedding = null) {
summary: memory.summary,
importance: memory.importance,
createdAt: memory.createdAt,
- status: memory.status
+ status: memory.status,
+ sourceAppId: memory.sourceAppId
});
index.count = index.memories.length;
await saveIndex(index);
@@ -269,6 +271,11 @@ export async function getMemories(options = {}) {
memories = memories.filter(m => m.tags.some(t => options.tags.includes(t)));
}
+ // Filter by app
+ if (options.appId) {
+ memories = memories.filter(m => m.sourceAppId === options.appId);
+ }
+
// Sort
const sortBy = options.sortBy || 'createdAt';
const sortOrder = options.sortOrder || 'desc';
@@ -296,7 +303,7 @@ export async function updateMemory(id, updates) {
if (!memory) return null;
// Apply updates
- const updatableFields = ['content', 'summary', 'category', 'tags', 'confidence', 'importance', 'relatedMemories', 'status', 'expiresAt'];
+ const updatableFields = ['content', 'summary', 'category', 'tags', 'confidence', 'importance', 'relatedMemories', 'status', 'expiresAt', 'sourceAppId'];
for (const field of updatableFields) {
if (updates[field] !== undefined) {
memory[field] = updates[field];
@@ -323,7 +330,8 @@ export async function updateMemory(id, updates) {
summary: memory.summary,
importance: memory.importance,
createdAt: memory.createdAt,
- status: memory.status
+ status: memory.status,
+ sourceAppId: memory.sourceAppId
};
await saveIndex(index);
}
@@ -335,6 +343,32 @@ export async function updateMemory(id, updates) {
});
}
+/**
+ * Update a memory's embedding
+ */
+export async function updateMemoryEmbedding(id, embedding) {
+ return withMemoryLock(async () => {
+ const memory = await loadMemory(id);
+ if (!memory) return null;
+
+ // Update memory with new embedding
+ memory.embedding = embedding;
+ memory.embeddingModel = DEFAULT_MEMORY_CONFIG.embeddingModel;
+ memory.updatedAt = new Date().toISOString();
+ await saveMemory(memory);
+
+ // Update embeddings file
+ const embeddings = await loadEmbeddings();
+ embeddings.vectors[id] = embedding;
+ embeddings.model = DEFAULT_MEMORY_CONFIG.embeddingModel;
+ embeddings.dimension = embedding.length;
+ await saveEmbeddings(embeddings);
+
+ console.log(`🧠 Memory embedding updated: ${id}`);
+ return memory;
+ });
+}
+
/**
* Delete a memory (soft delete by default)
*/
@@ -492,10 +526,11 @@ export async function searchMemories(queryEmbedding, options = {}) {
const meta = indexMap.get(r.id);
if (!meta || meta.status !== 'active') return null;
- // Apply type/category/tag filters
+ // Apply type/category/tag/app filters
if (options.types && options.types.length > 0 && !options.types.includes(meta.type)) return null;
if (options.categories && options.categories.length > 0 && !options.categories.includes(meta.category)) return null;
if (options.tags && options.tags.length > 0 && !meta.tags.some(t => options.tags.includes(t))) return null;
+ if (options.appId && meta.sourceAppId !== options.appId) return null;
return { ...meta, similarity: r.similarity };
})
@@ -524,6 +559,11 @@ export async function getTimeline(options = {}) {
memories = memories.filter(m => options.types.includes(m.type));
}
+ // Filter by app
+ if (options.appId) {
+ memories = memories.filter(m => m.sourceAppId === options.appId);
+ }
+
// Sort by date descending
memories.sort((a, b) => (b.createdAt > a.createdAt ? 1 : -1));
@@ -638,8 +678,18 @@ export async function getGraphData() {
const edges = [];
const seenEdges = new Set();
+ // Batch load all memories to avoid N+1 query pattern
+ // Load all memories in parallel instead of sequential loadMemory calls
+ const memoryLoadPromises = activeMemories.map(m => loadMemory(m.id));
+ const loadedMemories = await Promise.all(memoryLoadPromises);
+ const memoriesById = new Map();
+ loadedMemories.forEach((mem, idx) => {
+ if (mem) memoriesById.set(activeMemories[idx].id, mem);
+ });
+
+ // Build explicit link edges using pre-loaded memories
for (const memory of activeMemories) {
- const full = await loadMemory(memory.id);
+ const full = memoriesById.get(memory.id);
if (!full) continue;
// Explicit links
@@ -761,10 +811,17 @@ export async function applyDecay(decayRate = 0.01) {
const now = Date.now();
let updated = 0;
- for (const meta of index.memories) {
- if (meta.status !== 'active') continue;
+ // Filter active memories first
+ const activeMemories = index.memories.filter(m => m.status === 'active');
+
+ // Batch load all active memories to avoid N+1 query pattern
+ const memoryLoadPromises = activeMemories.map(m => loadMemory(m.id));
+ const loadedMemories = await Promise.all(memoryLoadPromises);
- const memory = await loadMemory(meta.id);
+ // Process each loaded memory
+ for (let i = 0; i < activeMemories.length; i++) {
+ const meta = activeMemories[i];
+ const memory = loadedMemories[i];
if (!memory) continue;
const ageInDays = (now - new Date(memory.createdAt).getTime()) / (1000 * 60 * 60 * 24);
@@ -798,10 +855,17 @@ export async function clearExpired() {
const now = new Date().toISOString();
let cleared = 0;
- for (const meta of index.memories) {
- if (meta.status !== 'active') continue;
+ // Filter active memories first
+ const activeMemories = index.memories.filter(m => m.status === 'active');
+
+ // Batch load all active memories to avoid N+1 query pattern
+ const memoryLoadPromises = activeMemories.map(m => loadMemory(m.id));
+ const loadedMemories = await Promise.all(memoryLoadPromises);
- const memory = await loadMemory(meta.id);
+ // Process each loaded memory
+ for (let i = 0; i < activeMemories.length; i++) {
+ const meta = activeMemories[i];
+ const memory = loadedMemories[i];
if (!memory) continue;
if (memory.expiresAt && memory.expiresAt < now) {