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

fix: guard voice socket handlers, time out deploys, client effect/button hygiene

[._.]/ Adam Eivy32ce4648b841
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index cf788401fd..9eb4fa0e5f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
- **Helper consolidation** — filename sanitization and MIME maps unified in fileUtils (was 3 copies); GSD/app document saves use atomic writes; client components use the canonical formatters and shared command API instead of local re-implementations.
- **Service extractions** — universe-builder render orchestration, brain bucket cascade/ordering, system folder-open, and reciprocal-rank-fusion moved out of routes into services/lib; the canonPrompt client/server mirror is now enforced by a parity test.
- **Loop fallback crash + durability** — provider fallback no longer crashes loop iterations; loops.json writes are atomic and serialized; cos-runner state races, leaked kill timers, and unguarded close handlers fixed; N+1 issue scans eliminated with an uncapped accessor so >1000-issue installs don't miscount; HF repo-size and Telegram check-in caches bounded.
+- **Crash-proofing + UI hygiene** — voice socket handlers can't take down the server on settings-read failures; hung deploy scripts time out instead of wedging the deploy lock; buttons get explicit types, list keys stabilized, theme/notification fetches gain abort/unmount guards.
- **A watched TUI run no longer false-times-out after finishing its work** — companion fix to *Live TUI runs are now viewable AND drivable in the Shell page* (above). One-shot AI runs that drive a terminal UI (Claude Code, Codex, etc.) write their completed answer to a response file and then return to an interactive prompt **without exiting**. The runner only auto-completed such a run via output-idle — which is paused while you watch it in the Shell page (so it isn't snapped shut mid-read). With the process never exiting and idle paused, a watched run had no terminus but the 10-minute hard timeout — at which point it was marked **failed**, its already-written result was **discarded**, and a useless fallback retry ran in its place. The runner now watches for the response file as the model's authoritative "done" signal and completes the run the moment it's written — even while you're watching — since once the file exists the task is genuinely finished. A second safety net salvages the file on hard timeout: if the result was written but completion stalled for any other reason, the run finishes as **success** with that result instead of throwing it away and falling back. So a long editorial pass you keep open in the Shell tab now lands its findings when the model finishes, instead of silently dying at 10 minutes. (`server/lib/tuiPromptRunner.js`)
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 6460605efc..ad1895a574 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -896,6 +896,7 @@ export default function Layout() {
{/* Collapsed: just logo, clickable to expand */}
{collapsed && (
<button
+ type="button"
onClick={() => setCollapsed(false)}
className="hidden lg:block opacity-95 transition-opacity hover:opacity-80"
title="Expand sidebar"
@@ -907,6 +908,7 @@ export default function Layout() {
{/* Expanded: collapse button */}
{!collapsed && (
<button
+ type="button"
onClick={() => setCollapsed(true)}
className="hidden lg:flex p-1 text-gray-500 hover:text-white transition-colors"
title="Collapse sidebar"
@@ -917,6 +919,7 @@ export default function Layout() {
)}
{/* Mobile close button */}
<button
+ type="button"
onClick={() => setMobileOpen(false)}
className="lg:hidden inline-flex items-center justify-center min-w-[40px] min-h-[40px] rounded-lg text-gray-500 hover:text-white"
aria-label="Close sidebar"
diff --git a/client/src/components/NotificationDropdown.jsx b/client/src/components/NotificationDropdown.jsx
index c4004208f6..7a47e3d5c0 100644
--- a/client/src/components/NotificationDropdown.jsx
+++ b/client/src/components/NotificationDropdown.jsx
@@ -114,6 +114,7 @@ export default function NotificationDropdown({
<div className="flex items-center gap-2">
{unreadCount > 0 && (
<button
+ type="button"
onClick={onMarkAllAsRead}
className="p-1.5 rounded hover:bg-port-border transition-colors focus:outline-hidden focus:ring-2 focus:ring-port-accent"
title="Mark all as read"
@@ -124,6 +125,7 @@ export default function NotificationDropdown({
)}
{notifications.length > 0 && (
<button
+ type="button"
onClick={onClearAll}
className="p-1.5 rounded hover:bg-port-border transition-colors focus:outline-hidden focus:ring-2 focus:ring-port-accent"
title="Clear all"
@@ -170,6 +172,7 @@ export default function NotificationDropdown({
{notification.title}
</span>
<button
+ type="button"
onClick={(e) => {
e.stopPropagation();
onRemove(notification.id);
@@ -191,6 +194,7 @@ export default function NotificationDropdown({
</span>
{!notification.read && (
<button
+ type="button"
onClick={(e) => {
e.stopPropagation();
onMarkAsRead(notification.id);
diff --git a/client/src/components/digital-twin/ListEnrichment.jsx b/client/src/components/digital-twin/ListEnrichment.jsx
index f40e89a72f..92d7e71691 100644
--- a/client/src/components/digital-twin/ListEnrichment.jsx
+++ b/client/src/components/digital-twin/ListEnrichment.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import {ArrowLeft,
Plus,
X,
@@ -29,8 +29,14 @@ export default function ListEnrichment({
}) {
const config = ENRICHMENT_CATEGORIES[categoryId];
+ // Stable key counter — items from the server have no id field, so we stamp
+ // a client-side _key on each item when it is loaded or created. This avoids
+ // the key={index} footgun when items are removed mid-list.
+ const nextKey = useRef(0);
+ const mkItem = (title = '', note = '') => ({ title, note, _key: nextKey.current++ });
+
// List items state
- const [items, setItems] = useState([{ title: '', note: '' }]);
+ const [items, setItems] = useState(() => [mkItem()]);
const [loadingItems, setLoadingItems] = useState(true);
// Analysis state
@@ -51,19 +57,19 @@ export default function ListEnrichment({
setLoadingItems(true);
const existingItems = await api.getEnrichmentListItems(categoryId).catch(() => []);
if (existingItems && existingItems.length > 0) {
- setItems(existingItems);
+ setItems(existingItems.map(({ title, note }) => mkItem(title, note)));
} else {
- setItems([{ title: '', note: '' }]);
+ setItems([mkItem()]);
}
setLoadingItems(false);
- }, [categoryId]);
+ }, [categoryId]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
loadExistingItems();
}, [loadExistingItems]);
const addItem = () => {
- setItems([...items, { title: '', note: '' }]);
+ setItems([...items, mkItem()]);
};
const updateItem = (index, field, value) => {
@@ -78,7 +84,10 @@ export default function ListEnrichment({
}
};
- const getValidItems = () => items.filter(item => item.title.trim().length > 0);
+ // Strip the client-only _key before sending items to the API.
+ const getValidItems = () => items
+ .filter(item => item.title.trim().length > 0)
+ .map(({ title, note }) => ({ title, note }));
const analyzeList = async () => {
const validItems = getValidItems();
@@ -176,7 +185,7 @@ export default function ListEnrichment({
<div className="space-y-4">
{items.map((item, index) => (
<div
- key={index}
+ key={item._key}
className="bg-port-bg rounded-lg border border-port-border p-4 relative group"
>
{items.length > 1 && (
diff --git a/client/src/components/digital-twin/tabs/EnrichTab.jsx b/client/src/components/digital-twin/tabs/EnrichTab.jsx
index 7919dc7135..63ae4c5fa5 100644
--- a/client/src/components/digital-twin/tabs/EnrichTab.jsx
+++ b/client/src/components/digital-twin/tabs/EnrichTab.jsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useRef } from 'react';
import { useSearchParams } from 'react-router-dom';
import {Sparkles,
ChevronRight,
@@ -32,9 +32,14 @@ export default function EnrichTab({ onRefresh }) {
const [loadingQuestion, setLoadingQuestion] = useState(false);
const [skippedIndices, setSkippedIndices] = useState([]);
- // Writing sample analysis
+ // Writing sample analysis.
+ // Each entry is { value: string, _key: number } so we have a stable key
+ // for React when samples are removed mid-list (key={index} causes
+ // mis-association of textarea state on removal).
+ const writingSampleKey = useRef(0);
+ const mkSample = (value = '') => ({ value, _key: writingSampleKey.current++ });
const [showWritingAnalysis, setShowWritingAnalysis] = useState(false);
- const [writingSamples, setWritingSamples] = useState(['']);
+ const [writingSamples, setWritingSamples] = useState(() => [mkSample()]);
const [analyzingWriting, setAnalyzingWriting] = useState(false);
const [writingAnalysis, setWritingAnalysis] = useState(null);
const [providers, setProviders] = useState([]);
@@ -63,12 +68,12 @@ export default function EnrichTab({ onRefresh }) {
}, [loadData, loadProviders]);
const addWritingSample = () => {
- setWritingSamples([...writingSamples, '']);
+ setWritingSamples([...writingSamples, mkSample()]);
};
const updateWritingSample = (index, value) => {
const updated = [...writingSamples];
- updated[index] = value;
+ updated[index] = { ...updated[index], value };
setWritingSamples(updated);
};
@@ -79,7 +84,7 @@ export default function EnrichTab({ onRefresh }) {
};
const analyzeWriting = async () => {
- const validSamples = writingSamples.filter(s => s.trim().length >= 50);
+ const validSamples = writingSamples.map(s => s.value).filter(s => s.trim().length >= 50);
if (validSamples.length === 0) {
toast.error('Add at least one writing sample (50+ characters)');
return;
@@ -560,9 +565,9 @@ export default function EnrichTab({ onRefresh }) {
{/* Writing Samples */}
<div className="space-y-3">
{writingSamples.map((sample, index) => (
- <div key={index} className="relative">
+ <div key={sample._key} className="relative">
<textarea
- value={sample}
+ value={sample.value}
onChange={(e) => updateWritingSample(index, e.target.value)}
placeholder={`Paste writing sample ${index + 1} here (emails, messages, docs)...`}
rows={4}
@@ -570,6 +575,7 @@ export default function EnrichTab({ onRefresh }) {
/>
{writingSamples.length > 1 && (
<button
+ type="button"
onClick={() => removeWritingSample(index)}
className="absolute top-2 right-2 text-gray-500 hover:text-red-400"
>
@@ -577,7 +583,7 @@ export default function EnrichTab({ onRefresh }) {
</button>
)}
<div className="text-xs text-gray-500 mt-1">
- {sample.length} characters {sample.length < 50 && sample.length > 0 && '(need 50+)'}
+ {sample.value.length} characters {sample.value.length < 50 && sample.value.length > 0 && '(need 50+)'}
</div>
</div>
))}
diff --git a/client/src/hooks/useNotifications.js b/client/src/hooks/useNotifications.js
index 50cc142492..65aa120ea0 100644
--- a/client/src/hooks/useNotifications.js
+++ b/client/src/hooks/useNotifications.js
@@ -10,6 +10,7 @@ export function useNotifications() {
// Fetch initial notifications
useEffect(() => {
+ let cancelled = false;
const fetchNotifications = async () => {
setLoading(true);
try {
@@ -17,16 +18,19 @@ export function useNotifications() {
api.getNotifications({ limit: 50 }),
api.getNotificationCount()
]);
+ if (cancelled) return;
setNotifications(notifs);
setUnreadCount(countData.count);
} catch (err) {
+ if (cancelled) return;
console.error(`❌ Failed to load notifications: ${err.message}`);
} finally {
- setLoading(false);
+ if (!cancelled) setLoading(false);
}
};
fetchNotifications();
+ return () => { cancelled = true; };
}, []);
// Subscribe to socket events
diff --git a/client/src/hooks/useTheme.js b/client/src/hooks/useTheme.js
index 858aabc882..237a191bc4 100644
--- a/client/src/hooks/useTheme.js
+++ b/client/src/hooks/useTheme.js
@@ -55,7 +55,8 @@ export default function useTheme() {
const userPickedRef = useRef(false);
useEffect(() => {
- fetch('/api/settings')
+ const controller = new AbortController();
+ fetch('/api/settings', { signal: controller.signal })
.then(r => r.ok ? r.json() : null)
.then(settings => {
if (userPickedRef.current) return;
@@ -68,7 +69,11 @@ export default function useTheme() {
setThemeId(serverTheme);
}
})
- .catch(() => console.log('Theme fetch failed, using localStorage fallback'));
+ .catch((err) => {
+ if (err.name === 'AbortError') return;
+ console.warn(`⚠️ Theme fetch failed, using localStorage fallback: ${err.message}`);
+ });
+ return () => controller.abort();
}, []);
const setTheme = useCallback((id) => {
diff --git a/server/routes/logs.js b/server/routes/logs.js
index 643dae6c56..7848bbdbfc 100644
--- a/server/routes/logs.js
+++ b/server/routes/logs.js
@@ -92,8 +92,10 @@ router.get('/:processName', asyncHandler(async (req, res) => {
});
logProcess.on('close', (code) => {
- res.write(`event: close\ndata: ${JSON.stringify({ code })}\n\n`);
- res.end();
+ if (!res.writableEnded && !res.destroyed) {
+ res.write(`event: close\ndata: ${JSON.stringify({ code })}\n\n`);
+ res.end();
+ }
});
// Cleanup on client disconnect
diff --git a/server/services/appDeployer.js b/server/services/appDeployer.js
index 7b2d090aef..533e0aa713 100644
--- a/server/services/appDeployer.js
+++ b/server/services/appDeployer.js
@@ -6,6 +6,10 @@ import { NON_PM2_TYPES } from './streamingDetect.js';
export const DEPLOY_FLAGS = ['--ios', '--macos', '--watch', '--all', '--skip-tests'];
const VALID_FLAGS = new Set(DEPLOY_FLAGS);
const FLUSH_INTERVAL_MS = 80;
+// Maximum time (ms) a deploy.sh may run before the child is killed and the
+// lock released. Escalates from SIGTERM → SIGKILL after DEPLOY_KILL_DELAY_MS.
+const DEPLOY_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
+const DEPLOY_KILL_DELAY_MS = 10 * 1000; // 10 seconds after SIGTERM
// Per-app lock to prevent concurrent deploys
const deployingApps = new Set();
@@ -65,10 +69,27 @@ export function deployApp(app, flags, emit) {
env: { ...process.env, FORCE_COLOR: '0' }
});
+ // Guard against a hung deploy.sh holding the lock forever.
+ // After DEPLOY_TIMEOUT_MS: SIGTERM the child; escalate to SIGKILL after
+ // DEPLOY_KILL_DELAY_MS if it hasn't exited. The 'close' handler below
+ // handles lock release and result resolution for both normal and timed-out
+ // exits, so we only need to kill here.
+ let killTimer = null;
+ const deployTimer = setTimeout(() => {
+ console.error(`❌ Deploy timed out after ${DEPLOY_TIMEOUT_MS / 1000}s — killing child process`);
+ emit('error', { message: 'Deploy timed out' });
+ child.kill('SIGTERM');
+ killTimer = setTimeout(() => {
+ child.kill('SIGKILL');
+ }, DEPLOY_KILL_DELAY_MS);
+ }, DEPLOY_TIMEOUT_MS);
+
child.stdout.on('data', (data) => { stdoutBuf += data.toString(); });
child.stderr.on('data', (data) => { stderrBuf += data.toString(); });
child.on('close', (code) => {
+ clearTimeout(deployTimer);
+ clearTimeout(killTimer);
const success = code === 0;
const result = finish(success, code);
emit('status', {
@@ -81,6 +102,8 @@ export function deployApp(app, flags, emit) {
});
child.on('error', (err) => {
+ clearTimeout(deployTimer);
+ clearTimeout(killTimer);
const result = finish(false, -1);
emit('error', { message: err.message });
resolve(result);
diff --git a/server/services/pm2.js b/server/services/pm2.js
index aac599e491..39e2fb2444 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -33,15 +33,29 @@ function isJsScript(script) {
* Spawn PM2 CLI via local binary (node pm2/bin/pm2).
* Always uses the local PM2 binary to avoid depending on a global pm2 install.
* On Windows this also avoids pm2.cmd which creates visible CMD windows.
+ *
+ * A default 'error' listener is attached so that an ENOENT or EACCES error
+ * (e.g. missing Node binary) doesn't crash Node via the uncaught-EventEmitter
+ * exception path when no caller attaches its own 'error' listener.
+ * Callers that attach their own 'error' handler are unaffected — multiple
+ * listeners are fine and all receive the event.
+ *
* @param {string[]} pm2Args PM2 CLI arguments (e.g. ['jlist'], ['start', 'ecosystem.config.cjs'])
* @param {object} opts Spawn options (cwd, env, etc.)
* @returns {ChildProcess}
*/
export function spawnPm2(pm2Args, opts = {}) {
- return spawn(process.execPath, [PM2_BIN, ...pm2Args], {
+ const child = spawn(process.execPath, [PM2_BIN, ...pm2Args], {
...opts,
windowsHide: true
});
+ // Default error handler — prevents an uncaught EventEmitter 'error' crash
+ // when no caller attaches its own handler. Callers that do attach their own
+ // 'error' listener receive the event too (multiple listeners are additive).
+ child.on('error', (err) => {
+ console.error(`❌ spawnPm2 error [${pm2Args[0]}]: ${err.message}`);
+ });
+ return child;
}
/**
diff --git a/server/services/socket.js b/server/services/socket.js
index ecf338e00f..b1890572a8 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -76,10 +76,12 @@ export function getIo() {
const ALL_SUBSCRIBER_SETS = [cosSubscribers, errorSubscribers, notificationSubscribers, agentSubscribers, instanceSubscribers, loopSubscribers];
function broadcastToSet(set, event, data) {
+ const disconnected = [];
for (const s of set) {
- if (!s.connected) { set.delete(s); continue; }
+ if (!s.connected) { disconnected.push(s); continue; }
s.emit(event, data);
}
+ for (const s of disconnected) set.delete(s);
}
function registerSubscriber(socket, namespace, set) {
diff --git a/server/sockets/voice.js b/server/sockets/voice.js
index 037e2ecbc6..d01888ff79 100644
--- a/server/sockets/voice.js
+++ b/server/sockets/voice.js
@@ -141,51 +141,61 @@ export const registerVoiceHandlers = (socket) => {
};
socket.on('voice:turn', async (payload = {}) => {
- if (!(await ensureEnabled('turn'))) return;
- const { audio, mimeType: rawMime } = payload;
- if (!audio) {
- socket.emit('voice:error', { stage: 'turn', message: 'audio is required' });
- return;
- }
- const size = audioByteLength(audio);
- if (!size) {
- socket.emit('voice:error', { stage: 'turn', message: 'audio is empty or unrecognized' });
- return;
- }
- if (size > MAX_AUDIO_BYTES) {
- socket.emit('voice:error', { stage: 'turn', message: `audio too large (${size} > ${MAX_AUDIO_BYTES} bytes)` });
- return;
+ try {
+ if (!(await ensureEnabled('turn'))) return;
+ const { audio, mimeType: rawMime } = payload;
+ if (!audio) {
+ socket.emit('voice:error', { stage: 'turn', message: 'audio is required' });
+ return;
+ }
+ const size = audioByteLength(audio);
+ if (!size) {
+ socket.emit('voice:error', { stage: 'turn', message: 'audio is empty or unrecognized' });
+ return;
+ }
+ if (size > MAX_AUDIO_BYTES) {
+ socket.emit('voice:error', { stage: 'turn', message: `audio too large (${size} > ${MAX_AUDIO_BYTES} bytes)` });
+ return;
+ }
+ // Normalize mimeType — reject anything that isn't a plain string to keep
+ // downstream HTTP multipart stable.
+ const mimeType = typeof rawMime === 'string' && rawMime.length <= 64 ? rawMime : 'audio/wav';
+ // Preserve TypedArray byteOffset/byteLength so a sliced Uint8Array view
+ // doesn't drag unrelated bytes from its underlying ArrayBuffer.
+ let buffer;
+ if (Buffer.isBuffer(audio)) buffer = audio;
+ else if (audio instanceof ArrayBuffer) buffer = Buffer.from(audio);
+ else if (ArrayBuffer.isView(audio)) buffer = Buffer.from(audio.buffer, audio.byteOffset, audio.byteLength);
+ else buffer = Buffer.from(audio);
+ await runTurnWithState({ audio: buffer, mimeType, errorStage: 'turn' });
+ } catch (err) {
+ console.error(`❌ voice:turn failed: ${err.message}`);
+ socket.emit('voice:error', { stage: 'turn', message: err.message });
}
- // Normalize mimeType — reject anything that isn't a plain string to keep
- // downstream HTTP multipart stable.
- const mimeType = typeof rawMime === 'string' && rawMime.length <= 64 ? rawMime : 'audio/wav';
- // Preserve TypedArray byteOffset/byteLength so a sliced Uint8Array view
- // doesn't drag unrelated bytes from its underlying ArrayBuffer.
- let buffer;
- if (Buffer.isBuffer(audio)) buffer = audio;
- else if (audio instanceof ArrayBuffer) buffer = Buffer.from(audio);
- else if (ArrayBuffer.isView(audio)) buffer = Buffer.from(audio.buffer, audio.byteOffset, audio.byteLength);
- else buffer = Buffer.from(audio);
- await runTurnWithState({ audio: buffer, mimeType, errorStage: 'turn' });
});
socket.on('voice:text', async (payload = {}) => {
- if (!(await ensureEnabled('text'))) return;
- const raw = payload?.text;
- if (typeof raw !== 'string' && typeof raw !== 'number') {
- socket.emit('voice:error', { stage: 'text', message: 'text is required' });
- return;
- }
- const text = String(raw).trim();
- if (!text) {
- socket.emit('voice:error', { stage: 'text', message: 'text is required' });
- return;
- }
- if (text.length > MAX_TEXT_LEN) {
- socket.emit('voice:error', { stage: 'text', message: `text too long (${text.length} > ${MAX_TEXT_LEN} chars)` });
- return;
+ try {
+ if (!(await ensureEnabled('text'))) return;
+ const raw = payload?.text;
+ if (typeof raw !== 'string' && typeof raw !== 'number') {
+ socket.emit('voice:error', { stage: 'text', message: 'text is required' });
+ return;
+ }
+ const text = String(raw).trim();
+ if (!text) {
+ socket.emit('voice:error', { stage: 'text', message: 'text is required' });
+ return;
+ }
+ if (text.length > MAX_TEXT_LEN) {
+ socket.emit('voice:error', { stage: 'text', message: `text too long (${text.length} > ${MAX_TEXT_LEN} chars)` });
+ return;
+ }
+ await runTurnWithState({ text, source: payload?.source, errorStage: 'text' });
+ } catch (err) {
+ console.error(`❌ voice:text failed: ${err.message}`);
+ socket.emit('voice:error', { stage: 'text', message: err.message });
}
- await runTurnWithState({ text, source: payload?.source, errorStage: 'text' });
});
socket.on('voice:interrupt', () => {