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: reuse shared formatBytes/sleep/pathExists/SSE/stripAnsi helpers (#2526)
Adam Eivy70950f79ed10
diff --git a/server/routes/ask.js b/server/routes/ask.jsindex 3469f4b4a9..3c796b5c15 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -23,6 +23,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { awaitWritableDrain } from '../lib/streamBackpressure.js';+import { SSE_HEADERS } from '../lib/sseHeaders.js';import * as convs from '../services/askConversations.js';import { runAsk, VALID_MODES } from '../services/askService.js';import { ID_RE as CONV_ID_RE } from '../services/askConversations.js';@@ -144,13 +145,9 @@ router.post('/', asyncHandler(async (req, res) => {});conversation = afterUser;- // SSE handshake.- res.set({- 'Content-Type': 'text/event-stream',- 'Cache-Control': 'no-cache, no-transform',- Connection: 'keep-alive',- 'X-Accel-Buffering': 'no',- });+ // SSE handshake. Shared SSE_HEADERS plus `no-transform` — this stream must+ // never be proxy-compressed/transformed, which the shared default omits.+ res.set({ ...SSE_HEADERS, 'Cache-Control': 'no-cache, no-transform' });res.flushHeaders?.();// Propagate client disconnects (browser nav, tab close, abort) intodiff --git a/server/routes/database.js b/server/routes/database.jsindex 03df2e3ae3..ef4bc8e267 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -6,6 +6,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, databaseSwitchSchema, databaseBackendSchema, databaseExportSchema } from '../lib/validation.js';import { checkHealth, query } from '../lib/db.js';import { PATHS } from '../lib/fileUtils.js';+import { stripAnsi } from '../lib/ansiStrip.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';import { resolveBashBinary } from '../lib/bashResolver.js';@@ -24,8 +25,6 @@ const bashBinary = resolveBashBinary();const router = Router();-const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, '');-/*** Run a command and return { stdout, stderr, exitCode }.*/diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 7eb0e402fa..4864df44ed 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -9,6 +9,7 @@ import { checkHealth } from '../lib/db.js';import { getCurrentVersion } from '../services/updateChecker.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { getMemoryStats } from '../lib/memoryStats.js';+import { formatBytes } from '../lib/fileUtils.js';import { getSettings, updateSettingsWith } from '../services/settings.js';// Defaults are tuned for a real dev machine: memory routinely sits in the@@ -181,13 +182,6 @@ router.get('/health/details', asyncHandler(async (req, res) => {} : null;// Format memory for display- const formatBytes = (bytes) => {- const gb = bytes / (1024 * 1024 * 1024);- if (gb >= 1) return `${gb.toFixed(1)}GB`;- const mb = bytes / (1024 * 1024);- return `${mb.toFixed(0)}MB`;- };-// Format uptime for displayconst uptime = process.uptime();const days = Math.floor(uptime / 86400);diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex 6abc026a3c..4922abd59a 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -1,3 +1,4 @@+import { formatBytes as formatBytesRaw } from '../lib/fileUtils.js'import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import { readResponseJson } from '../lib/readResponseJson.js'import { LOCAL_LLM_CATEGORIES, isBackend } from '../lib/localLlmCatalog.js'@@ -221,16 +222,12 @@ function pickGgufFile(model) {.sort((a, b) => a.priority - b.priority || (a.size || Number.MAX_SAFE_INTEGER) - (b.size || Number.MAX_SAFE_INTEGER))[0]}+// Delegates formatting to the shared fileUtils.formatBytes, but returns `null`+// (not the shared helper's "0 B") for unknown/zero sizes so callers can fall+// back to a quant/label string via `formatBytes(x) || fallback`.function formatBytes(bytes) {if (!Number.isFinite(bytes) || bytes <= 0) return null- const units = ['B', 'KB', 'MB', 'GB', 'TB']- let value = bytes- let idx = 0- while (value >= 1024 && idx < units.length - 1) {- value /= 1024- idx++- }- return `${value >= 10 || idx === 0 ? value.toFixed(0) : value.toFixed(1)} ${units[idx]}`+ return formatBytesRaw(bytes)}function extractParams(repoId) {diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex a7f124130d..39a4e2e0aa 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -23,12 +23,12 @@import { execFile, spawn } from 'child_process'import { promisify } from 'util'import { readFileSync, createWriteStream } from 'fs'-import { stat, rm } from 'fs/promises'+import { rm } from 'fs/promises'import { join } from 'path'import { tmpdir } from 'os'import { pipeline } from 'stream/promises'import { Readable } from 'stream'-import { PATHS, atomicWrite, ensureDir } from '../lib/fileUtils.js'+import { PATHS, atomicWrite, ensureDir, pathExists } from '../lib/fileUtils.js'import { compareSemver } from '../lib/versionUtils.js'import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'import { sanitizeOllamaName } from '../lib/localLlmDisk.js'@@ -96,11 +96,6 @@ function macAppPath(backend) {return backend === 'ollama' ? '/Applications/Ollama.app' : '/Applications/LM Studio.app'}-async function pathExists(p) {- if (!p) return false- return stat(p).then(() => true).catch(() => false)-}-/*** Where did this install of `backend` come from? Decides which upgrade path is* actually safe to run — `brew upgrade ollama` against a `.app`-installeddiff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex e9c91e1a90..3af4e44f34 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -33,6 +33,7 @@ import { randomUUID } from 'crypto';import { unlink } from 'fs/promises';import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';import { PATHS, readJSONFile, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';+import { SSE_HEADERS } from '../../lib/sseHeaders.js';import { reapAndCleanDetachedDirs } from '../../lib/detachedSpawn.js';import {broadcastSse,@@ -1039,11 +1040,7 @@ export function attachSseClient(jobId, res) {job.status === 'completed' ? { type: 'complete', result: job.result }: job.status === 'canceled' ? { type: 'canceled', reason: job.error || 'Canceled' }: { type: 'error', error: job.error || `Job ${job.status}` };- res.writeHead(200, {- 'Content-Type': 'text/event-stream',- 'Cache-Control': 'no-cache',- Connection: 'keep-alive',- });+ res.writeHead(200, SSE_HEADERS);res.write(`data: ${JSON.stringify(terminal)}\n\n`);res.end();return true;diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.jsindex d0e7e49d82..3d9646bbaa 100644--- a/server/services/pipeline/seriesAutopilot.js+++ b/server/services/pipeline/seriesAutopilot.js@@ -67,6 +67,7 @@import { randomUUID } from 'crypto';import { EventEmitter } from 'events';+import { sleep } from '../../lib/fileUtils.js';import { broadcastSse, attachSseClient, SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';import { getDomainMode } from '../../lib/domainAutonomy.js';import { parseComicScript } from '../../lib/comicScriptParser.js';@@ -435,8 +436,6 @@ export const VISUAL_DRAFT_ENABLED = true;// Poll cadence while awaiting a delegated child runner (volume beats / auto-run).const CHILD_POLL_MS = 750;-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));-// ---------------------------------------------------------------------------// Pure next-step resolver — the heart of the conductor (no I/O; unit-tested).// ---------------------------------------------------------------------------diff --git a/server/services/youtubeSync.js b/server/services/youtubeSync.jsindex 1a1a857ad4..0a8f5bc39c 100644--- a/server/services/youtubeSync.js+++ b/server/services/youtubeSync.js@@ -29,7 +29,7 @@* The pure mappers (video-id parse, day-label resolution, candidate mapping) are* exported and unit-tested against saved DOM-shaped fixtures — no browser or DB.*/-import { dataPath, ensureDir, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { dataPath, ensureDir, atomicWrite, tryReadFile, safeJSONParse, sleep } from '../lib/fileUtils.js';import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';import { getSettings } from './settings.js';import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';@@ -253,8 +253,6 @@ async function writeSyncState(state) {// failure returns a status report the UI renders (mirrors message lastSyncStatus).// ----------------------------------------------------------------------------const sleep = (ms) => new Promise((r) => setTimeout(r, ms));-// Ensure the managed browser has the history page loaded and return the CDP page// object, or a { status } report when it can't. If a YouTube tab is open on a// different path, navigate it to the history feed in place (CDP re-attaches to