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: consolidate duplicate duration formatters onto utils/formatters (#2028)
Adam Eivyed7418ddb302
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 71bac5ba93..ece1ac4793 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,4 +10,5 @@## Internal+- Consolidated five component-local duration/uptime/time-until formatters onto the shared `utils/formatters.js` helpers (`formatDurationMs`, `timeUntil`), per the "do not re-define formatters inside components" convention (#2028). `formatDurationMs` gained a day bucket (`2d 3h`) so long uptimes no longer render as an unbounded hours count; ProcessesTab, CityHud, Shell session ages, the CoS QuickSummary "next job" countdown, and the Loops interval label now all route through the shared helpers, and a `console.log` in `memoryClassifier.js` was collapsed to a single interpolated line.- Migration 155 heals `data/prompts/stages/cd-treatment.md` installs that #1808's anchor-based migration 148 left stranded (#2042). Installs seeded before the `imageStrength` scene knob (older pre-#1808 template) got the `## Cast & ingredients` list but missed the per-scene `"cast": [{ "ingredientId": … }]` field, so the Creative Director cast-threading regression test stayed red on the runtime template and migration 148 (already applied) never re-ran. The new hash-driven prompt-replace upgrades those copies (and both pristine pre-#1808 shipped versions) to the current shipped reference, leaving hand-customized copies untouched. Also folds `cd-treatment.md` into `buildPromptDriftTables` so setup-data.js's drift warning classifies a stranded copy correctly.diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsxindex db8e995d79..46f9a43d95 100644--- a/client/src/components/apps/tabs/ProcessesTab.jsx+++ b/client/src/components/apps/tabs/ProcessesTab.jsx@@ -5,17 +5,7 @@ import { executeCommand } from '../../../services/api';import socket from '../../../services/socket';import BrailleSpinner from '../../BrailleSpinner';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';-import { formatBytes } from '../../../utils/formatters';--const formatUptime = (ms) => {- if (!ms) return '-';- const hours = Math.floor(ms / 3600000);- const mins = Math.floor((ms % 3600000) / 60000);- if (hours > 24) {- return `${Math.floor(hours / 24)}d ${hours % 24}h`;- }- return `${hours}h ${mins}m`;-};+import { formatBytes, formatDurationMs } from '../../../utils/formatters';const getStatusClasses = (status) => {switch (status) {@@ -174,7 +164,7 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {<td className="px-4 py-3 text-gray-400 font-mono text-sm">{proc.pid || '-'}</td><td className="px-4 py-3 text-gray-400">{proc.cpu ? `${proc.cpu}%` : '-'}</td><td className="px-4 py-3 text-gray-400">{formatBytes(proc.memory)}</td>- <td className="px-4 py-3 text-gray-400">{formatUptime(proc.uptime)}</td>+ <td className="px-4 py-3 text-gray-400">{proc.uptime ? formatDurationMs(proc.uptime) : '-'}</td><td className="px-4 py-3 text-gray-400">{proc.restarts}</td><td className="px-4 py-3 text-right"><div className="flex justify-end gap-1">diff --git a/client/src/components/city/CityHud.jsx b/client/src/components/city/CityHud.jsxindex 4b1737fbf9..56aade99b3 100644--- a/client/src/components/city/CityHud.jsx+++ b/client/src/components/city/CityHud.jsx@@ -5,6 +5,7 @@ import CityAgentBar from './CityAgentBar';import CityFilterBar from './CityFilterBar';import CityXpBadge from './CityXpBadge';import CityMiniMap from './CityMiniMap';+import { formatDurationMs } from '../../utils/formatters';// WASD controls hint shown briefly on first exploration entryfunction ControlsHint({ visible }) {@@ -49,16 +50,6 @@ function ControlsHint({ visible }) {);}-// Format uptime from page load-const formatUptime = (seconds) => {- const h = Math.floor(seconds / 3600);- const m = Math.floor((seconds % 3600) / 60);- const s = Math.floor(seconds % 60);- if (h > 0) return `${h}h ${m}m`;- if (m > 0) return `${m}m ${s}s`;- return `${s}s`;-};-const getHealthSentinel = (systemHealth, onlineRatio) => {if (systemHealth?.overallHealth === 'critical') return { dot: 'bg-port-error', text: 'text-port-error', label: 'CRITICAL' };if (systemHealth?.overallHealth === 'warning') return { dot: 'bg-port-warning', text: 'text-port-warning', label: 'WARN' };@@ -213,7 +204,7 @@ export default function CityHud({ cosStatus, cosAgents, agentMap, eventLogs, con<div className="flex items-center justify-between gap-6"><span className="font-pixel text-[10px] text-gray-400 tracking-wide">UPTIME</span><span className="font-pixel text-[11px] text-cyan-400" style={{ textShadow: '0 0 6px rgba(6,182,212,0.4)' }}>- {formatUptime(uptimeSeconds)}+ {formatDurationMs(uptimeSeconds * 1000)}</span></div>diff --git a/client/src/components/cos/QuickSummary.jsx b/client/src/components/cos/QuickSummary.jsxindex a151f4bb60..15b70866e7 100644--- a/client/src/components/cos/QuickSummary.jsx+++ b/client/src/components/cos/QuickSummary.jsx@@ -18,6 +18,7 @@ import {} from 'lucide-react';import * as api from '../../services/api';import { useAutoRefetch } from '../../hooks/useAutoRefetch';+import { timeUntil } from '../../utils/formatters';/*** QuickSummary - At-a-glance dashboard widget for CoS status@@ -76,22 +77,6 @@ export default function QuickSummary() {const velocityDisplay = getVelocityDisplay();- // Format time until next job- const formatTimeUntil = (isoDate) => {- if (!isoDate) return null;- const now = Date.now();- const due = new Date(isoDate).getTime();- const diffMs = due - now;-- if (diffMs <= 0) return 'now';-- const minutes = Math.floor(diffMs / 60000);- const hours = Math.floor(minutes / 60);-- if (hours > 0) return `${hours}h ${minutes % 60}m`;- return `${minutes}m`;- };-return (<div className="bg-gradient-to-r from-port-card to-port-bg border border-port-border rounded-lg p-3 mb-4"><div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">@@ -253,7 +238,7 @@ export default function QuickSummary() {{nextJob.jobName?.replace(/^(self-improvement|app-improvement|task)-/, '').replace(/-/g, ' ')}</span><span className="text-gray-500 text-xs">- {nextJob.isDue ? 'due' : formatTimeUntil(nextJob.nextDueAt)}+ {nextJob.isDue ? 'due' : timeUntil(nextJob.nextDueAt)}</span></div>)}diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 1127391754..b09f4ed8f9 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -362,13 +362,6 @@ export const detectAutonomyLevel = (config) => {return null; // Custom configuration};-// Format milliseconds as human-readable interval-export const formatInterval = (ms) => {- if (ms < 60000) return `${ms / 1000}s`;- if (ms < 3600000) return `${ms / 60000}min`;- return `${ms / 3600000}hr`;-};-// Avatar style labels for displayexport const AVATAR_STYLE_LABELS = {svg: 'Digital (SVG)',diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsxindex cedb6856c3..90d2b08943 100644--- a/client/src/pages/Loops.jsx+++ b/client/src/pages/Loops.jsx@@ -7,7 +7,7 @@ import * as api from '../services/api';import socket from '../services/socket';import toast from '../components/ui/Toast';import { timeAgo } from '../components/feature-agents/constants';-import { formatInterval } from '../components/cos/constants';+import { formatDurationMs } from '../utils/formatters';import BrailleSpinner from '../components/BrailleSpinner';import { useAutoRefetch } from '../hooks/useAutoRefetch';@@ -234,7 +234,7 @@ function LoopCard({ loop, onAction, expandedId, onToggle }) {<div className="flex items-center gap-2"><span className="text-sm font-medium text-gray-200 truncate">{loop.name}</span><StatusBadge loop={loop} />- <span className="text-xs text-gray-500">every {formatInterval(loop.intervalMs)}</span>+ <span className="text-xs text-gray-500">every {formatDurationMs(loop.intervalMs)}</span></div><div className="flex items-center gap-3 mt-0.5 text-xs text-gray-500"><span>#{loop.currentIteration || 0} iterations</span>diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsxindex 9afe52d97e..74df56274b 100644--- a/client/src/pages/Shell.jsx+++ b/client/src/pages/Shell.jsx@@ -9,6 +9,7 @@ import { useThemeContext } from '../components/ThemeContext';import { RefreshCw, Power, PowerOff, FolderOpen, ChevronDown, Plus, X, Terminal as TerminalIcon, ClipboardPaste, OctagonX, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft, Bot, Maximize2, Minimize2 } from 'lucide-react';import * as api from '../services/api';import { readClipboard } from '../lib/clipboard';+import { formatDurationMs } from '../utils/formatters';import { buildTerminalTheme, parseCssColorToHex } from '../lib/terminalTheme';// Must match MAX_TOTAL_SESSIONS in server/services/shell.js@@ -68,15 +69,6 @@ const readTerminalTheme = () => {}, mode);};-const formatAge = (createdAt) => {- const seconds = Math.floor((Date.now() - createdAt) / 1000);- if (seconds < 60) return `${seconds}s`;- const minutes = Math.floor(seconds / 60);- if (minutes < 60) return `${minutes}m`;- const hours = Math.floor(minutes / 60);- return `${hours}h${minutes % 60}m`;-};-const shortId = (id) => id?.slice(0, 6) ?? '';// Touch-friendly TUI-driving controls shared by the inline quick-commands toolbar@@ -959,12 +951,12 @@ export default function Shell() {: 'bg-port-card hover:bg-port-border text-gray-400 hover:text-white border border-port-border'}`}onClick={() => !isActive && switchToSession(s.sessionId)}- title={`${isRun ? 'Live TUI run — ' : ''}${s.label || s.cwd || shortId(s.sessionId)} — ${formatAge(s.createdAt)} old`}+ title={`${isRun ? 'Live TUI run — ' : ''}${s.label || s.cwd || shortId(s.sessionId)} — ${formatDurationMs(Date.now() - s.createdAt)} old`}><TabIcon size={12} className="shrink-0" /><span className="min-w-0 break-all">{label}</span>{isRun && <span className="w-1.5 h-1.5 rounded-full bg-port-accent animate-pulse shrink-0" title="Live" />}- <span className="text-[10px] opacity-60 shrink-0">{formatAge(s.createdAt)}</span>+ <span className="text-[10px] opacity-60 shrink-0">{formatDurationMs(Date.now() - s.createdAt)}</span><buttononClick={(e) => { e.stopPropagation(); killOtherSession(s.sessionId); }}className={`shrink-0 ml-0.5 p-0.5 rounded transition-colors ${diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex 8f433ffeb7..748b45f5f8 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -282,9 +282,11 @@ export function parseTimeoutMs(raw) {}/**- * Format a duration in milliseconds as a human-readable string+ * Format a duration in milliseconds as a human-readable string. Buckets down+ * from days so multi-day uptimes read as "2d 3h" rather than an unbounded+ * hours count ("51h 0m").* @param {number} ms - Duration in milliseconds- * @returns {string} Formatted duration (e.g., "45s", "3m 12s", "2h 5m")+ * @returns {string} Formatted duration (e.g., "45s", "3m 12s", "2h 5m", "2d 3h")*/export function formatDurationMs(ms) {if (ms == null) return '-';@@ -293,7 +295,9 @@ export function formatDurationMs(ms) {const minutes = Math.floor(seconds / 60);if (minutes < 60) return `${minutes}m ${seconds % 60}s`;const hours = Math.floor(minutes / 60);- return `${hours}h ${minutes % 60}m`;+ if (hours < 24) return `${hours}h ${minutes % 60}m`;+ const days = Math.floor(hours / 24);+ return `${days}d ${hours % 24}h`;}/**diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex 6877fa0cc4..a49948cd12 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest';import {- formatContextLength, formatDurationMin, formatEventDateTime, timeAgo,+ formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo,formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs,} from './formatters.js';@@ -22,6 +22,26 @@ describe('formatContextLength', () => {});});+describe('formatDurationMs', () => {+ it('formats sub-minute, minute, and hour buckets', () => {+ expect(formatDurationMs(0)).toBe('0s');+ expect(formatDurationMs(45_000)).toBe('45s');+ expect(formatDurationMs(72_000)).toBe('1m 12s');+ expect(formatDurationMs(2 * 3_600_000 + 5 * 60_000)).toBe('2h 5m');+ });++ it('buckets multi-day durations into days + hours', () => {+ expect(formatDurationMs(24 * 3_600_000)).toBe('1d 0h');+ expect(formatDurationMs(25 * 3_600_000)).toBe('1d 1h');+ expect(formatDurationMs(51 * 3_600_000)).toBe('2d 3h');+ });++ it('returns a dash for nullish input', () => {+ expect(formatDurationMs(null)).toBe('-');+ expect(formatDurationMs(undefined)).toBe('-');+ });+});+describe('formatDurationMin', () => {it('formats sub-hour, exact-hour, and hour+min durations', () => {expect(formatDurationMin(30)).toBe('30m');diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.jsindex 2fbba0b1ae..d5e779d9ce 100644--- a/server/services/memoryClassifier.js+++ b/server/services/memoryClassifier.js@@ -380,7 +380,7 @@ export async function classifyMemories(task, agentOutput) {const result = parseLLMResponse(llmResponse);if (result.parseError) {- console.log('⚠️ Failed to parse LLM response, raw:', llmResponse.substring(0, 200));+ console.log(`⚠️ Failed to parse LLM response, raw: ${llmResponse.substring(0, 200)}`);return {memories: [],rejected: [],