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 to reduce code duplication

Adam Eivye3c39729d3e4
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.md
index fae5560c8e..35e1caecec 100644
--- a/.changelog/v0.10.x.md
+++ b/.changelog/v0.10.x.md
@@ -276,10 +276,17 @@ This release introduces a structured changelog documentation system for creating
- `ensureDirs(paths)` - Ensures multiple directories exist
- `dataPath(...segments)` - Get path relative to data directory
- `rootPath(...segments)` - Get path relative to project root
+ - `formatDuration(ms)` - Formats milliseconds as human-readable duration (e.g., "5m", "2h 30m", "3d 5h")
- `PATHS` - Centralized path constants (data, cos, brain, digitalTwin, runs, memory, agents, scripts, reports)
- **Reduced Code Duplication**: Refactored 4 services (`apps.js`, `history.js`, `usage.js`, `notifications.js`) to use shared utility, eliminating identical `ensureDir` implementations and reducing boilerplate
+- **formatDuration Consolidation**: Extracted duplicate `formatDuration` implementations from `cos.js` and `weeklyDigest.js` into shared utility
- **Pattern for Future Refactoring**: Establishes pattern for remaining 7+ services with similar duplicated directory logic
+### DRY Refactoring: Client Formatters
+- **New `client/src/utils/formatters.js` additions**:
+ - `getAppName(appId, apps, fallback)` - Lookup app name from ID with customizable fallback
+- **Reduced Component Duplication**: Extracted duplicate `getAppName` implementations from `MemoryTab.jsx` and `MemoryEditModal.jsx` into shared formatter utility
+
### Chief of Staff - Navigation Improvements
- **Sidebar Sub-Navigation**: Chief of Staff sub-pages (Tasks, Agents, Scripts, Schedule, Digest, Learning, Memory, Health, Config) now appear as children in the sidebar navigation under Chief of Staff, making all tabs accessible without scrolling the page
- **Collapsible Agent Panel**: On mobile, the COS Agent avatar panel is now collapsible with a tap toggle header showing state and running status
diff --git a/client/src/components/cos/tabs/MemoryEditModal.jsx b/client/src/components/cos/tabs/MemoryEditModal.jsx
index 1ddd74b660..db4718a356 100644
--- a/client/src/components/cos/tabs/MemoryEditModal.jsx
+++ b/client/src/components/cos/tabs/MemoryEditModal.jsx
@@ -3,6 +3,7 @@ import { X, Save, Plus, Trash2 } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';
+import { getAppName } from '../../../utils/formatters';
export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
const [formData, setFormData] = useState({
@@ -90,37 +91,30 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
}
};
- // Get app name for display
- const getAppName = (appId) => {
- if (!appId) return 'None';
- const app = apps?.find(a => a.id === appId);
- return app?.name || appId;
- };
-
return (
- <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
- <div className="bg-port-card border border-port-border rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-auto">
+ <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 w-full max-w-2xl max-h-[90vh] overflow-auto">
<div className="flex items-center justify-between mb-4">
- <h2 className="text-xl font-bold text-white">Edit Memory</h2>
+ <h2 className="text-lg sm:text-xl font-bold text-white">Edit Memory</h2>
<button
onClick={onClose}
- className="text-gray-500 hover:text-white transition-colors"
+ className="p-2 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-500 hover:text-white transition-colors rounded-lg"
>
- <X size={20} />
+ <X size={22} />
</button>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
{/* Type */}
<div>
- <label className="block text-sm text-gray-400 mb-1">Type</label>
+ <label className="block text-sm text-gray-400 mb-2">Type</label>
<div className="flex flex-wrap gap-2">
{MEMORY_TYPES.map(type => (
<button
key={type}
type="button"
onClick={() => setFormData({ ...formData, type })}
- className={`px-3 py-1.5 text-sm rounded-lg border transition-colors ${
+ className={`px-4 py-2 min-h-[40px] text-sm rounded-lg border transition-colors ${
formData.type === type
? MEMORY_TYPE_COLORS[type]
: 'border-port-border text-gray-500 hover:text-gray-300'
@@ -134,7 +128,7 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
{/* Content */}
<div>
- <label className="block text-sm text-gray-400 mb-1">
+ <label className="block text-sm text-gray-400 mb-2">
Content <span className="text-port-accent">*</span>
</label>
<textarea
@@ -142,7 +136,7 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
onChange={e => setFormData({ ...formData, content: e.target.value })}
placeholder="Memory content..."
rows={5}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none resize-none"
+ className="w-full px-3 py-3 min-h-[120px] bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none resize-none"
autoFocus
/>
<p className="text-xs text-gray-500 mt-1">
@@ -152,24 +146,24 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
{/* Summary */}
<div>
- <label className="block text-sm text-gray-400 mb-1">Summary (optional)</label>
+ <label className="block text-sm text-gray-400 mb-2">Summary (optional)</label>
<input
type="text"
value={formData.summary}
onChange={e => setFormData({ ...formData, summary: e.target.value })}
placeholder="Brief summary..."
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ className="w-full px-3 py-3 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
/>
</div>
{/* Category and App */}
- <div className="flex gap-3">
+ <div className="flex flex-col sm:flex-row gap-3">
<div className="flex-1">
- <label className="block text-sm text-gray-400 mb-1">Category</label>
+ <label className="block text-sm text-gray-400 mb-2">Category</label>
<select
value={formData.category}
onChange={e => setFormData({ ...formData, category: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ className="w-full px-3 py-3 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
>
<option value="other">Other</option>
<option value="codebase">Codebase</option>
@@ -184,11 +178,11 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
</select>
</div>
<div className="flex-1">
- <label className="block text-sm text-gray-400 mb-1">Associated App</label>
+ <label className="block text-sm text-gray-400 mb-2">Associated App</label>
<select
value={formData.sourceAppId}
onChange={e => setFormData({ ...formData, sourceAppId: e.target.value })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ className="w-full px-3 py-3 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
>
<option value="">None (General)</option>
{apps?.map(app => (
@@ -200,20 +194,20 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
{/* Tags */}
<div>
- <label className="block text-sm text-gray-400 mb-1">Tags</label>
- <div className="flex flex-wrap gap-2 mb-2">
+ <label className="block text-sm text-gray-400 mb-2">Tags</label>
+ <div className="flex flex-wrap gap-2 mb-3">
{formData.tags.map(tag => (
<span
key={tag}
- className="flex items-center gap-1 px-2 py-1 bg-port-border rounded text-sm text-gray-300"
+ className="flex items-center gap-2 px-3 py-2 min-h-[36px] bg-port-border rounded-lg text-sm text-gray-300"
>
{tag}
<button
type="button"
onClick={() => handleRemoveTag(tag)}
- className="text-gray-500 hover:text-port-error transition-colors"
+ className="p-1 min-w-[24px] min-h-[24px] flex items-center justify-center text-gray-500 hover:text-port-error transition-colors"
>
- <Trash2 size={12} />
+ <Trash2 size={14} />
</button>
</span>
))}
@@ -225,23 +219,23 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
onChange={e => setNewTag(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Add tag..."
- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
+ className="flex-1 px-3 py-3 min-h-[44px] bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-none"
/>
<button
type="button"
onClick={handleAddTag}
disabled={!newTag.trim()}
- className="px-3 py-2 bg-port-border hover:bg-port-border/70 text-gray-300 rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ className="px-4 py-3 min-h-[44px] min-w-[44px] flex items-center justify-center bg-port-border hover:bg-port-border/70 text-gray-300 rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
- <Plus size={16} />
+ <Plus size={20} />
</button>
</div>
</div>
{/* Importance and Confidence */}
- <div className="flex gap-3">
+ <div className="flex flex-col sm:flex-row gap-4">
<div className="flex-1">
- <label className="block text-sm text-gray-400 mb-1">
+ <label className="block text-sm text-gray-400 mb-2">
Importance: {(formData.importance * 100).toFixed(0)}%
</label>
<input
@@ -251,11 +245,11 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
step="0.05"
value={formData.importance}
onChange={e => setFormData({ ...formData, importance: parseFloat(e.target.value) })}
- className="w-full accent-port-accent"
+ className="w-full h-8 accent-port-accent"
/>
</div>
<div className="flex-1">
- <label className="block text-sm text-gray-400 mb-1">
+ <label className="block text-sm text-gray-400 mb-2">
Confidence: {(formData.confidence * 100).toFixed(0)}%
</label>
<input
@@ -265,7 +259,7 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
step="0.05"
value={formData.confidence}
onChange={e => setFormData({ ...formData, confidence: parseFloat(e.target.value) })}
- className="w-full accent-port-accent"
+ className="w-full h-8 accent-port-accent"
/>
</div>
</div>
@@ -281,26 +275,26 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {
<div>Agent: {memory.sourceAgentId || fullMemory?.sourceAgentId}</div>
)}
{formData.sourceAppId && (
- <div>App: {getAppName(formData.sourceAppId)}</div>
+ <div>App: {getAppName(formData.sourceAppId, apps, formData.sourceAppId)}</div>
)}
</div>
)}
{/* Actions */}
- <div className="flex justify-end gap-2 pt-2">
+ <div className="flex flex-col-reverse sm:flex-row justify-end gap-2 pt-4">
<button
type="button"
onClick={onClose}
- className="px-4 py-2 text-sm text-gray-400 hover:text-white transition-colors"
+ className="px-4 py-3 min-h-[44px] text-sm text-gray-400 hover:text-white transition-colors rounded-lg"
>
Cancel
</button>
<button
type="submit"
disabled={saving || !formData.content.trim()}
- className="flex items-center gap-2 px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ className="flex items-center justify-center gap-2 px-5 py-3 min-h-[44px] bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
- <Save size={14} />
+ <Save size={18} />
{saving ? 'Saving...' : 'Save Changes'}
</button>
</div>
diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsx
index 12fbb6a614..423b1a9786 100644
--- a/client/src/components/cos/tabs/MemoryTab.jsx
+++ b/client/src/components/cos/tabs/MemoryTab.jsx
@@ -3,6 +3,7 @@ import { RefreshCw, Trash2, X, Check, XCircle, Pencil } from 'lucide-react';
import toast from 'react-hot-toast';
import * as api from '../../../services/api';
import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';
+import { getAppName } from '../../../utils/formatters';
import MemoryTimeline from './MemoryTimeline';
import MemoryGraph from './MemoryGraph';
import MemoryEditModal from './MemoryEditModal';
@@ -69,17 +70,10 @@ export default function MemoryTab({ apps = [] }) {
const displayMemories = searchResults || memories;
- // Get app name for display
- const getAppName = (appId) => {
- if (!appId) return null;
- const app = apps?.find(a => a.id === appId);
- return app?.name || null;
- };
-
return (
<div className="space-y-6">
{/* Header */}
- <div className="flex items-center justify-between">
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
<div>
<h3 className="text-lg font-semibold text-white">Memory System</h3>
<p className="text-sm text-gray-500">
@@ -93,7 +87,7 @@ export default function MemoryTab({ apps = [] }) {
<button
key={v}
onClick={() => setView(v)}
- className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
+ className={`px-4 py-2 min-h-[40px] text-sm rounded-lg transition-colors ${
view === v ? 'bg-port-accent text-white' : 'bg-port-border text-gray-400 hover:text-white'
}`}
>
@@ -111,20 +105,20 @@ export default function MemoryTab({ apps = [] }) {
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
placeholder="Search memories semantically..."
- className="flex-1 bg-port-card border border-port-border rounded-lg px-4 py-2 text-white placeholder-gray-500 focus:border-port-accent outline-none"
+ className="flex-1 bg-port-card border border-port-border rounded-lg px-4 py-2 min-h-[40px] text-white placeholder-gray-500 focus:border-port-accent outline-none"
/>
<button
onClick={handleSearch}
- className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
+ className="px-4 py-2 min-h-[40px] bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors"
>
Search
</button>
{searchResults && (
<button
onClick={() => { setSearchResults(null); setSearchQuery(''); }}
- className="px-3 py-2 bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"
+ className="px-3 py-2 min-h-[40px] min-w-[40px] flex items-center justify-center bg-port-border text-gray-400 hover:text-white rounded-lg transition-colors"
>
- <X size={16} />
+ <X size={18} />
</button>
)}
</div>
@@ -140,7 +134,7 @@ export default function MemoryTab({ apps = [] }) {
: [...filters.types, type];
setFilters({ ...filters, types: newTypes });
}}
- className={`px-3 py-1 text-xs rounded-full border transition-colors ${
+ className={`px-3 py-2 min-h-[36px] text-xs rounded-full border transition-colors ${
filters.types.includes(type) ? MEMORY_TYPE_COLORS[type] : 'border-port-border text-gray-500 hover:text-gray-300'
}`}
>
@@ -167,10 +161,10 @@ export default function MemoryTab({ apps = [] }) {
<h3 className="text-lg font-semibold text-yellow-500">Pending Approval ({pendingMemories.length})</h3>
{pendingMemories.map(memory => (
<div key={memory.id} className="bg-port-card border border-yellow-500/50 rounded-lg p-4">
- <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
<div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 mb-2">
- <span className={`px-2 py-0.5 text-xs rounded-full border ${MEMORY_TYPE_COLORS[memory.type]}`}>
+ <div className="flex flex-wrap items-center gap-2 mb-2">
+ <span className={`px-2 py-1 text-xs rounded-full border ${MEMORY_TYPE_COLORS[memory.type]}`}>
{memory.type}
</span>
<span className="text-xs text-gray-500">{memory.category}</span>
@@ -180,9 +174,9 @@ export default function MemoryTab({ apps = [] }) {
</div>
<p className="text-white text-sm">{memory.summary || memory.content?.substring(0, 200)}</p>
{memory.tags?.length > 0 && (
- <div className="flex gap-1 mt-2">
+ <div className="flex flex-wrap gap-1 mt-2">
{memory.tags.map(tag => (
- <span key={tag} className="px-2 py-0.5 text-xs bg-port-border rounded text-gray-400">
+ <span key={tag} className="px-2 py-1 text-xs bg-port-border rounded text-gray-400">
{tag}
</span>
))}
@@ -190,35 +184,35 @@ export default function MemoryTab({ apps = [] }) {
)}
<div className="text-xs text-gray-500 mt-2 flex flex-wrap gap-2">
<span>{new Date(memory.createdAt).toLocaleDateString()}</span>
- {getAppName(memory.sourceAppId) && (
+ {getAppName(memory.sourceAppId, apps) && (
<>
<span>*</span>
- <span className="text-port-accent">{getAppName(memory.sourceAppId)}</span>
+ <span className="text-port-accent">{getAppName(memory.sourceAppId, apps)}</span>
</>
)}
</div>
</div>
- <div className="flex gap-2">
+ <div className="flex gap-2 sm:flex-col md:flex-row">
<button
onClick={() => setEditingMemory(memory)}
- className="p-2 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg transition-colors"
+ className="flex-1 sm:flex-none p-3 min-h-[44px] min-w-[44px] flex items-center justify-center bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded-lg transition-colors"
title="Edit before approving"
>
- <Pencil size={16} />
+ <Pencil size={20} />
</button>
<button
onClick={() => handleApprove(memory.id)}
- className="p-2 bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded-lg transition-colors"
+ className="flex-1 sm:flex-none p-3 min-h-[44px] min-w-[44px] flex items-center justify-center bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded-lg transition-colors"
title="Approve"
>
- <Check size={16} />
+ <Check size={20} />
</button>
<button
onClick={() => handleReject(memory.id)}
- className="p-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-lg transition-colors"
+ className="flex-1 sm:flex-none p-3 min-h-[44px] min-w-[44px] flex items-center justify-center bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-lg transition-colors"
title="Reject"
>
- <XCircle size={16} />
+ <XCircle size={20} />
</button>
</div>
</div>
@@ -268,10 +262,10 @@ export default function MemoryTab({ apps = [] }) {
) : (
displayMemories.map(memory => (
<div key={memory.id} className="bg-port-card border border-port-border rounded-lg p-4">
- <div className="flex items-start justify-between gap-4">
+ <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
<div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 mb-2">
- <span className={`px-2 py-0.5 text-xs rounded-full border ${MEMORY_TYPE_COLORS[memory.type]}`}>
+ <div className="flex flex-wrap items-center gap-2 mb-2">
+ <span className={`px-2 py-1 text-xs rounded-full border ${MEMORY_TYPE_COLORS[memory.type]}`}>
{memory.type}
</span>
<span className="text-xs text-gray-500">{memory.category}</span>
@@ -281,9 +275,9 @@ export default function MemoryTab({ apps = [] }) {
</div>
<p className="text-white text-sm">{memory.summary || memory.content?.substring(0, 200)}</p>
{memory.tags?.length > 0 && (
- <div className="flex gap-1 mt-2">
+ <div className="flex flex-wrap gap-1 mt-2">
{memory.tags.map(tag => (
- <span key={tag} className="px-2 py-0.5 text-xs bg-port-border rounded text-gray-400">
+ <span key={tag} className="px-2 py-1 text-xs bg-port-border rounded text-gray-400">
{tag}
</span>
))}
@@ -293,28 +287,28 @@ export default function MemoryTab({ apps = [] }) {
<span>{new Date(memory.createdAt).toLocaleDateString()}</span>
<span>*</span>
<span>importance: {((memory.importance || 0.5) * 100).toFixed(0)}%</span>
- {getAppName(memory.sourceAppId) && (
+ {getAppName(memory.sourceAppId, apps) && (
<>
<span>*</span>
- <span className="text-port-accent">{getAppName(memory.sourceAppId)}</span>
+ <span className="text-port-accent">{getAppName(memory.sourceAppId, apps)}</span>
</>
)}
</div>
</div>
- <div className="flex gap-1">
+ <div className="flex gap-2 sm:gap-1">
<button
onClick={() => setEditingMemory(memory)}
- className="p-2 text-gray-500 hover:text-port-accent transition-colors"
+ className="p-3 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-500 hover:text-port-accent transition-colors"
title="Edit memory"
>
- <Pencil size={14} />
+ <Pencil size={18} />
</button>
<button
onClick={() => handleDelete(memory.id)}
- className="p-2 text-gray-500 hover:text-port-error transition-colors"
+ className="p-3 min-h-[40px] min-w-[40px] flex items-center justify-center text-gray-500 hover:text-port-error transition-colors"
title="Archive memory"
>
- <Trash2 size={14} />
+ <Trash2 size={18} />
</button>
</div>
</div>
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index 9ea5ea3a5c..a5fc80f7cf 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -46,3 +46,16 @@ export function formatBytes(bytes, decimals = 1) {
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
}
+
+/**
+ * Get app name from app ID by looking up in apps array
+ * @param {string|null} appId - The app ID to look up
+ * @param {Array<{id: string, name: string}>} apps - Array of app objects
+ * @param {string} fallback - Fallback value if app not found
+ * @returns {string|null} App name or fallback
+ */
+export function getAppName(appId, apps, fallback = null) {
+ if (!appId) return fallback;
+ const app = apps?.find(a => a.id === appId);
+ return app?.name || fallback;
+}
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 2cb46e3396..e659695c56 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -275,3 +275,33 @@ export async function readJSONLFile(filePath, { logErrors = false } = {}) {
}
return safeJSONLParse(content, { logErrors, context: filePath });
}
+
+/**
+ * Format a duration in milliseconds to a human-readable string.
+ * Outputs the most appropriate unit (minutes, hours, days) based on size.
+ *
+ * @param {number} ms - Duration in milliseconds
+ * @returns {string} Formatted duration (e.g., "5m", "2h 30m", "3d 5h")
+ *
+ * @example
+ * formatDuration(30000) // "0m"
+ * formatDuration(300000) // "5m"
+ * formatDuration(7200000) // "2h 0m"
+ * formatDuration(90000000) // "1d 1h"
+ */
+export function formatDuration(ms) {
+ if (!ms) return '0m';
+ const mins = Math.floor(ms / 60000);
+ const hours = Math.floor(mins / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) {
+ const remainingHours = hours % 24;
+ return `${days}d ${remainingHours}h`;
+ }
+ if (hours > 0) {
+ const remainingMins = mins % 60;
+ return `${hours}h ${remainingMins}m`;
+ }
+ return `${mins}m`;
+}
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index 19147c5219..50ac239c17 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -7,7 +7,8 @@ import {
safeJSONParse,
safeJSONLParse,
readJSONFile,
- readJSONLFile
+ readJSONLFile,
+ formatDuration
} from './fileUtils.js';
describe('fileUtils', () => {
@@ -303,4 +304,31 @@ describe('fileUtils', () => {
expect(result).toEqual([{ valid: 1 }, { also: 'valid' }]);
});
});
+
+ describe('formatDuration', () => {
+ it('should return "0m" for zero or falsy values', () => {
+ expect(formatDuration(0)).toBe('0m');
+ expect(formatDuration(null)).toBe('0m');
+ expect(formatDuration(undefined)).toBe('0m');
+ });
+
+ it('should format minutes correctly', () => {
+ expect(formatDuration(60000)).toBe('1m');
+ expect(formatDuration(300000)).toBe('5m');
+ expect(formatDuration(59 * 60000)).toBe('59m');
+ });
+
+ it('should format hours and minutes correctly', () => {
+ expect(formatDuration(60 * 60000)).toBe('1h 0m');
+ expect(formatDuration(90 * 60000)).toBe('1h 30m');
+ expect(formatDuration(150 * 60000)).toBe('2h 30m');
+ });
+
+ it('should format days and hours correctly', () => {
+ expect(formatDuration(24 * 60 * 60000)).toBe('1d 0h');
+ expect(formatDuration(25 * 60 * 60000)).toBe('1d 1h');
+ expect(formatDuration(48 * 60 * 60000)).toBe('2d 0h');
+ expect(formatDuration(50 * 60 * 60000)).toBe('2d 2h');
+ });
+ });
});
diff --git a/server/services/cos.js b/server/services/cos.js
index 2ec6fe6736..965e7b1d09 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -19,6 +19,7 @@ import { getAllApps } from './apps.js';
import { getAdaptiveCooldownMultiplier, getSkippedTaskTypes, getPerformanceSummary, checkAndRehabilitateSkippedTasks } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';
import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';
+import { formatDuration } from '../lib/fileUtils.js';
// Import and re-export cosEvents from separate module to avoid circular dependencies
import { cosEvents as _cosEvents } from './cosEvents.js';
export const cosEvents = _cosEvents;
@@ -2401,17 +2402,6 @@ export async function getTodayActivity() {
return sum + (Date.now() - new Date(a.startedAt).getTime());
}, 0);
- // Format duration as human-readable
- const formatDuration = (ms) => {
- const mins = Math.floor(ms / 60000);
- const hours = Math.floor(mins / 60);
- const remainingMins = mins % 60;
- if (hours > 0) {
- return `${hours}h ${remainingMins}m`;
- }
- return `${mins}m`;
- };
-
// Get top accomplishments (successful tasks with description snippets)
const accomplishments = succeeded
.map(a => ({
diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.js
index cb8428a848..97b3f4b596 100644
--- a/server/services/weeklyDigest.js
+++ b/server/services/weeklyDigest.js
@@ -11,7 +11,7 @@ import { existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { cosEvents, emitLog, getAgents } from './cos.js';
-import { readJSONFile } from '../lib/fileUtils.js';
+import { readJSONFile, formatDuration } from '../lib/fileUtils.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -82,26 +82,6 @@ async function saveDigest(digest) {
return path;
}
-/**
- * Format duration in human-readable format
- */
-function formatDuration(ms) {
- if (!ms) return '0m';
- const mins = Math.floor(ms / 60000);
- const hours = Math.floor(mins / 60);
- const days = Math.floor(hours / 24);
-
- if (days > 0) {
- const remainingHours = hours % 24;
- return `${days}d ${remainingHours}h`;
- }
- if (hours > 0) {
- const remainingMins = mins % 60;
- return `${hours}h ${remainingMins}m`;
- }
- return `${mins}m`;
-}
-
/**
* Calculate percentage change between two values
*/