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: code-quality sweep — asyncHandler in history routes, factory clients, named constants, a11y labels
[._.]/ Adam Eivyea3f3ecece92
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex 7f21ccf800..1fe91a586c 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -217,7 +217,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fadescription: newTask.description}).catch(err => {toast('Enhancement failed, using original description', { icon: '\u26a0\ufe0f' });- console.warn('Task enhancement failed:', err.message);+ console.warn(`⚠️ Task enhancement failed: ${err.message}`);return null;});diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsxindex ad2783475b..b30e6f6f0c 100644--- a/client/src/components/settings/BackupTab.jsx+++ b/client/src/components/settings/BackupTab.jsx@@ -7,6 +7,7 @@ import FolderPicker from '../FolderPicker';import useAsyncAction from '../../hooks/useAsyncAction';import Modal from '../ui/Modal';import { getSettings, updateSettings, getBackupStatus, triggerBackup, getBackupSnapshots, restoreDatabase } from '../../services/api';+import { formatBytes } from '../../utils/formatters';// Set equality — rsync --exclude flags are order-independent, so reordering// is NOT a dirty state; only membership changes (added/removed entries) are.@@ -132,7 +133,7 @@ export function BackupTab() {} else {toast.success(`Backup complete — ${filesChanged} files changed`, { icon: '💾' });}- getBackupSnapshots({ silent: true }).then(s => setSnapshots(Array.isArray(s) ? s : [])).catch(() => {});+ getBackupSnapshots({ silent: true }).then(s => setSnapshots(Array.isArray(s) ? s : [])).catch((err) => { console.warn(`⚠️ Failed to refresh snapshots: ${err?.message || err}`); });}return result;}, { errorMessage: 'Backup failed' });@@ -175,7 +176,7 @@ export function BackupTab() {const renderPgStatus = () => {if (!pgBackup) return <span className="text-gray-500">No backup run yet</span>;if (pgBackup.status === 'ok') {- return <span className="text-port-success">✅ {Math.round((pgBackup.sizeBytes || 0) / 1024)} KB · {pgBackup.tableCount} tables</span>;+ return <span className="text-port-success">✅ {formatBytes(pgBackup.sizeBytes || 0)} · {pgBackup.tableCount} tables</span>;}if (pgBackup.status === 'skipped') {return <span className="text-gray-400">⏭️ Not configured (file mode)</span>;@@ -228,7 +229,7 @@ export function BackupTab() {)}<div className="space-y-1">- <label className="block text-sm text-gray-400">Database Backup (last run)</label>+ <p className="block text-sm text-gray-400">Database Backup (last run)</p><div className="text-sm">{renderPgStatus()}</div></div>@@ -248,9 +249,11 @@ export function BackupTab() {</div><div className="flex items-center gap-3">- <label className="text-sm text-gray-400">Enabled</label>+ <span className="text-sm text-gray-400">Enabled</span><buttononClick={() => setEnabled(!enabled)}+ aria-label={enabled ? 'Disable scheduled backups' : 'Enable scheduled backups'}+ aria-pressed={enabled}className={`relative w-10 h-5 rounded-full transition-colors ${enabled ? 'bg-port-accent' : 'bg-port-border'}`}><span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${enabled ? 'translate-x-5' : ''}`} />@@ -274,7 +277,7 @@ export function BackupTab() {<div className="space-y-2"><div className="flex items-center gap-2"><ShieldOff size={14} className="text-gray-500" />- <label className="block text-sm text-gray-400">Default Exclusions</label>+ <span className="block text-sm text-gray-400">Default Exclusions</span></div><p className="text-xs text-gray-500">Built-in paths skipped by default to keep snapshots small. Overridable entries (large re-downloadable assets) can be re-enabled below; fixed entries hold ephemeral data and stay off.</p><ul className="space-y-1.5 mt-1">@@ -354,7 +357,7 @@ export function BackupTab() {{snapshots.length > 0 && (<div className="space-y-2">- <label className="block text-sm text-gray-400">Snapshots</label>+ <p className="block text-sm text-gray-400">Snapshots</p><ul className="space-y-1.5">{snapshots.slice(0, 10).map((snap) => (<li key={snap.id} className="flex items-center justify-between gap-2 text-xs bg-port-bg border border-port-border rounded-lg px-2.5 py-1.5">@@ -382,7 +385,7 @@ export function BackupTab() {<h3 className="text-white text-sm font-medium">Restore database?</h3><p className="text-sm text-gray-400">This replays <code>portos-db.sql</code> from snapshot <code className="text-gray-300">{restoreTarget}</code>- {restorePreview && <> ({Math.round((restorePreview.sizeBytes || 0) / 1024)} KB · {restorePreview.tableCount} tables)</>}+ {restorePreview && <> ({formatBytes(restorePreview.sizeBytes || 0)} · {restorePreview.tableCount} tables)</>}{' '}into the live PostgreSQL database. Existing rows may be overwritten.</p><div className="flex justify-end gap-2">diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 4fdec04d44..8bf4d4cc0e 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -22,6 +22,7 @@ import {} from '../../services/api';import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';import { resolveCleanersFromConfig } from '../../lib/imageCleaners';+import { safeParseJSON } from '../../lib/genUtils';const SDAPI_TOOL_ID = 'sdapi';const CODEX_TOOL_ID = 'codex-imagegen';@@ -109,7 +110,7 @@ export function ImageGenTab() {useEffect(() => {getHfTokenStatus().then((s) => { if (s) setHfTokenInfo({ hfTokenPresent: !!s.hfTokenPresent, source: s.source || null }); })- .catch(() => {});+ .catch((err) => { console.warn(`⚠️ Failed to load HF token status: ${err?.message || err}`); });}, []);const handleSaveHfToken = async () => {@@ -330,7 +331,7 @@ export function ImageGenTab() {renderEsRef.current = es;const closeEs = () => { es.close(); renderEsRef.current = null; };es.onmessage = (e) => {- const msg = (() => { try { return JSON.parse(e.data); } catch { return null; } })();+ const msg = safeParseJSON(e.data);if (!msg) return;if (msg.type === 'complete') {closeEs();diff --git a/client/src/components/settings/MortalLoomTab.jsx b/client/src/components/settings/MortalLoomTab.jsxindex f8bb2ecf82..136a75f368 100644--- a/client/src/components/settings/MortalLoomTab.jsx+++ b/client/src/components/settings/MortalLoomTab.jsx@@ -74,7 +74,8 @@ export function MortalLoomTab() {toast.success(`Imported ${totalAdded} new records (${totalSkipped} already present)`);const now = new Date().toISOString();setLastImport(now);- await updateSettings({ mortalloom: { enabled, path: path.trim(), lastImportAt: now } }).catch(() => {});+ await updateSettings({ mortalloom: { enabled, path: path.trim(), lastImportAt: now } })+ .catch((err) => { console.warn(`⚠️ Failed to persist import timestamp: ${err?.message || err}`); });await refreshStatus();};diff --git a/client/src/components/settings/TelegramTab.jsx b/client/src/components/settings/TelegramTab.jsxindex 1f0016fd8a..f18aff2737 100644--- a/client/src/components/settings/TelegramTab.jsx+++ b/client/src/components/settings/TelegramTab.jsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useId } from 'react';import { Save, Eye, EyeOff, Trash2, Send } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';@@ -18,6 +18,8 @@ const NOTIFICATION_TYPES = [];export function TelegramTab() {+ const botTokenId = useId();+ const chatIdId = useId();const [loading, setLoading] = useState(true);const [method, setMethod] = useState('manual');const [switching, setSwitching] = useState(false);@@ -124,7 +126,7 @@ export function TelegramTab() {<div className="space-y-4">{/* Method Selector */}<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">- <label className="block text-sm text-gray-400">Integration Method</label>+ <p className="block text-sm text-gray-400">Integration Method</p><div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><buttononClick={() => method !== 'manual' && handleMethodChange('manual')}@@ -179,9 +181,10 @@ export function TelegramTab() {)}<div className="space-y-1">- <label className="block text-sm text-gray-400">Bot Token</label>+ <label htmlFor={botTokenId} className="block text-sm text-gray-400">Bot Token</label><div className="flex gap-2"><input+ id={botTokenId}type={tgShowToken ? 'text' : 'password'}value={tgToken}onChange={e => setTgToken(e.target.value)}@@ -199,8 +202,9 @@ export function TelegramTab() {</div><div className="space-y-1">- <label className="block text-sm text-gray-400">Chat ID</label>+ <label htmlFor={chatIdId} className="block text-sm text-gray-400">Chat ID</label><input+ id={chatIdId}type="text"value={tgChatId}onChange={e => setTgChatId(e.target.value)}@@ -300,7 +304,7 @@ export function TelegramTab() {{/* Forward types (shared between both methods) */}{tgStatus?.connected && (<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-2">- <label className="block text-sm text-gray-400">Forward Notification Types</label>+ <p className="block text-sm text-gray-400">Forward Notification Types</p><p className="text-xs text-gray-500">When all are unchecked, all types are forwarded</p><div className="grid grid-cols-2 sm:grid-cols-3 gap-2">{NOTIFICATION_TYPES.map(({ key, label }) => (diff --git a/client/src/components/universe/CharacterReferenceSheetPanel.jsx b/client/src/components/universe/CharacterReferenceSheetPanel.jsxindex 6c0921779e..d0ac3ff183 100644--- a/client/src/components/universe/CharacterReferenceSheetPanel.jsx+++ b/client/src/components/universe/CharacterReferenceSheetPanel.jsx@@ -242,7 +242,7 @@ function getVariantCatalog() {return _variantCache;}).catch((err) => {- console.error('Failed to load reference-sheet variant catalog', err);+ console.error(`❌ Failed to load reference-sheet variant catalog: ${err?.message || err}`);// Fallback to the legacy standard-only catalog so the panel still// works against an older server that hasn't shipped the registry yet._variantCache = [{ id: LEGACY_SHEET_VARIANT_ID, label: 'Reference sheet', description: '' }];diff --git a/server/integrations/moltbook/README.md b/server/integrations/moltbook/README.mdindex f363c90608..c7160d18bb 100644--- a/server/integrations/moltbook/README.md+++ b/server/integrations/moltbook/README.md@@ -6,20 +6,20 @@ This directory contains a self-contained integration for Moltbook, an AI agent s- `api.js` - REST API client with all Moltbook actions- `rateLimits.js` - Rate limit tracking and enforcement-- `index.js` - Main export with MoltbookClient class+- `index.js` - Main export with the createMoltbookClient factory## Usage### In PortOS```javascript-import { MoltbookClient, register } from './integrations/moltbook/index.js';+import { createMoltbookClient, register } from './integrations/moltbook/index.js';// Register a new agentconst { api_key, claim_url } = await register('MyAgent', 'An AI agent');// Create a client for an existing agent-const client = new MoltbookClient(apiKey);+const client = createMoltbookClient(apiKey);// Check statusconst status = await client.getStatus();@@ -106,13 +106,13 @@ The integration only requires:The Moltbook integration is used by the automation scheduler to execute scheduled actions:```javascript-import { MoltbookClient } from './integrations/moltbook/index.js';+import { createMoltbookClient } from './integrations/moltbook/index.js';import { scheduleEvents } from './services/automationScheduler.js';// Listen for scheduled action executionsscheduleEvents.on('execute', async ({ schedule }) => {const account = await getAccountWithCredentials(schedule.accountId);- const client = new MoltbookClient(account.credentials.apiKey);+ const client = createMoltbookClient(account.credentials.apiKey);switch (schedule.action.type) {case 'post':diff --git a/server/integrations/moltbook/index.js b/server/integrations/moltbook/index.jsindex 5be0c9d423..ecb45844fa 100644--- a/server/integrations/moltbook/index.js+++ b/server/integrations/moltbook/index.js@@ -24,56 +24,53 @@ import * as api from './api.js';import { getRateLimitStatus } from './rateLimits.js';/**- * Moltbook client for a specific agent account+ * Create a Moltbook client for a specific agent account*/-export class MoltbookClient {- constructor(apiKey) {- this.apiKey = apiKey;- this.aiConfig = null;- }-- // Account- getStatus() { return api.getStatus(this.apiKey); }- getProfile() { return api.getProfile(this.apiKey); }- updateProfile(updates) { return api.updateProfile(this.apiKey, updates); }-- // Posts- createPost(submolt, title, content) { return api.createPost(this.apiKey, submolt, title, content, this.aiConfig); }- getFeed(sort, limit) { return api.getFeed(this.apiKey, sort, limit); }- getPost(postId) { return api.getPost(this.apiKey, postId); }- getPostsByAuthor(username) { return api.getPostsByAuthor(this.apiKey, username); }- deletePost(postId) { return api.deletePost(this.apiKey, postId); }-- // Comments- createComment(postId, content) { return api.createComment(this.apiKey, postId, content, this.aiConfig); }- replyToComment(postId, parentId, content) { return api.replyToComment(this.apiKey, postId, parentId, content, this.aiConfig); }- getComments(postId) { return api.getComments(this.apiKey, postId); }-- // Voting- upvote(postId) { return api.upvote(this.apiKey, postId); }- downvote(postId) { return api.downvote(this.apiKey, postId); }- upvoteComment(commentId) { return api.upvoteComment(this.apiKey, commentId); }-- // Social- follow(agentName) { return api.follow(this.apiKey, agentName); }- unfollow(agentName) { return api.unfollow(this.apiKey, agentName); }- getAgentProfile(agentName) { return api.getAgentProfile(this.apiKey, agentName); }- getFollowers() { return api.getFollowers(this.apiKey); }- getFollowing() { return api.getFollowing(this.apiKey); }-- // Heartbeat- heartbeat(options) { return api.heartbeat(this.apiKey, options); }-- // Submolts- getSubmolts() { return api.getSubmolts(this.apiKey); }- getSubmolt(name) { return api.getSubmolt(this.apiKey, name); }-- // Rate limits- getRateLimitStatus() { return getRateLimitStatus(this.apiKey); }+export function createMoltbookClient(apiKey) {+ let aiConfig = null;+ const client = {+ apiKey,+ get aiConfig() { return aiConfig; },+ set aiConfig(v) { aiConfig = v; },+ // Account+ getStatus: () => api.getStatus(apiKey),+ getProfile: () => api.getProfile(apiKey),+ updateProfile: (updates) => api.updateProfile(apiKey, updates),+ // Posts+ createPost: (submolt, title, content) => api.createPost(apiKey, submolt, title, content, aiConfig),+ getFeed: (sort, limit) => api.getFeed(apiKey, sort, limit),+ getPost: (postId) => api.getPost(apiKey, postId),+ getPostsByAuthor: (username) => api.getPostsByAuthor(apiKey, username),+ deletePost: (postId) => api.deletePost(apiKey, postId),+ // Comments+ createComment: (postId, content) => api.createComment(apiKey, postId, content, aiConfig),+ replyToComment: (postId, parentId, content) => api.replyToComment(apiKey, postId, parentId, content, aiConfig),+ getComments: (postId) => api.getComments(apiKey, postId),+ // Voting+ upvote: (postId) => api.upvote(apiKey, postId),+ downvote: (postId) => api.downvote(apiKey, postId),+ upvoteComment: (commentId) => api.upvoteComment(apiKey, commentId),+ // Social+ follow: (agentName) => api.follow(apiKey, agentName),+ unfollow: (agentName) => api.unfollow(apiKey, agentName),+ getAgentProfile: (agentName) => api.getAgentProfile(apiKey, agentName),+ getFollowers: () => api.getFollowers(apiKey),+ getFollowing: () => api.getFollowing(apiKey),+ // Heartbeat+ heartbeat: (options) => api.heartbeat(apiKey, options),+ // Submolts+ getSubmolts: () => api.getSubmolts(apiKey),+ getSubmolt: (name) => api.getSubmolt(apiKey, name),+ // Rate limits+ getRateLimitStatus: () => getRateLimitStatus(apiKey),+ };+ return client;}+/** @deprecated Use createMoltbookClient() */+export const MoltbookClient = createMoltbookClient;+/**- * Register a new agent on Moltbook- * This is a static method since it doesn't require an existing API key+ * Register a new agent on Moltbook (doesn't require an existing API key)*/-MoltbookClient.register = api.register;+export const registerMoltbookAgent = api.register;diff --git a/server/integrations/moltworld/README.md b/server/integrations/moltworld/README.mdindex c8a869d659..2809e7b78e 100644--- a/server/integrations/moltworld/README.md+++ b/server/integrations/moltworld/README.md@@ -6,20 +6,20 @@ This directory contains a self-contained integration for Moltworld, a shared vox- `api.js` - REST API client with all Moltworld actions- `rateLimits.js` - Rate limit tracking and enforcement (per-action + global 60 req/min)-- `index.js` - Main export with MoltworldClient class+- `index.js` - Main export with the createMoltworldClient factory## Usage### In PortOS```javascript-import { MoltworldClient, register } from './integrations/moltworld/index.js';+import { createMoltworldClient, register } from './integrations/moltworld/index.js';// Register a new agentconst { agentId, apiKey } = await register('MyAgent', { color: '#3b82f6', emoji: '🤖' });// Create a client for an existing agent-const client = new MoltworldClient(apiKey, agentId);+const client = createMoltworldClient(apiKey, agentId);// Join/move in the world (also heartbeat)const world = await client.joinWorld({ name: 'MyAgent', x: 5, y: -3 });@@ -65,10 +65,10 @@ const { balance } = await client.getBalance();## Integration with PortOS Scheduler```javascript-import { MoltworldClient } from './integrations/moltworld/index.js';+import { createMoltworldClient } from './integrations/moltworld/index.js';// Heartbeat — call every 5-10s to keep agent visible-const client = new MoltworldClient(apiKey, agentId);+const client = createMoltworldClient(apiKey, agentId);await client.joinWorld({ name: 'MyAgent', x: 0, y: 0 });// Explore — move to coordinates and thinkdiff --git a/server/integrations/moltworld/index.js b/server/integrations/moltworld/index.jsindex b218598df2..6880d4b7cd 100644--- a/server/integrations/moltworld/index.js+++ b/server/integrations/moltworld/index.js@@ -25,32 +25,30 @@ import * as api from './api.js';import { getRateLimitStatus } from './rateLimits.js';/**- * Moltworld client for a specific agent account+ * Create a Moltworld client for a specific agent account*/-export class MoltworldClient {- constructor(apiKey, agentId) {- this.apiKey = apiKey;- this.agentId = agentId;- }-- // World actions- joinWorld(options) { return api.joinWorld(this.agentId, options); }- think(thought) { return api.think(this.agentId, thought); }- build(options) { return api.build(this.agentId, options); }-- // Profile- getProfile() { return api.getProfile(this.agentId); }- updateProfile(updates) { return api.updateProfile(this.agentId, updates); }-- // Balance- getBalance() { return api.getBalance(this.agentId); }-- // Rate limits- getRateLimitStatus() { return getRateLimitStatus(this.agentId); }+export function createMoltworldClient(apiKey, agentId) {+ return {+ apiKey,+ agentId,+ // World actions+ joinWorld: (options) => api.joinWorld(agentId, options),+ think: (thought) => api.think(agentId, thought),+ build: (options) => api.build(agentId, options),+ // Profile+ getProfile: () => api.getProfile(agentId),+ updateProfile: (updates) => api.updateProfile(agentId, updates),+ // Balance+ getBalance: () => api.getBalance(agentId),+ // Rate limits+ getRateLimitStatus: () => getRateLimitStatus(agentId),+ };}+/** @deprecated Use createMoltworldClient() */+export const MoltworldClient = createMoltworldClient;+/**- * Register a new agent on Moltworld- * This is a static method since it doesn't require an existing agent ID+ * Register a new agent on Moltworld (doesn't require an existing agent ID)*/-MoltworldClient.register = api.register;+export const registerMoltworldAgent = api.register;diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.jsindex 109cbd0d31..83ece0a5ec 100644--- a/server/routes/appleHealth.js+++ b/server/routes/appleHealth.js@@ -19,6 +19,10 @@ import {getLatestMetricValues} from '../services/appleHealthQuery.js';+// Polling interval and timeout for XML write-stream completion (ms)+const XML_WRITE_POLL_INTERVAL_MS = 50;+const XML_WRITE_TIMEOUT_MS = 5000;+const isZip = (file) =>file.mimetype === 'application/zip' ||file.mimetype === 'application/x-zip-compressed' ||@@ -140,8 +144,8 @@ router.post('/import/xml', uploadXml, asyncHandler(async (req, res) => {if (!foundXml) return settle(reject)(new ServerError('ZIP does not contain export.xml', { status: 400, code: 'BAD_REQUEST' }));// Wait briefly for XML write stream to finish if close fires firstif (xmlWriteFinished) return settle(resolve)();- const check = setInterval(() => { if (xmlWriteFinished) { clearInterval(check); settle(resolve)(); } }, 50);- setTimeout(() => { clearInterval(check); settle(resolve)(); }, 5000);+ const check = setInterval(() => { if (xmlWriteFinished) { clearInterval(check); settle(resolve)(); } }, XML_WRITE_POLL_INTERVAL_MS);+ setTimeout(() => { clearInterval(check); settle(resolve)(); }, XML_WRITE_TIMEOUT_MS);}).on('error', settle(reject));});diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 2299e431c2..c386c25c31 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -24,6 +24,9 @@ import { certPaths } from '../../lib/certPaths.js';const router = Router();+// Delay before restarting PortOS itself so the JSON response reaches the client+const SELF_RESTART_RESPONSE_DELAY_MS = 500;+/** Async equivalent of existsSync — returns true if the path is accessible */const pathExists = (p) => access(p).then(() => true).catch(() => false);@@ -651,7 +654,7 @@ router.post('/:id/restart', loadApp, asyncHandler(async (req, res) => {await pm2Service.restartApp(name, app.pm2Home).catch(err => console.error(`❌ Self-restart failed for ${name}: ${err.message}`));}- }, 500);+ }, SELF_RESTART_RESPONSE_DELAY_MS);return;}diff --git a/server/routes/history.js b/server/routes/history.jsindex 391d387d5c..8bd7967e1b 100644--- a/server/routes/history.js+++ b/server/routes/history.js@@ -5,7 +5,7 @@ import * as history from '../services/history.js';const router = Router();// GET /api/history - Get history entries-router.get('/', async (req, res, next) => {+router.get('/', asyncHandler(async (req, res) => {const options = {limit: parseInt(req.query.limit, 10) || 100,offset: parseInt(req.query.offset, 10) || 0,@@ -14,33 +14,30 @@ router.get('/', async (req, res, next) => {success: req.query.success !== undefined ? req.query.success === 'true' : undefined};- const result = await history.getHistory(options).catch(next);- if (result) res.json(result);-});+ res.json(await history.getHistory(options));+}));// GET /api/history/stats - Get history statistics-router.get('/stats', async (req, res, next) => {- const stats = await history.getHistoryStats().catch(next);- if (stats) res.json(stats);-});+router.get('/stats', asyncHandler(async (req, res) => {+ res.json(await history.getHistoryStats());+}));// GET /api/history/actions - Get unique action types-router.get('/actions', async (req, res, next) => {- const actions = await history.getActionTypes().catch(next);- if (actions) res.json(actions);-});+router.get('/actions', asyncHandler(async (req, res) => {+ res.json(await history.getActionTypes());+}));// DELETE /api/history/:id - Delete single entry-router.delete('/:id', async (req, res, next) => {- const result = await history.deleteEntry(req.params.id).catch(next);- if (result) res.json(result);-});+router.delete('/:id', asyncHandler(async (req, res) => {+ const result = await history.deleteEntry(req.params.id);+ if (!result) throw new ServerError('Entry not found', { status: 404, code: 'NOT_FOUND' });+ res.json(result);+}));// DELETE /api/history - Clear history-router.delete('/', async (req, res, next) => {+router.delete('/', asyncHandler(async (req, res) => {const olderThanDays = req.query.olderThanDays ? parseInt(req.query.olderThanDays, 10) : null;- const result = await history.clearHistory(olderThanDays).catch(next);- if (result) res.json(result);-});+ res.json(await history.clearHistory(olderThanDays));+}));export default router;diff --git a/server/routes/history.test.js b/server/routes/history.test.jsindex 0e9de687a5..051ca4aacc 100644--- a/server/routes/history.test.js+++ b/server/routes/history.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';import historyRoutes from './history.js';// Mock the history service@@ -15,13 +16,19 @@ vi.mock('../services/history.js', () => ({// Import mocked modulesimport * as history from '../services/history.js';+const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/history', historyRoutes);+ app.use(errorMiddleware);+ return app;+};+describe('History Routes', () => {let app;beforeEach(() => {- app = express();- app.use(express.json());- app.use('/api/history', historyRoutes);+ app = buildApp();// Reset all mocksvi.clearAllMocks();@@ -97,6 +104,14 @@ describe('History Routes', () => {offset: 0}));});++ it('should propagate service errors as 500', async () => {+ history.getHistory.mockRejectedValue(new Error('DB unavailable'));++ const response = await request(app).get('/api/history');++ expect(response.status).toBe(500);+ });});describe('GET /api/history/stats', () => {@@ -121,7 +136,7 @@ describe('History Routes', () => {expect(response.status).toBe(200);expect(response.body.totalEntries).toBe(150);expect(response.body.successRate).toBe(0.95);- expect(response.body.byAction).toBeDefined();+ expect(response.body.byAction).toMatchObject({ start: 50, stop: 40, restart: 60 });});});@@ -160,13 +175,22 @@ describe('History Routes', () => {});it('should handle deletion of non-existent entry', async () => {- history.deleteEntry.mockResolvedValue({ success: false, error: 'Entry not found' });+ history.deleteEntry.mockResolvedValue(null);const response = await request(app).delete('/api/history/h-nonexistent');- expect(response.status).toBe(200);+ expect(response.status).toBe(404);+ expect(response.body.error).toMatch(/not found/i);expect(history.deleteEntry).toHaveBeenCalledWith('h-nonexistent');});++ it('should propagate service errors as 500', async () => {+ history.deleteEntry.mockRejectedValue(new Error('DB connection lost'));++ const response = await request(app).delete('/api/history/h-err');++ expect(response.status).toBe(500);+ });});describe('DELETE /api/history', () => {diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 4078640b35..b3ffe0ec93 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -15,6 +15,11 @@ import { getToken, getTokenStatus, testApi, clearTokenCache } from '../services/const router = express.Router();+// Maximum number of messages fetched for a full-body refresh pass.+// When the result set hits this cap the response includes truncated:true so+// callers know there may be un-refreshed messages beyond the limit.+const FULL_BODY_REFRESH_LIMIT = 1000;+// === Validation Schemas ===const createAccountSchema = z.object({name: z.string().min(1),@@ -395,7 +400,8 @@ router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {if (account.type !== 'outlook') return res.json({ updated: 0, total: 0 });const force = req.body?.force === true;- const allResult = await messageSync.getMessages({ accountId, limit: 1000 });+ const allResult = await messageSync.getMessages({ accountId, limit: FULL_BODY_REFRESH_LIMIT });+ const truncated = allResult.messages.length >= FULL_BODY_REFRESH_LIMIT;const toRefresh = force ? allResult.messages : allResult.messages.filter(m => m.bodyFull === false);let updated = 0;@@ -405,7 +411,7 @@ router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {}if (updated > 0) req.app.get('io')?.emit('messages:changed', {});- res.json({ updated, total: toRefresh.length });+ res.json({ updated, total: toRefresh.length, truncated });}));// === Clear account cache ===