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

refactor: extract shared utilities for DRY compliance

Adam Eivy14e088b3f892
diff --git a/client/src/components/cos/tabs/TasksTab.jsx b/client/src/components/cos/tabs/TasksTab.jsx
index 2355f86c1b..b000e9184a 100644
--- a/client/src/components/cos/tabs/TasksTab.jsx
+++ b/client/src/components/cos/tabs/TasksTab.jsx
@@ -16,6 +16,7 @@ import {
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import * as api from '../../../services/api';
+import { processScreenshotUploads } from '../../../utils/fileUpload';
import TaskItem from './TaskItem';
import SortableTaskItem from './SortableTaskItem';
@@ -120,51 +121,12 @@ export default function TasksTab({ tasks, onRefresh, providers, apps }) {
}
};
- // Screenshot handling - limit to 10MB per file
- const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
-
+ // Screenshot handling using shared utility
const handleFileSelect = async (e) => {
- const files = Array.from(e.target.files);
- for (const file of files) {
- if (!file.type.startsWith('image/')) continue;
- if (file.size > MAX_FILE_SIZE) {
- toast.error(`File "${file.name}" exceeds 10MB limit`);
- continue;
- }
-
- const reader = new FileReader();
- reader.onload = async (ev) => {
- const result = ev?.target?.result;
- if (typeof result !== 'string') {
- console.error('❌ Failed to read file: unexpected FileReader result type');
- return;
- }
-
- const parts = result.split(',');
- if (parts.length < 2) {
- console.error('❌ Failed to read file: unexpected data URL format');
- return;
- }
-
- const base64 = parts[1];
- const uploaded = await api.uploadScreenshot(base64, file.name, file.type).catch((err) => {
- console.error(`❌ Failed to upload screenshot: ${err.message}`);
- return null;
- });
- if (uploaded) {
- setScreenshots(prev => [...prev, {
- id: uploaded.id,
- filename: uploaded.filename,
- preview: result,
- path: uploaded.path
- }]);
- }
- };
- reader.onerror = (err) => {
- console.error(`❌ FileReader failed to read file: ${err.message}`);
- };
- reader.readAsDataURL(file);
- }
+ await processScreenshotUploads(e.target.files, {
+ onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),
+ onError: (msg) => toast.error(msg)
+ });
e.target.value = '';
};
diff --git a/client/src/pages/DevTools.jsx b/client/src/pages/DevTools.jsx
index 68a2b8d749..a46418c42f 100644
--- a/client/src/pages/DevTools.jsx
+++ b/client/src/pages/DevTools.jsx
@@ -5,6 +5,7 @@ import toast from 'react-hot-toast';
import * as api from '../services/api';
import socket from '../services/socket';
import { formatTime, formatRuntime } from '../utils/formatters';
+import { processScreenshotUploads } from '../utils/fileUpload';
export function HistoryPage() {
const [history, setHistory] = useState([]);
@@ -885,43 +886,10 @@ ${prompt.trim()}`;
};
const handleFileSelect = async (e) => {
- const files = Array.from(e.target.files);
- for (const file of files) {
- if (!file.type.startsWith('image/')) continue;
-
- const reader = new FileReader();
- reader.onload = async (ev) => {
- const result = ev?.target?.result;
- if (typeof result !== 'string') {
- console.error('Failed to read file: unexpected FileReader result type');
- return;
- }
-
- const parts = result.split(',');
- if (parts.length < 2) {
- console.error('Failed to read file: unexpected data URL format');
- return;
- }
-
- const base64 = parts[1];
- const uploaded = await api.uploadScreenshot(base64, file.name, file.type).catch((err) => {
- console.error('Failed to upload screenshot', err);
- return null;
- });
- if (uploaded) {
- setScreenshots(prev => [...prev, {
- id: uploaded.id,
- filename: uploaded.filename,
- preview: result,
- path: uploaded.path
- }]);
- }
- };
- reader.onerror = (err) => {
- console.error('FileReader failed to read file', err);
- };
- reader.readAsDataURL(file);
- }
+ await processScreenshotUploads(e.target.files, {
+ onSuccess: (fileInfo) => setScreenshots(prev => [...prev, fileInfo]),
+ onError: (msg) => toast.error(msg)
+ });
e.target.value = '';
};
diff --git a/client/src/utils/fileUpload.js b/client/src/utils/fileUpload.js
new file mode 100644
index 0000000000..212de70387
--- /dev/null
+++ b/client/src/utils/fileUpload.js
@@ -0,0 +1,102 @@
+/**
+ * Shared file upload utilities
+ * Used by DevTools Runner and CoS TasksTab for screenshot uploads
+ */
+
+import * as api from '../services/api';
+
+// Default max file size: 10MB
+const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
+
+/**
+ * Process and upload image files as screenshots
+ *
+ * @param {FileList|File[]} files - Files to process
+ * @param {Object} options - Upload options
+ * @param {number} options.maxFileSize - Max file size in bytes (default: 10MB)
+ * @param {Function} options.onSuccess - Callback for successful upload (receives uploaded file info)
+ * @param {Function} options.onError - Callback for errors (receives error message)
+ * @returns {Promise<void>}
+ */
+export async function processScreenshotUploads(files, options = {}) {
+ const {
+ maxFileSize = DEFAULT_MAX_FILE_SIZE,
+ onSuccess,
+ onError
+ } = options;
+
+ const fileArray = Array.from(files);
+
+ for (const file of fileArray) {
+ // Skip non-image files silently
+ if (!file.type.startsWith('image/')) continue;
+
+ // Check file size
+ if (file.size > maxFileSize) {
+ const sizeMB = Math.round(maxFileSize / (1024 * 1024));
+ onError?.(`File "${file.name}" exceeds ${sizeMB}MB limit`);
+ continue;
+ }
+
+ await uploadScreenshotFile(file, { onSuccess, onError });
+ }
+}
+
+/**
+ * Upload a single screenshot file
+ *
+ * @param {File} file - File to upload
+ * @param {Object} options - Upload options
+ * @param {Function} options.onSuccess - Callback for successful upload
+ * @param {Function} options.onError - Callback for errors
+ * @returns {Promise<Object|null>} Uploaded file info or null on failure
+ */
+export async function uploadScreenshotFile(file, options = {}) {
+ const { onSuccess, onError } = options;
+
+ return new Promise((resolve) => {
+ const reader = new FileReader();
+
+ reader.onload = async (ev) => {
+ const result = ev?.target?.result;
+ if (typeof result !== 'string') {
+ onError?.('Failed to read file: unexpected result type');
+ resolve(null);
+ return;
+ }
+
+ const parts = result.split(',');
+ if (parts.length < 2) {
+ onError?.('Failed to read file: invalid data URL format');
+ resolve(null);
+ return;
+ }
+
+ const base64 = parts[1];
+ const uploaded = await api.uploadScreenshot(base64, file.name, file.type).catch((err) => {
+ onError?.(`Failed to upload: ${err.message}`);
+ return null;
+ });
+
+ if (uploaded) {
+ const fileInfo = {
+ id: uploaded.id,
+ filename: uploaded.filename,
+ preview: result,
+ path: uploaded.path
+ };
+ onSuccess?.(fileInfo);
+ resolve(fileInfo);
+ } else {
+ resolve(null);
+ }
+ };
+
+ reader.onerror = () => {
+ onError?.('Failed to read file');
+ resolve(null);
+ };
+
+ reader.readAsDataURL(file);
+ });
+}
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 97a107fd56..b6fe8bf00f 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -242,6 +242,48 @@ function extractErrorFromOutput(output, exitCode) {
};
}
+/**
+ * Process post-completion tasks: memory extraction and app cooldown
+ * Shared between handleAgentCompletion (runner mode) and spawnDirectly (direct mode)
+ */
+async function processAgentCompletion(agentId, task, success, outputBuffer) {
+ // Extract memories from successful output
+ if (success && outputBuffer.length > 100) {
+ const memoryResult = await extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {
+ console.log(`⚠️ Memory extraction failed: ${err.message}`);
+ return { created: 0, pendingApproval: 0 };
+ });
+ if (memoryResult.created > 0 || memoryResult.pendingApproval > 0) {
+ await updateAgent(agentId, {
+ memoryExtraction: {
+ created: memoryResult.created,
+ pendingApproval: memoryResult.pendingApproval,
+ extractedAt: new Date().toISOString()
+ }
+ });
+ }
+ }
+
+ // Handle app cooldown
+ const appId = task.metadata?.app;
+ if (appId) {
+ const config = await getConfig();
+ const cooldownMs = config.appReviewCooldownMs || 3600000;
+
+ const issuesFound = success ? 1 : 0;
+ const issuesFixed = success ? 1 : 0;
+ await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {
+ emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });
+ });
+
+ await startAppCooldown(appId, cooldownMs).catch(err => {
+ emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });
+ });
+
+ emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });
+ }
+}
+
// Active agent processes
const activeAgents = new Map();
@@ -679,42 +721,8 @@ async function handleAgentCompletion(agentId, exitCode, success, duration) {
});
}
- // Extract memories from successful output
- if (success && outputBuffer.length > 100) {
- const memoryResult = await extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {
- console.log(`⚠️ Memory extraction failed: ${err.message}`);
- return { created: 0, pendingApproval: 0 };
- });
- // Update agent with memory extraction result
- if (memoryResult.created > 0 || memoryResult.pendingApproval > 0) {
- await updateAgent(agentId, {
- memoryExtraction: {
- created: memoryResult.created,
- pendingApproval: memoryResult.pendingApproval,
- extractedAt: new Date().toISOString()
- }
- });
- }
- }
-
- // Handle app cooldown
- const appId = task.metadata?.app;
- if (appId) {
- const config = await getConfig();
- const cooldownMs = config.appReviewCooldownMs || 3600000;
-
- const issuesFound = success ? 1 : 0;
- const issuesFixed = success ? 1 : 0;
- await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {
- emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });
- });
-
- await startAppCooldown(appId, cooldownMs).catch(err => {
- emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });
- });
-
- emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });
- }
+ // Process memory extraction and app cooldown
+ await processAgentCompletion(agentId, task, success, outputBuffer);
runnerAgents.delete(agentId);
}
@@ -835,40 +843,8 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, provid
});
}
- if (success && outputBuffer.length > 100) {
- const memoryResult = await extractAndStoreMemories(agentId, task.id, outputBuffer, task).catch(err => {
- console.log(`⚠️ Memory extraction failed: ${err.message}`);
- return { created: 0, pendingApproval: 0 };
- });
- // Update agent with memory extraction result
- if (memoryResult.created > 0 || memoryResult.pendingApproval > 0) {
- await updateAgent(agentId, {
- memoryExtraction: {
- created: memoryResult.created,
- pendingApproval: memoryResult.pendingApproval,
- extractedAt: new Date().toISOString()
- }
- });
- }
- }
-
- const appId = task.metadata?.app;
- if (appId) {
- const config = await getConfig();
- const cooldownMs = config.appReviewCooldownMs || 3600000;
-
- const issuesFound = success ? 1 : 0;
- const issuesFixed = success ? 1 : 0;
- await markAppReviewCompleted(appId, issuesFound, issuesFixed).catch(err => {
- emitLog('warn', `Failed to mark app review completed: ${err.message}`, { appId });
- });
-
- await startAppCooldown(appId, cooldownMs).catch(err => {
- emitLog('warn', `Failed to start app cooldown: ${err.message}`, { appId });
- });
-
- emitLog('info', `App ${appId} cooldown started (${Math.round(cooldownMs / 60000)} min)`, { appId, cooldownMs });
- }
+ // Process memory extraction and app cooldown
+ await processAgentCompletion(agentId, task, success, outputBuffer);
unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
activeAgents.delete(agentId);