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: fix code quality findings across server and client
Adam Eivy0bf4d0ca15ce
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex c8ac211f2b..0e87eb8138 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -103,7 +103,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fasetTemplateNameInput('');api.getCosPopularTemplates(8).then(data => setTemplates(data.templates || []))- .catch(() => {});+ .catch(err => console.warn('refresh templates:', err.message));}}, [newTask, templateNameInput, showTemplateSave]);diff --git a/client/src/components/meatspace/HealthCategorySection.jsx b/client/src/components/meatspace/HealthCategorySection.jsxindex 666d10a529..fd61234978 100644--- a/client/src/components/meatspace/HealthCategorySection.jsx+++ b/client/src/components/meatspace/HealthCategorySection.jsx@@ -45,7 +45,7 @@ export default function HealthCategorySection({ category, from, to, expanded, onif (emptyMetrics.length > 0) {api.getLatestHealthMetrics(emptyMetrics).then(latest => { if (!cancelled) setLatestValues(prev => ({ ...prev, ...latest })); })- .catch(() => {});+ .catch(err => console.warn('fetch latest health metrics:', err.message));}});diff --git a/client/src/hooks/useAgentFeedbackToast.jsx b/client/src/hooks/useAgentFeedbackToast.jsxindex 18ff7957ea..d046b146de 100644--- a/client/src/hooks/useAgentFeedbackToast.jsx+++ b/client/src/hooks/useAgentFeedbackToast.jsx@@ -40,7 +40,7 @@ function AgentFeedbackToast({ t, agentData, onFeedback }) {setLoadingOutput(true);api.getCosAgent(agentId).then(data => setOutput(data?.output || []))- .catch(() => {})+ .catch(err => console.warn('fetch agent output:', err.message)).finally(() => setLoadingOutput(false));}}, [expanded, output.length, loadingOutput, agentId]);diff --git a/client/src/pages/Browser.jsx b/client/src/pages/Browser.jsxindex b264e5197b..d28b0f0c8b 100644--- a/client/src/pages/Browser.jsx+++ b/client/src/pages/Browser.jsx@@ -84,7 +84,7 @@ export default function BrowserPage() {getBrowserConfig().then(c => {setConfig(c);setConfigDraft(c);- }).catch(() => {});+ }).catch(err => console.warn('load browser config:', err.message));}}, [showConfig, config]);diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsxindex a021f728b4..3988447950 100644--- a/client/src/pages/DevTools.jsx+++ b/client/src/pages/DevTools.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useRef, Fragment } from 'react';+import { useState, useEffect, useRef, useCallback, Fragment } from 'react';import { useLocation, useNavigate } from 'react-router-dom';import { Clock, RefreshCw, Activity, Image, X, XCircle, Cpu, MemoryStick, Terminal, Trash2, MessageSquarePlus, Info, Save, RotateCcw } from 'lucide-react';import ProcessesTab from '../components/apps/tabs/ProcessesTab';@@ -18,11 +18,7 @@ export function HistoryPage() {const [confirmingClear, setConfirmingClear] = useState(false);const [expandedId, setExpandedId] = useState(null);- useEffect(() => {- loadData();- }, [filter]);-- const loadData = async () => {+ const loadData = useCallback(async () => {setLoading(true);const [historyData, statsData, actionsData] = await Promise.all([api.getHistory({@@ -37,7 +33,11 @@ export function HistoryPage() {setStats(statsData);setActions(actionsData);setLoading(false);- };+ }, [filter]);++ useEffect(() => {+ loadData();+ }, [loadData]);const handleClear = async () => {await api.clearHistory();diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex 123fc9a02d..52af36457f 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -78,7 +78,7 @@ export default function Shell() {.map(a => ({ name: a.name, path: a.repoPath })).sort((a, b) => a.name.localeCompare(b.name))))- .catch(() => {});+ .catch(err => console.warn('fetch app folders:', err.message));}, []);// Close dropdown on outside clickdiff --git a/server/services/contextUpgrader.js b/server/services/contextUpgrader.jsdeleted file mode 100644index a10478bbc3..0000000000--- a/server/services/contextUpgrader.js+++ /dev/null@@ -1,331 +0,0 @@-/**- * Context Upgrader Service- *- * Analyzes if a task needs more context or a heavier model.- * Provides recommendations for model/context upgrades.- */--import * as thinkingLevels from './thinkingLevels.js'-import * as localThinking from './localThinking.js'-import { cosEvents } from './cosEvents.js'--// Upgrade triggers-const UPGRADE_TRIGGERS = {- // Context-based triggers- longContext: {- threshold: 5000,- suggestUpgrade: true,- suggestHeavyModel: true- },- multiFileChange: {- fileCount: 3,- suggestUpgrade: true,- suggestHeavyModel: false- },-- // Complexity-based triggers- highComplexity: {- threshold: 0.7,- suggestUpgrade: true,- suggestHeavyModel: true- },- architecturalChange: {- suggestUpgrade: true,- suggestHeavyModel: true- },-- // Error-based triggers- previousFailure: {- suggestUpgrade: true,- suggestHeavyModel: true- },- consecutiveFailures: {- threshold: 2,- suggestUpgrade: true,- suggestHeavyModel: true- }-}--// Upgrade history tracking-const upgradeHistory = []-const MAX_HISTORY = 200--/**- * Analyze if a task needs context or model upgrade- *- * @param {Object} task - Task to analyze- * @param {Object} context - Current context- * @returns {Promise<Object>} - Upgrade recommendations- */-async function analyzeTaskNeedsUpgrade(task, context = {}) {- const recommendations = {- needsUpgrade: false,- suggestHeavyModel: false,- suggestMoreContext: false,- currentLevel: context.thinkingLevel || 'medium',- suggestedLevel: null,- reasons: [],- confidence: 0- }-- // Check context length- const contextLength = context.contextLength || (task.description?.length || 0)- if (contextLength > UPGRADE_TRIGGERS.longContext.threshold) {- recommendations.needsUpgrade = true- recommendations.suggestHeavyModel = true- recommendations.reasons.push(`Context length (${contextLength}) exceeds threshold`)- }-- // Check for multi-file changes (from task metadata or keywords)- const fileReferences = countFileReferences(task.description || '')- if (fileReferences >= UPGRADE_TRIGGERS.multiFileChange.fileCount) {- recommendations.needsUpgrade = true- recommendations.reasons.push(`Multiple file changes detected (${fileReferences} files)`)- }-- // Get local complexity analysis if available- const analysis = await localThinking.analyzeTask(task)- if (analysis.complexity > UPGRADE_TRIGGERS.highComplexity.threshold) {- recommendations.needsUpgrade = true- recommendations.suggestHeavyModel = true- recommendations.reasons.push(`High complexity score (${analysis.complexity.toFixed(2)})`)- }-- // Check for architectural keywords- if (hasArchitecturalKeywords(task.description || '')) {- recommendations.needsUpgrade = true- recommendations.suggestHeavyModel = true- recommendations.reasons.push('Architectural change detected')- }-- // Check for previous failures- if (context.previousAttempts > 0 && context.previousSuccess === false) {- recommendations.needsUpgrade = true- recommendations.suggestHeavyModel = true- recommendations.reasons.push('Previous attempt failed')- }-- if (context.consecutiveFailures >= UPGRADE_TRIGGERS.consecutiveFailures.threshold) {- recommendations.needsUpgrade = true- recommendations.suggestHeavyModel = true- recommendations.reasons.push(`${context.consecutiveFailures} consecutive failures`)- }-- // Determine suggested level- if (recommendations.needsUpgrade) {- const suggestedLevel = thinkingLevels.suggestLevel(analysis)- const currentLevelIndex = Object.keys(thinkingLevels.THINKING_LEVELS).indexOf(recommendations.currentLevel)- const suggestedLevelIndex = Object.keys(thinkingLevels.THINKING_LEVELS).indexOf(suggestedLevel)-- if (suggestedLevelIndex > currentLevelIndex) {- recommendations.suggestedLevel = suggestedLevel- } else if (recommendations.suggestHeavyModel) {- recommendations.suggestedLevel = thinkingLevels.upgradeLevel(recommendations.currentLevel)- }-- recommendations.confidence = calculateConfidence(recommendations.reasons.length)- }-- // Record analysis- recordUpgradeAnalysis(task.id, recommendations)-- return recommendations-}--/**- * Count file references in text- * @param {string} text - Text to analyze- * @returns {number} - Number of file references- */-function countFileReferences(text) {- const filePatterns = [- /\.(js|ts|jsx|tsx|py|go|rs|java|c|cpp|h|hpp)(?:\s|$|,|:)/g,- /(?:file|component|module|service|route|model)s?\s*:/gi,- /(?:create|modify|update|edit|change)\s+(?:the\s+)?(?:file|component)/gi- ]-- let count = 0- for (const pattern of filePatterns) {- const matches = text.match(pattern)- if (matches) count += matches.length- }-- return count-}--/**- * Check for architectural change keywords- * @param {string} text - Text to analyze- * @returns {boolean} - True if architectural keywords found- */-function hasArchitecturalKeywords(text) {- const keywords = [- 'architect', 'restructure', 'redesign', 'migration',- 'refactor entire', 'overhaul', 'rewrite', 'new system',- 'database schema', 'api design', 'infrastructure'- ]-- const lower = text.toLowerCase()- return keywords.some(k => lower.includes(k))-}--/**- * Calculate confidence score based on trigger count- * @param {number} triggerCount - Number of triggers hit- * @returns {number} - Confidence 0-1- */-function calculateConfidence(triggerCount) {- if (triggerCount === 0) return 0- if (triggerCount === 1) return 0.6- if (triggerCount === 2) return 0.8- return 0.95-}--/**- * Record upgrade analysis for learning- * @param {string} taskId - Task identifier- * @param {Object} recommendations - Upgrade recommendations- */-function recordUpgradeAnalysis(taskId, recommendations) {- upgradeHistory.unshift({- taskId,- timestamp: Date.now(),- needsUpgrade: recommendations.needsUpgrade,- suggestedLevel: recommendations.suggestedLevel,- reasons: recommendations.reasons,- confidence: recommendations.confidence- })-- while (upgradeHistory.length > MAX_HISTORY) {- upgradeHistory.pop()- }-}--/**- * Record upgrade outcome for learning- * @param {string} taskId - Task identifier- * @param {boolean} wasSuccessful - Whether upgrade led to success- */-function recordUpgradeOutcome(taskId, wasSuccessful) {- const entry = upgradeHistory.find(h => h.taskId === taskId)- if (entry) {- entry.outcome = wasSuccessful ? 'success' : 'failure'- entry.resolvedAt = Date.now()- }-- cosEvents.emit('upgrade:outcomeRecorded', { taskId, wasSuccessful })-}--/**- * Get upgrade statistics- * @returns {Object} - Upgrade statistics- */-function getStats() {- const recent = upgradeHistory.filter(h => h.outcome)- const upgradedTasks = recent.filter(h => h.needsUpgrade)- const successfulUpgrades = upgradedTasks.filter(h => h.outcome === 'success')-- return {- totalAnalyses: upgradeHistory.length,- upgradesRecommended: upgradeHistory.filter(h => h.needsUpgrade).length,- upgradeSuccessRate: upgradedTasks.length > 0- ? ((successfulUpgrades.length / upgradedTasks.length) * 100).toFixed(1) + '%'- : 'N/A',- commonReasons: getCommonReasons(),- recentUpgrades: upgradeHistory.slice(0, 10).map(h => ({- taskId: h.taskId,- suggestedLevel: h.suggestedLevel,- outcome: h.outcome || 'pending'- }))- }-}--/**- * Get most common upgrade reasons- * @returns {Object} - Reason counts- */-function getCommonReasons() {- const reasons = {}-- for (const entry of upgradeHistory) {- if (!entry.needsUpgrade) continue-- for (const reason of entry.reasons) {- // Normalize reason- const normalized = reason.split('(')[0].trim()- reasons[normalized] = (reasons[normalized] || 0) + 1- }- }-- return reasons-}--/**- * Should upgrade based on quick heuristics (no async)- * @param {Object} task - Task to check- * @param {Object} context - Current context- * @returns {boolean} - True if upgrade likely needed- */-function quickCheckNeedsUpgrade(task, context = {}) {- const description = task.description || ''-- // Quick length check- if (description.length > UPGRADE_TRIGGERS.longContext.threshold) {- return true- }-- // Quick keyword check- if (hasArchitecturalKeywords(description)) {- return true- }-- // Priority check- const priority = task.priority?.toUpperCase()- if (priority === 'URGENT' || priority === 'CRITICAL') {- return true- }-- // Failure check- if (context.previousSuccess === false) {- return true- }-- return false-}--/**- * Get upgrade history- * @param {Object} options - Filter options- * @returns {Array} - Upgrade history- */-function getHistory(options = {}) {- let history = [...upgradeHistory]-- if (options.needsUpgrade !== undefined) {- history = history.filter(h => h.needsUpgrade === options.needsUpgrade)- }-- if (options.outcome) {- history = history.filter(h => h.outcome === options.outcome)- }-- const limit = options.limit || 50- return history.slice(0, limit)-}--/**- * Clear upgrade history- */-function clearHistory() {- upgradeHistory.length = 0-}--export {- analyzeTaskNeedsUpgrade,- recordUpgradeOutcome,- getStats,- getHistory,- clearHistory,- quickCheckNeedsUpgrade,- UPGRADE_TRIGGERS-}diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 129ba932d7..32ffc63726 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -9,7 +9,7 @@ import { cosEvents } from './cosEvents.js'// Default LM Studio configurationconst DEFAULT_CONFIG = {- baseUrl: 'http://localhost:1234',+ baseUrl: process.env.LM_STUDIO_URL || 'http://localhost:1234',timeout: 30000,defaultThinkingModel: 'gpt-oss-20b'}diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.jsindex 4ccc0f1320..b6cb39855c 100644--- a/server/services/memoryClassifier.js+++ b/server/services/memoryClassifier.js@@ -21,7 +21,7 @@ const MEMORY_CONFIG_FILE = join(CONFIG_DIR, 'memory-classifier-config.json');const DEFAULT_CONFIG = {enabled: true,provider: 'lmstudio',- endpoint: 'http://localhost:1234/v1/chat/completions',+ endpoint: process.env.LM_STUDIO_URL ? `${process.env.LM_STUDIO_URL}/v1/chat/completions` : 'http://localhost:1234/v1/chat/completions',model: 'gptoss-20b',timeout: 60000,maxOutputLength: 10000,