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
fix: address third round of PR review feedback
Adam Eivyeb607994017a
diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 456de5cd65..43ff636e4b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -136,7 +136,7 @@ export const getRunOutput = (id) => request(`/runs/${id}/output`);export const getRunPrompt = (id) => request(`/runs/${id}/prompt`);export const stopRun = (id) => request(`/runs/${id}/stop`, { method: 'POST' });export const deleteRun = (id) => request(`/runs/${id}`, { method: 'DELETE' });-export const deleteFailedRuns = () => request('/runs', { method: 'DELETE' });+export const deleteFailedRuns = () => request('/runs?confirm=true', { method: 'DELETE' });// Historyexport const getHistory = (options = {}) => {diff --git a/ecosystem.config.cjs b/ecosystem.config.cjsindex 145fc89852..4b705bf422 100644--- a/ecosystem.config.cjs+++ b/ecosystem.config.cjs@@ -87,6 +87,9 @@ module.exports = {script: 'browser/server.js',cwd: __dirname,interpreter: 'node',+ // Browser service exposes CDP on 0.0.0.0 for Tailscale remote access+ // Unlike cos-runner, this is safe because CDP already has its own auth+ // and browser instances are sandboxed. Accessed via PortOS UI remotely.ports: { cdp: 5556, health: 5557 },env: {NODE_ENV: 'development',diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 4de7ecccc6..361cf72ac5 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -42,14 +42,40 @@ const io = new SocketServer(server, {cors: { origin: '*' }});+/**+ * Validate JSON string before parsing+ */+function isValidJSON(str) {+ if (!str || !str.trim()) return false;+ const trimmed = str.trim();+ // Check for basic JSON structure+ if (!(trimmed.startsWith('{') && trimmed.endsWith('}'))) return false;+ // Check for common corruption patterns+ if (trimmed.endsWith('}}') || trimmed.includes('}{')) return false;+ return true;+}+/*** Load runner state from disk*/async function loadState() {+ const defaultState = { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };+if (!existsSync(STATE_FILE)) {- return { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };+ return defaultState;}+const content = await readFile(STATE_FILE, 'utf-8');++ if (!isValidJSON(content)) {+ console.log('⚠️ Corrupted or empty state file, returning default state');+ // Backup the corrupted file for debugging+ const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`;+ await writeFile(backupPath, content).catch(() => {});+ console.log(`📝 Backed up corrupted state to ${backupPath}`);+ return defaultState;+ }+return JSON.parse(content);}diff --git a/server/routes/runs.js b/server/routes/runs.jsindex e209570afc..978868ce6d 100644--- a/server/routes/runs.js+++ b/server/routes/runs.js@@ -171,8 +171,15 @@ router.delete('/:id', asyncHandler(async (req, res, next) => {res.status(204).send();}));-// DELETE /api/runs/failed - Delete all failed runs+// DELETE /api/runs - Delete all failed runs+// Requires ?confirm=true query parameter to prevent accidental deletionrouter.delete('/', asyncHandler(async (req, res, next) => {+ if (req.query.confirm !== 'true') {+ throw new ServerError('Destructive operation requires ?confirm=true', {+ status: 400,+ code: 'CONFIRMATION_REQUIRED'+ });+ }const deletedCount = await runner.deleteFailedRuns();res.json({ deleted: deletedCount });}));diff --git a/server/routes/screenshots.js b/server/routes/screenshots.jsindex aa5fc601b8..f3b65ec3e5 100644--- a/server/routes/screenshots.js+++ b/server/routes/screenshots.js@@ -15,8 +15,16 @@ const router = Router();// Max file size: 10MBconst MAX_FILE_SIZE = 10 * 1024 * 1024;-// Validate image magic bytes+/**+ * Validate image magic bytes+ * Note: This validates the file signature/magic bytes at the start of the file.+ * It does NOT validate the entire file structure - a file could have valid magic+ * bytes but malformed content. This is sufficient for basic type detection and+ * blocking non-image uploads. For high-security scenarios, consider using a+ * proper image processing library to fully validate the file structure.+ */function isValidImage(buffer) {+ if (buffer.length < 12) return null; // Too small to be a valid image// PNG: 89 50 4E 47if (buffer[0] === 0x89 && buffer[1] === 0x50 && buffer[2] === 0x4E && buffer[3] === 0x47) {return 'png';diff --git a/server/services/cos.js b/server/services/cos.jsindex d60e94bd8f..c6e3e1ab7f 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -133,6 +133,19 @@ async function ensureDirectories() {}}+/**+ * Validate JSON string before parsing+ */+function isValidJSON(str) {+ if (!str || !str.trim()) return false;+ const trimmed = str.trim();+ // Check for basic JSON structure+ if (!(trimmed.startsWith('{') && trimmed.endsWith('}'))) return false;+ // Check for common corruption patterns+ if (trimmed.endsWith('}}') || trimmed.includes('}{')) return false;+ return true;+}+/*** Load CoS state*/@@ -144,6 +157,16 @@ async function loadState() {}const content = await readFile(STATE_FILE, 'utf-8');++ if (!isValidJSON(content)) {+ console.log(`⚠️ Corrupted or empty state file at ${STATE_FILE}, returning default state`);+ // Backup the corrupted file for debugging+ const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`;+ await writeFile(backupPath, content).catch(() => {});+ console.log(`📝 Backed up corrupted state to ${backupPath}`);+ return { ...DEFAULT_STATE };+ }+const state = JSON.parse(content);// Merge with defaults to ensure all fields existdiff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 18056da025..24bc6c39b2 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -113,6 +113,10 @@ export async function spawnAgentViaRunner(options) {claudePath} = options;+ // Create abort controller for timeout (60 seconds for agent spawn)+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 60000);+const response = await fetch(`${COS_RUNNER_URL}/spawn`, {method: 'POST',headers: { 'Content-Type': 'application/json' },@@ -124,8 +128,9 @@ export async function spawnAgentViaRunner(options) {model,envVars,claudePath- })- });+ }),+ signal: controller.signal+ }).finally(() => clearTimeout(timeoutId));if (!response.ok) {const error = await response.json();diff --git a/server/services/runner.js b/server/services/runner.jsindex d15c234980..6df2c0ddbc 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -23,11 +23,16 @@ const RUNS_DIR = join(DATA_DIR, 'runs');/*** Safe JSON parse with fallback to empty object+ * Logs parse errors for debugging corrupted metadata files*/function safeJsonParse(str, fallback = {}) {try {return JSON.parse(str);- } catch {+ } catch (err) {+ // Log only if str is not empty/default - empty strings are expected from .catch(() => '{}')+ if (str && str !== '{}') {+ console.warn(`⚠️ JSON parse failed: ${err.message} (input: ${str.slice(0, 100)}...)`);+ }return fallback;}}@@ -142,6 +147,8 @@ function categorizeError(output, exitCode) {const lowerOutput = output.toLowerCase();// API/Model errors - check specific patterns first+ // Model not found requires BOTH "model:" AND a not-found pattern to avoid false positives+ // from legitimate output that might contain just "model:" in a different contextif (lowerOutput.includes('not_found_error') && lowerOutput.includes('model:')) {return { category: 'model_not_found', suggestion: 'The specified model does not exist - check AI provider settings and select a valid model' };}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex bf17bca94e..734d96f638 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -87,6 +87,10 @@ function selectModelForTask(task, provider) {}// Detect coding/development tasks - these should NEVER use light model+ // Intentionally inclusive: if a task mentions any coding-related term (even in+ // broader context like "bug report template"), we err on the side of using+ // a stronger model since misclassifying a coding task is more costly than+ // over-allocating resources for a documentation task.const isCodingTask = /\b(fix|bug|implement|develop|code|refactor|test|feature|function|class|module|api|endpoint|component|service|route|schema|migration|script|build|deploy|debug|error|exception|crash|issue|patch)\b/.test(desc);// Simple/quick tasks → haiku/light (ONLY for non-coding tasks)@@ -469,7 +473,10 @@ const runnerAgents = new Map();* This allows us to receive completion events for agents spawned before restart*/async function syncRunnerAgents() {- const agents = await getActiveAgentsFromRunner().catch(() => []);+ const agents = await getActiveAgentsFromRunner().catch(err => {+ console.error(`❌ Failed to get active agents from runner: ${err.message}`);+ return [];+ });if (agents.length === 0) return 0;console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);