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 PR review feedback (round 2)
Adam Eivy501772df0758
diff --git a/client/src/components/DirectoryPicker.jsx b/client/src/components/DirectoryPicker.jsxindex c8199d5241..30b40e0d86 100644--- a/client/src/components/DirectoryPicker.jsx+++ b/client/src/components/DirectoryPicker.jsx@@ -13,7 +13,7 @@ export default function DirectoryPicker({ value, onChange, label = 'Select DirecuseEffect(() => {// Load directories and auto-set value if none providedloadDirectories(value || null, !value);- }, []);+ }, [value]);const loadDirectories = async (path = null, setAsValue = false) => {setLoading(true);diff --git a/client/src/components/brain/tabs/TrustTab.jsx b/client/src/components/brain/tabs/TrustTab.jsxindex 125544a03d..91d29547a3 100644--- a/client/src/components/brain/tabs/TrustTab.jsx+++ b/client/src/components/brain/tabs/TrustTab.jsx@@ -45,8 +45,14 @@ export default function TrustTab({ onRefresh }) {}, [fetchData]);const handleSaveSettings = async () => {+ const threshold = parseFloat(settingsForm.confidenceThreshold);+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {+ toast.error('Confidence threshold must be a number between 0 and 1');+ return;+ }+const result = await api.updateBrainSettings({- confidenceThreshold: parseFloat(settingsForm.confidenceThreshold),+ confidenceThreshold: threshold,dailyDigestTime: settingsForm.dailyDigestTime,weeklyReviewTime: settingsForm.weeklyReviewTime,weeklyReviewDay: settingsForm.weeklyReviewDaydiff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsxindex 2eb9d8bdb7..03234d66b2 100644--- a/client/src/pages/PromptManager.jsx+++ b/client/src/pages/PromptManager.jsx@@ -155,7 +155,13 @@ export default function PromptManager() {const deleteStage = async (stageName) => {// Check if stage is in use- const usageRes = await fetch(`/api/prompts/${stageName}/usage`).then(r => r.json());+ let usageRes;+ const usageResponse = await fetch(`/api/prompts/${stageName}/usage`).catch(() => null);+ if (!usageResponse || !usageResponse.ok) {+ usageRes = { isSystemStage: false, usedBy: [] };+ } else {+ usageRes = await usageResponse.json().catch(() => ({ isSystemStage: false, usedBy: [] }));+ }let confirmMessage = `Delete stage "${stageName}"?`;diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 95caa7132d..d383e2296f 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -220,7 +220,16 @@ app.post('/spawn', async (req, res) => {let command, spawnArgs;if (cliCommand && cliArgs) {command = cliCommand;- spawnArgs = cliArgs;+ // Normalize cliArgs to an array+ if (Array.isArray(cliArgs)) {+ spawnArgs = cliArgs;+ } else if (typeof cliArgs === 'string') {+ spawnArgs = [cliArgs];+ } else {+ return res.status(400).json({+ error: 'Invalid cliArgs: expected an array or string'+ });+ }} else {// Legacy: Claude-specific argscommand = claudePath;diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsnew file mode 100644index 0000000000..6cd84c9308--- /dev/null+++ b/server/lib/fileUtils.test.js@@ -0,0 +1,294 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { writeFile, rm, mkdir } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import {+ isValidJSON,+ safeJSONParse,+ safeJSONLParse,+ readJSONFile,+ readJSONLFile+} from './fileUtils.js';++describe('fileUtils', () => {+ describe('isValidJSON', () => {+ it('should return true for valid JSON object', () => {+ expect(isValidJSON('{"key": "value"}')).toBe(true);+ });++ it('should return true for valid JSON array when allowed', () => {+ expect(isValidJSON('[1, 2, 3]')).toBe(true);+ });++ it('should return false for JSON array when not allowed', () => {+ expect(isValidJSON('[1, 2, 3]', { allowArray: false })).toBe(false);+ });++ it('should return false for empty string', () => {+ expect(isValidJSON('')).toBe(false);+ });++ it('should return false for whitespace-only string', () => {+ expect(isValidJSON(' ')).toBe(false);+ });++ it('should return false for null', () => {+ expect(isValidJSON(null)).toBe(false);+ });++ it('should return false for undefined', () => {+ expect(isValidJSON(undefined)).toBe(false);+ });++ it('should return false for string not starting with { or [', () => {+ expect(isValidJSON('hello')).toBe(false);+ });++ it('should return false for incomplete object (missing end)', () => {+ expect(isValidJSON('{"key":')).toBe(false);+ });++ it('should return false for incomplete array (missing end)', () => {+ expect(isValidJSON('[1, 2')).toBe(false);+ });++ it('should handle whitespace around valid JSON', () => {+ expect(isValidJSON(' {"key": "value"} ')).toBe(true);+ });++ it('should handle nested objects', () => {+ expect(isValidJSON('{"outer": {"inner": "value"}}')).toBe(true);+ });+ });++ describe('safeJSONParse', () => {+ it('should parse valid JSON object', () => {+ const result = safeJSONParse('{"key": "value"}', {});+ expect(result).toEqual({ key: 'value' });+ });++ it('should parse valid JSON array', () => {+ const result = safeJSONParse('[1, 2, 3]', []);+ expect(result).toEqual([1, 2, 3]);+ });++ it('should return default value for empty string', () => {+ const result = safeJSONParse('', { default: true });+ expect(result).toEqual({ default: true });+ });++ it('should return default value for null input', () => {+ const result = safeJSONParse(null, []);+ expect(result).toEqual([]);+ });++ it('should return default value for invalid JSON', () => {+ const result = safeJSONParse('not json', { fallback: 'value' });+ expect(result).toEqual({ fallback: 'value' });+ });++ it('should return default value for JSON with trailing comma', () => {+ const result = safeJSONParse('{"a": 1,}', {});+ expect(result).toEqual({});+ });++ it('should return default value for truncated JSON', () => {+ const result = safeJSONParse('{"key": "value', {});+ expect(result).toEqual({});+ });++ it('should return null as default when no defaultValue provided', () => {+ const result = safeJSONParse('invalid');+ expect(result).toBe(null);+ });++ it('should reject arrays when allowArray is false', () => {+ const result = safeJSONParse('[1, 2, 3]', {}, { allowArray: false });+ expect(result).toEqual({});+ });++ it('should log error when logError is true', () => {+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ safeJSONParse('invalid', {}, { logError: true });+ expect(consoleSpy).toHaveBeenCalled();+ consoleSpy.mockRestore();+ });++ it('should include context in log message', () => {+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ safeJSONParse('invalid', {}, { logError: true, context: 'test-file.json' });+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('test-file.json'));+ consoleSpy.mockRestore();+ });++ it('should not log for empty input even with logError true', () => {+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ safeJSONParse('', {}, { logError: true });+ expect(consoleSpy).not.toHaveBeenCalled();+ consoleSpy.mockRestore();+ });++ it('should handle syntax error in structurally valid JSON', () => {+ // Passes structural check but fails JSON.parse+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const result = safeJSONParse('{"key": undefined}', { fallback: true }, { logError: true });+ expect(result).toEqual({ fallback: true });+ expect(consoleErrorSpy).toHaveBeenCalled();+ consoleErrorSpy.mockRestore();+ });+ });++ describe('safeJSONLParse', () => {+ it('should parse valid JSONL content', () => {+ const content = '{"a": 1}\n{"b": 2}\n{"c": 3}';+ const result = safeJSONLParse(content);+ expect(result).toEqual([{ a: 1 }, { b: 2 }, { c: 3 }]);+ });++ it('should skip empty lines', () => {+ const content = '{"a": 1}\n\n{"b": 2}\n';+ const result = safeJSONLParse(content);+ expect(result).toEqual([{ a: 1 }, { b: 2 }]);+ });++ it('should skip whitespace-only lines', () => {+ const content = '{"a": 1}\n \n{"b": 2}';+ const result = safeJSONLParse(content);+ expect(result).toEqual([{ a: 1 }, { b: 2 }]);+ });++ it('should skip invalid lines and continue parsing', () => {+ const content = '{"a": 1}\ninvalid json\n{"b": 2}';+ const result = safeJSONLParse(content);+ expect(result).toEqual([{ a: 1 }, { b: 2 }]);+ });++ it('should return empty array for empty content', () => {+ expect(safeJSONLParse('')).toEqual([]);+ });++ it('should return empty array for null content', () => {+ expect(safeJSONLParse(null)).toEqual([]);+ });++ it('should return empty array for whitespace-only content', () => {+ expect(safeJSONLParse(' \n ')).toEqual([]);+ });++ it('should handle single line without trailing newline', () => {+ const result = safeJSONLParse('{"single": "line"}');+ expect(result).toEqual([{ single: 'line' }]);+ });++ it('should reject array values in lines (JSONL expects objects)', () => {+ const content = '{"a": 1}\n[1, 2, 3]\n{"b": 2}';+ const result = safeJSONLParse(content);+ // Arrays are rejected because allowArray: false is passed internally+ expect(result).toEqual([{ a: 1 }, { b: 2 }]);+ });++ it('should handle lines with only truncated JSON', () => {+ const content = '{"complete": true}\n{"incomplete":';+ const result = safeJSONLParse(content);+ expect(result).toEqual([{ complete: true }]);+ });+ });++ describe('readJSONFile', () => {+ const testDir = join(tmpdir(), 'fileutils-test-' + Date.now());++ beforeEach(async () => {+ await mkdir(testDir, { recursive: true });+ });++ afterEach(async () => {+ await rm(testDir, { recursive: true, force: true });+ });++ it('should read and parse valid JSON file', async () => {+ const filePath = join(testDir, 'valid.json');+ await writeFile(filePath, '{"key": "value"}');++ const result = await readJSONFile(filePath, {});+ expect(result).toEqual({ key: 'value' });+ });++ it('should return default value for non-existent file', async () => {+ const result = await readJSONFile('/nonexistent/path.json', { default: true });+ expect(result).toEqual({ default: true });+ });++ it('should return default value for empty file', async () => {+ const filePath = join(testDir, 'empty.json');+ await writeFile(filePath, '');++ const result = await readJSONFile(filePath, { empty: true });+ expect(result).toEqual({ empty: true });+ });++ it('should return default value for corrupted file', async () => {+ const filePath = join(testDir, 'corrupted.json');+ await writeFile(filePath, '{"incomplete":');++ const result = await readJSONFile(filePath, { fallback: true });+ expect(result).toEqual({ fallback: true });+ });++ it('should handle arrays when allowArray is true', async () => {+ const filePath = join(testDir, 'array.json');+ await writeFile(filePath, '[1, 2, 3]');++ const result = await readJSONFile(filePath, []);+ expect(result).toEqual([1, 2, 3]);+ });++ it('should reject arrays when allowArray is false', async () => {+ const filePath = join(testDir, 'array.json');+ await writeFile(filePath, '[1, 2, 3]');++ const result = await readJSONFile(filePath, {}, { allowArray: false });+ expect(result).toEqual({});+ });+ });++ describe('readJSONLFile', () => {+ const testDir = join(tmpdir(), 'fileutils-jsonl-test-' + Date.now());++ beforeEach(async () => {+ await mkdir(testDir, { recursive: true });+ });++ afterEach(async () => {+ await rm(testDir, { recursive: true, force: true });+ });++ it('should read and parse valid JSONL file', async () => {+ const filePath = join(testDir, 'valid.jsonl');+ await writeFile(filePath, '{"a": 1}\n{"b": 2}\n{"c": 3}');++ const result = await readJSONLFile(filePath);+ expect(result).toEqual([{ a: 1 }, { b: 2 }, { c: 3 }]);+ });++ it('should return empty array for non-existent file', async () => {+ const result = await readJSONLFile('/nonexistent/path.jsonl');+ expect(result).toEqual([]);+ });++ it('should return empty array for empty file', async () => {+ const filePath = join(testDir, 'empty.jsonl');+ await writeFile(filePath, '');++ const result = await readJSONLFile(filePath);+ expect(result).toEqual([]);+ });++ it('should skip invalid lines in JSONL file', async () => {+ const filePath = join(testDir, 'mixed.jsonl');+ await writeFile(filePath, '{"valid": 1}\nnot json\n{"also": "valid"}');++ const result = await readJSONLFile(filePath);+ expect(result).toEqual([{ valid: 1 }, { also: 'valid' }]);+ });+ });+});diff --git a/server/lib/taskParser.js b/server/lib/taskParser.jsindex 95ddab81f8..e760f3db69 100644--- a/server/lib/taskParser.js+++ b/server/lib/taskParser.js@@ -87,19 +87,23 @@ function parseTaskLine(line) {};}+// Sentinel prefix for JSON-encoded metadata values+const JSON_SENTINEL = '__json__:';+/*** Unescape newlines in metadata values.*- * For values stored as JSON string literals (produced by escapeNewlines),+ * For values prefixed with the JSON sentinel (produced by escapeNewlines),* this uses JSON.parse to correctly restore backslashes, newlines, etc.* For legacy or simple values, falls back to simple replacement for backwards compatibility.*/function unescapeNewlines(value) {if (typeof value !== 'string') return value;- // Check if this looks like a JSON-encoded string (starts and ends with quotes)- if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {+ // Check for explicit JSON sentinel prefix+ if (value.startsWith(JSON_SENTINEL)) {+ const jsonPart = value.slice(JSON_SENTINEL.length);try {- return JSON.parse(value);+ return JSON.parse(jsonPart);} catch {// Fall through to legacy behavior if parsing fails}@@ -112,13 +116,13 @@ function unescapeNewlines(value) {* Escape newlines in metadata values.** For values containing special characters (newlines, backslashes), uses JSON- * string escaping for reversibility. Simple values are stored as-is.+ * string escaping with a sentinel prefix for reversibility. Simple values are stored as-is.*/function escapeNewlines(value) {if (typeof value !== 'string') return String(value);// Only use JSON encoding if the value contains characters that need escapingif (value.includes('\n') || value.includes('\\')) {- return JSON.stringify(value);+ return JSON_SENTINEL + JSON.stringify(value);}return value;}