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: harden background service and mobile lifecycles

[._.]/ Adam Eivyf192ba70b2d7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d770e3ad3f..80ba12554e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -45,6 +45,8 @@
## Fixed
+- **A DevSecOps hardening pass makes background services fail safely and persistent controls touch-accessible.** Autofixer process/history data now renders through safe DOM text nodes and its periodic scan cannot overlap itself; CLI runner terminal events finalize exactly once; port discovery fails closed with deterministic cross-platform parsing; backup `rsync` lookup is portable; task-watcher events, Spotify requests, and shared media streams now have bounded/owned lifecycles; repeated CyberCity district-bound calculations use one empty-safe helper; and persistent mobile navigation plus timeline removal controls provide 44×44 touch targets with accessible labels. Focused regression coverage accompanies each repaired path.
+
- **CoS agents (notably codex) now open their PR as the gh account that matches the repo owner, not gh's mutable active user.** PortOS's own `createPR` pins `GH_TOKEN` to the logged-in gh account whose login matches the repo owner (avoiding the multi-account "must be a collaborator" failure), but a spawned agent running its *own* `gh pr create` — a codex/Claude/CLI CoS agent finishing `/do:pr` — never received that pinning. TUI agents fared worst: `shell.js`'s `buildSafeEnv` strips `GH_TOKEN` from the inherited env entirely, so their `gh` fell back to whatever `hosts.yml` active user happened to be set. A new best-effort `resolveForgeTokenEnv(dir)` (in `server/services/git.js`) resolves just the owner-matched `GH_TOKEN` overlay and is injected into all three agent-spawn env paths — direct CLI (`spawnDirectly`), TUI shell session (`spawnTuiAgent`), and the CoS runner (`spawnViaRunner`). It's provider-agnostic (no codex special-case), returns `{}` when no owner-matched account exists (so single-account installs and GitLab repos are untouched), and is spread before `provider.envVars` so an explicit provider `GH_TOKEN` override still wins.
- **Read-only CoS agents (e.g. reference-watch) on a TUI provider now signal completion via the `.agent-done` sentinel.** The prompt builder's completion decision tree gave every other task shape (reasoning-only, TUI push+PR, CLI) an explicit sentinel instruction, but the `isReadOnly` branch emitted only the bare "Read-Only Task" notice with no sentinel — so a read-only TUI run (reference-watch records its proposals directly in the tracker, then just needs to signal done) never wrote `.agent-done`. The 2s sentinel poll in `spawnTuiAgent` — the primary finalize path and the channel that ingests the run summary — therefore never fired, and the run only completed via the idle-reaper / shell-exit fallback with no clean resolution summary captured. `agentPromptBuilder.js` now routes the read-only branch through a new `buildReadOnlyCompletionSection({ isTui, sentinelPath })` that keeps the do-not-modify guidance and, for TUI agents, appends the write-`.agent-done`-then-stop instruction. CLI/API read-only agents complete on process exit and never poll a sentinel, so they still get the bare notice.
diff --git a/autofixer/server.js b/autofixer/server.js
index bbc777b804..150ac46a96 100644
--- a/autofixer/server.js
+++ b/autofixer/server.js
@@ -52,6 +52,8 @@ const INDEX_FILE = join(AUTOFIXER_DIR, 'index.json');
const recentlyFixed = new Map();
const FIX_COOLDOWN = 30 * 60 * 1000; // 30 minutes
const CHECK_INTERVAL = 15 * 60 * 1000; // 15 minutes
+let checkTimer = null;
+let shuttingDown = false;
// Load apps from PortOS
async function loadApps() {
@@ -359,6 +361,28 @@ async function checkAndFixProcesses() {
}
}
+function scheduleNextCheck() {
+ if (shuttingDown) return;
+
+ checkTimer = setTimeout(() => {
+ checkTimer = null;
+ void runCheckCycle();
+ }, CHECK_INTERVAL);
+}
+
+// Schedule from completion rather than wall-clock time so a long-running fix
+// cannot overlap the next process scan. Errors are contained here because this
+// loop runs outside a request lifecycle and must keep retrying autonomously.
+async function runCheckCycle() {
+ try {
+ await checkAndFixProcesses();
+ } catch (error) {
+ console.error(`❌ [Autofixer] Process check failed: ${error?.message || String(error)}`);
+ } finally {
+ scheduleNextCheck();
+ }
+}
+
// Main loop
async function main() {
console.log(`🚀 [Autofixer] Starting PortOS Autofixer daemon`);
@@ -367,25 +391,24 @@ async function main() {
await ensureHistoryDir();
- // Initial check
- await checkAndFixProcesses();
-
- // Periodic check
- setInterval(async () => {
- await checkAndFixProcesses();
- }, CHECK_INTERVAL);
+ // Run immediately, then wait a full interval after each pass completes.
+ await runCheckCycle();
}
// Graceful shutdown
-process.on('SIGINT', () => {
- console.log(`\n🛑 [Autofixer] Shutting down...`);
- process.exit(0);
-});
+function shutdown() {
+ shuttingDown = true;
+ if (checkTimer) {
+ clearTimeout(checkTimer);
+ checkTimer = null;
+ }
-process.on('SIGTERM', () => {
console.log(`\n🛑 [Autofixer] Shutting down...`);
process.exit(0);
-});
+}
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
// Start
main().catch(error => {
diff --git a/autofixer/ui.template.html b/autofixer/ui.template.html
index 3b1dd1198b..f8ac4cb73c 100644
--- a/autofixer/ui.template.html
+++ b/autofixer/ui.template.html
@@ -495,14 +495,19 @@
let totalLines = 0;
let autoScroll = true;
let selectedProcess = null;
- let processStatuses = {};
+ let processStatuses = new Map();
+ const processStatusClasses = new Map([
+ ['online', 'status-online'],
+ ['stopped', 'status-stopped'],
+ ['errored', 'status-errored']
+ ]);
// Fetch PM2 status
async function fetchStatus() {
const res = await fetch('/api/status');
const statuses = await res.json();
- processStatuses = {};
- statuses.forEach(s => { processStatuses[s.name] = s.status; });
+ processStatuses = new Map();
+ statuses.forEach(s => { processStatuses.set(String(s.name ?? ''), s.status); });
updateProcessList();
}
@@ -524,33 +529,39 @@
function updateProcessList() {
const processes = window.processesList || [];
- processList.innerHTML = processes.map(p => {
- const status = processStatuses[p.name] || 'unknown';
- const selected = selectedProcess === p.name ? 'selected' : '';
- return `
- <div class="process-item ${selected}" data-name="${p.name}">
- <div class="process-name">
- <span class="process-status status-${status}"></span>
- ${p.name}
- </div>
- <div class="process-app">${p.app}</div>
- </div>
- `;
- }).join('');
-
- // Reattach click handlers
- document.querySelectorAll('.process-item').forEach(item => {
+ processList.replaceChildren();
+
+ processes.forEach(p => {
+ const name = String(p.name ?? '');
+ const item = document.createElement('div');
+ item.classList.add('process-item');
+ if (selectedProcess === name) item.classList.add('selected');
+ item.dataset.name = name;
+
+ const nameEl = document.createElement('div');
+ nameEl.className = 'process-name';
+
+ const statusEl = document.createElement('span');
+ const statusClass = processStatusClasses.get(processStatuses.get(name)) || 'status-unknown';
+ statusEl.classList.add('process-status', statusClass);
+ nameEl.append(statusEl, document.createTextNode(name));
+
+ const appEl = document.createElement('div');
+ appEl.className = 'process-app';
+ appEl.textContent = String(p.app ?? '');
+
+ item.append(nameEl, appEl);
item.addEventListener('click', () => {
- const name = item.dataset.name;
- selectProcess(name);
+ selectProcess(item.dataset.name);
});
+ processList.appendChild(item);
});
}
function selectProcess(name) {
selectedProcess = name;
currentProcessEl.textContent = name;
- logsContainer.innerHTML = '';
+ logsContainer.replaceChildren();
totalLines = 0;
lineCount.textContent = '0 lines';
restartBtn.disabled = false;
@@ -647,24 +658,44 @@
async function fetchHistory() {
const res = await fetch('/api/history');
const history = await res.json();
+ historyPanel.replaceChildren();
+
+ if (!Array.isArray(history) || history.length === 0) {
+ const empty = document.createElement('div');
+ empty.style.padding = '1rem';
+ empty.style.color = '#666';
+ empty.textContent = 'No fix history yet';
+ historyPanel.appendChild(empty);
+ return;
+ }
- historyPanel.innerHTML = history.map(h => {
+ history.forEach(h => {
const date = new Date(h.startTime).toLocaleString();
const duration = Math.round(h.duration / 1000);
- return `
- <div class="history-item">
- <div class="time">${date} (${duration}s)</div>
- <div class="process">${h.processName} - ${h.appName || 'Unknown App'}</div>
- <div class="result ${h.success ? 'success' : 'failed'}">
- ${h.success ? 'Fixed successfully' : 'Fix failed'}
- </div>
- </div>
- `;
- }).join('') || '<div style="padding:1rem;color:#666">No fix history yet</div>';
+
+ const item = document.createElement('div');
+ item.className = 'history-item';
+
+ const timeEl = document.createElement('div');
+ timeEl.className = 'time';
+ timeEl.textContent = `${date} (${duration}s)`;
+
+ const processEl = document.createElement('div');
+ processEl.className = 'process';
+ processEl.textContent = `${String(h.processName ?? '')} - ${String(h.appName || 'Unknown App')}`;
+
+ const resultEl = document.createElement('div');
+ const succeeded = h.success === true;
+ resultEl.classList.add('result', succeeded ? 'success' : 'failed');
+ resultEl.textContent = succeeded ? 'Fixed successfully' : 'Fix failed';
+
+ item.append(timeEl, processEl, resultEl);
+ historyPanel.appendChild(item);
+ });
}
clearBtn.addEventListener('click', () => {
- logsContainer.innerHTML = '';
+ logsContainer.replaceChildren();
totalLines = 0;
lineCount.textContent = '0 lines';
});
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 58bbbb674e..dfe9659608 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -124,7 +124,7 @@ function ThemeModeToggle({ className = '' }) {
onClick={toggleMode}
title={`${theme?.label ?? 'Theme'}${pairLabel}`}
aria-label={`Toggle day/night mode${pairLabel}`}
- className={`inline-flex items-center justify-center min-w-[40px] min-h-[40px] sm:min-w-0 sm:min-h-0 sm:p-1.5 rounded-lg text-gray-500 hover:text-port-accent transition-colors ${className}`}
+ className={`inline-flex items-center justify-center min-w-[44px] min-h-[44px] lg:min-w-0 lg:min-h-0 lg:p-1.5 rounded-lg text-gray-500 hover:text-port-accent transition-colors ${className}`}
>
<Icon size={18} aria-hidden="true" />
</button>
@@ -964,7 +964,7 @@ export default function Layout() {
<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"
+ className="lg:hidden inline-flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg text-gray-500 hover:text-white"
aria-label="Close sidebar"
>
<span aria-hidden="true">✕</span>
@@ -1006,7 +1006,7 @@ export default function Layout() {
<div className={`flex items-center gap-1 ${collapsed ? 'lg:flex-col' : ''}`}>
<NavLink
to="/ambient"
- className={`inline-flex items-center justify-center min-w-[40px] min-h-[40px] sm:min-w-0 sm:min-h-0 sm:p-1.5 rounded-lg transition-colors ${collapsed ? 'lg:hidden' : ''} ${
+ className={`inline-flex items-center justify-center min-w-[44px] min-h-[44px] lg:min-w-0 lg:min-h-0 lg:p-1.5 rounded-lg transition-colors ${collapsed ? 'lg:hidden' : ''} ${
isActive('/ambient')
? 'text-port-accent'
: 'text-gray-500 hover:text-white'
@@ -1114,7 +1114,7 @@ export default function Layout() {
<header className="lg:hidden flex items-center justify-between px-2 py-1.5 border-b border-port-border bg-port-card print:hidden">
<button
onClick={() => setMobileOpen(true)}
- className="inline-flex items-center justify-center min-w-[40px] min-h-[40px] -ml-1 rounded-lg text-gray-400 hover:text-white"
+ className="inline-flex items-center justify-center min-w-[44px] min-h-[44px] -ml-1 rounded-lg text-gray-400 hover:text-white"
aria-label="Open navigation menu"
aria-expanded={mobileOpen}
>
@@ -1127,7 +1127,7 @@ export default function Layout() {
<div className="flex items-center gap-0.5">
<NavLink
to="/ambient"
- className={`inline-flex items-center justify-center min-w-[40px] min-h-[40px] rounded-lg transition-colors ${
+ className={`inline-flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg transition-colors ${
isActive('/ambient')
? 'text-port-accent'
: 'text-gray-500 hover:text-white'
diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsx
index 17490a80b9..47ada77ec3 100644
--- a/client/src/components/Layout.test.jsx
+++ b/client/src/components/Layout.test.jsx
@@ -134,3 +134,35 @@ describe('Layout — pinned single nav rows', () => {
expect(within(pinned).getAllByRole('link')).toHaveLength(1);
});
});
+
+describe('Layout — persistent mobile touch targets', () => {
+ const expectAtLeast44px = (element) => {
+ expect(element.className).toContain('min-w-[44px]');
+ expect(element.className).toContain('min-h-[44px]');
+ };
+
+ it('keeps navigation and header controls 44px through the mobile layout', async () => {
+ await renderLayout();
+
+ const openMenu = screen.getByRole('button', { name: 'Open navigation menu' });
+ const closeMenu = screen.getByRole('button', { name: 'Close sidebar' });
+ expectAtLeast44px(openMenu);
+ expectAtLeast44px(closeMenu);
+ expect(openMenu.closest('header')?.className).toContain('lg:hidden');
+ expect(closeMenu.className).toContain('lg:hidden');
+
+ const ambientLinks = screen.getAllByRole('link', { name: 'Ambient display' });
+ expect(ambientLinks).toHaveLength(2);
+ ambientLinks.forEach(expectAtLeast44px);
+
+ const themeToggles = screen.getAllByRole('button', { name: 'Toggle day/night mode' });
+ expect(themeToggles).toHaveLength(2);
+ themeToggles.forEach((toggle) => {
+ expectAtLeast44px(toggle);
+ expect(toggle.className).toContain('lg:min-w-0');
+ expect(toggle.className).toContain('lg:min-h-0');
+ expect(toggle.className).not.toContain('sm:min-w-0');
+ expect(toggle.className).not.toContain('sm:min-h-0');
+ });
+ });
+});
diff --git a/client/src/components/city/CityBillboards.jsx b/client/src/components/city/CityBillboards.jsx
index e310613bcb..e77a460853 100644
--- a/client/src/components/city/CityBillboards.jsx
+++ b/client/src/components/city/CityBillboards.jsx
@@ -2,6 +2,7 @@ import { useRef, useMemo, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import { Text } from '@react-three/drei';
import * as THREE from 'three';
+import { computeDistrictBounds } from '../../utils/cityMiniMap';
import { PIXEL_FONT_URL } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
@@ -229,20 +230,11 @@ export default function CityBillboards({ positions, apps, cosStatus, reviewCount
const onlinePeers = peers.filter(peer => peer.status === 'online').length;
const nodeCount = 1 + peers.length;
- // Find downtown bounding box for billboard placement
- const entries = [];
- positions.forEach((pos) => {
- if (pos.district === 'downtown') entries.push(pos);
- });
- if (entries.length < 2) return [];
-
- let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
- entries.forEach(p => {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
- minZ = Math.min(minZ, p.z);
- maxZ = Math.max(maxZ, p.z);
- });
+ // Find downtown bounding box for billboard placement.
+ const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
+ if (!bounds) return [];
+ const { minX, maxX, minZ, maxZ } = bounds;
+ const downtownCount = [...positions.values()].filter((pos) => pos.district === 'downtown').length;
const uptime = totalActive > 0
? `${Math.round(onlineApps.length / totalActive * 100)}%`
@@ -310,7 +302,7 @@ export default function CityBillboards({ positions, apps, cosStatus, reviewCount
});
// Billboard 3 - Front facing into the city (only if enough buildings)
- if (entries.length >= 4) {
+ if (downtownCount >= 4) {
const frontMessages = onlineApps.slice(0, 6).map(a => ({
label: 'ONLINE',
text: (a.name || '').toUpperCase(),
diff --git a/client/src/components/city/CityNeonSigns.jsx b/client/src/components/city/CityNeonSigns.jsx
index a1a31ef208..f03102e9f2 100644
--- a/client/src/components/city/CityNeonSigns.jsx
+++ b/client/src/components/city/CityNeonSigns.jsx
@@ -2,6 +2,7 @@ import { useRef, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
import { Text } from '@react-three/drei';
import * as THREE from 'three';
+import { computeDistrictBounds } from '../../utils/cityMiniMap';
import { PIXEL_FONT_URL } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
@@ -110,20 +111,9 @@ export default function CityNeonSigns({ positions }) {
const signs = useMemo(() => {
if (!positions || positions.size < 2) return [];
- const entries = [];
- positions.forEach((pos) => {
- if (pos.district === 'downtown') entries.push(pos);
- });
-
- if (entries.length < 2) return [];
-
- let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
- entries.forEach(p => {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
- minZ = Math.min(minZ, p.z);
- maxZ = Math.max(maxZ, p.z);
- });
+ const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
+ if (!bounds) return [];
+ const { minX, maxX, minZ, maxZ } = bounds;
const colors = neonAccents;
const pad = 3;
@@ -210,20 +200,9 @@ export default function CityNeonSigns({ positions }) {
const bars = useMemo(() => {
if (!positions || positions.size < 2) return [];
- const entries = [];
- positions.forEach((pos) => {
- if (pos.district === 'downtown') entries.push(pos);
- });
-
- if (entries.length < 2) return [];
-
- let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
- entries.forEach(p => {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
- minZ = Math.min(minZ, p.z);
- maxZ = Math.max(maxZ, p.z);
- });
+ const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
+ if (!bounds) return [];
+ const { minX, maxX, minZ, maxZ } = bounds;
const colors = neonAccents;
const pad = 3;
diff --git a/client/src/components/city/CitySignalBeacons.jsx b/client/src/components/city/CitySignalBeacons.jsx
index d719017831..7d4c5f02c0 100644
--- a/client/src/components/city/CitySignalBeacons.jsx
+++ b/client/src/components/city/CitySignalBeacons.jsx
@@ -1,6 +1,7 @@
import { useMemo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
+import { computeDistrictBounds } from '../../utils/cityMiniMap';
import { PIXEL_FONT_URL, cityDayMix } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
import CityLabel from './CityLabel';
@@ -83,19 +84,9 @@ export default function CitySignalBeacons({ positions, reviewCounts, instances,
const config = useMemo(() => {
if (!positions || positions.size === 0) return [];
- const entries = [];
- positions.forEach((pos) => {
- if (pos.district === 'downtown') entries.push(pos);
- });
- if (entries.length === 0) return [];
-
- let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
- entries.forEach(p => {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
- minZ = Math.min(minZ, p.z);
- maxZ = Math.max(maxZ, p.z);
- });
+ const bounds = computeDistrictBounds(positions, 'downtown');
+ if (!bounds) return [];
+ const { minX, maxX, minZ, maxZ } = bounds;
const pending = reviewCounts?.total || 0;
const alerts = reviewCounts?.alert || 0;
diff --git a/client/src/components/city/CityTraffic.jsx b/client/src/components/city/CityTraffic.jsx
index 347c652b16..c6b60bc034 100644
--- a/client/src/components/city/CityTraffic.jsx
+++ b/client/src/components/city/CityTraffic.jsx
@@ -1,5 +1,6 @@
import { useRef, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
+import { computeDistrictBounds } from '../../utils/cityMiniMap';
import { useCityPalette } from './CityPaletteContext';
// A single flying hover vehicle
@@ -75,21 +76,9 @@ export default function CityTraffic({ positions }) {
const vehicles = useMemo(() => {
if (!positions || positions.size < 2) return [];
- const entries = [];
- positions.forEach((pos) => {
- if (pos.district === 'downtown') entries.push(pos);
- });
-
- if (entries.length < 2) return [];
-
- // Find bounding box of downtown
- let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
- entries.forEach(p => {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
- minZ = Math.min(minZ, p.z);
- maxZ = Math.max(maxZ, p.z);
- });
+ const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
+ if (!bounds) return [];
+ const { minX, maxX, minZ, maxZ } = bounds;
const pad = 3;
const colors = neonAccents;
@@ -105,7 +94,8 @@ export default function CityTraffic({ positions }) {
];
// Perimeter vehicles (3-5 hover cars circling the downtown)
- const vehicleCount = Math.min(5, Math.max(3, entries.length));
+ const downtownCount = [...positions.values()].filter((pos) => pos.district === 'downtown').length;
+ const vehicleCount = Math.min(5, Math.max(3, downtownCount));
for (let i = 0; i < vehicleCount; i++) {
result.push({
id: `perim-${i}`,
@@ -118,7 +108,7 @@ export default function CityTraffic({ positions }) {
}
// Cross-city lanes (a few vehicles going through the center)
- if (entries.length >= 3) {
+ if (downtownCount >= 3) {
// Horizontal lane
result.push({
id: 'cross-h',
diff --git a/client/src/components/city/CityVolumetricLights.jsx b/client/src/components/city/CityVolumetricLights.jsx
index 8cee6627eb..024aec6ebb 100644
--- a/client/src/components/city/CityVolumetricLights.jsx
+++ b/client/src/components/city/CityVolumetricLights.jsx
@@ -1,6 +1,7 @@
import { useRef, useMemo, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
+import { computeDistrictBounds } from '../../utils/cityMiniMap';
import { cityDayMix } from './cityConstants';
import { useCityPalette } from './CityPaletteContext';
@@ -146,18 +147,9 @@ export default function CityVolumetricLights({ positions, settings }) {
const beams = useMemo(() => {
if (!positions || positions.size < 2) return { lights: [], scans: [] };
- const entries = [];
- positions.forEach((pos) => {
- if (pos.district === 'downtown') entries.push(pos);
- });
-
- let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
- entries.forEach(p => {
- minX = Math.min(minX, p.x);
- maxX = Math.max(maxX, p.x);
- minZ = Math.min(minZ, p.z);
- maxZ = Math.max(maxZ, p.z);
- });
+ const bounds = computeDistrictBounds(positions, 'downtown', { minCount: 2 });
+ if (!bounds) return { lights: [], scans: [] };
+ const { minX, maxX, minZ, maxZ } = bounds;
const pad = 5;
const colors = neonAccents;
diff --git a/client/src/components/voice/VoiceToggleButton.jsx b/client/src/components/voice/VoiceToggleButton.jsx
index 5b54055a9b..3544a22ce5 100644
--- a/client/src/components/voice/VoiceToggleButton.jsx
+++ b/client/src/components/voice/VoiceToggleButton.jsx
@@ -53,7 +53,7 @@ export default function VoiceToggleButton({ className = '' }) {
<button
type="button"
onClick={toggle}
- className={`inline-flex items-center justify-center min-w-[40px] min-h-[40px] sm:min-w-0 sm:min-h-0 sm:p-1.5 rounded-lg transition-colors ${
+ className={`inline-flex items-center justify-center min-w-[44px] min-h-[44px] lg:min-w-0 lg:min-h-0 lg:p-1.5 rounded-lg transition-colors ${
engaged ? 'text-port-accent' : 'text-gray-500 hover:text-white'
} ${className}`}
title={engaged ? 'Hide voice agent controls' : 'Engage voice agent controls'}
diff --git a/client/src/components/voice/VoiceToggleButton.test.jsx b/client/src/components/voice/VoiceToggleButton.test.jsx
new file mode 100644
index 0000000000..00fc13052e
--- /dev/null
+++ b/client/src/components/voice/VoiceToggleButton.test.jsx
@@ -0,0 +1,46 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+
+const mocks = vi.hoisted(() => ({
+ getVoiceConfig: vi.fn(),
+ onVoiceEvent: vi.fn(() => () => {}),
+ readVoiceHidden: vi.fn(() => true),
+ writeVoiceHidden: vi.fn(),
+}));
+
+vi.mock('../../services/apiVoice', () => ({ getVoiceConfig: mocks.getVoiceConfig }));
+vi.mock('../../services/voiceClient', () => ({ onVoiceEvent: mocks.onVoiceEvent }));
+vi.mock('../../services/voiceVisibility', () => ({
+ VISIBILITY_EVENT: 'portos:voice-visibility',
+ ENGAGE_EVENT: 'portos:voice-engage',
+ DISENGAGE_EVENT: 'portos:voice-disengage',
+ readVoiceHidden: mocks.readVoiceHidden,
+ writeVoiceHidden: mocks.writeVoiceHidden,
+ isVoiceHiddenStorageEvent: () => false,
+}));
+
+import VoiceToggleButton from './VoiceToggleButton';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getVoiceConfig.mockResolvedValue({ enabled: true });
+ mocks.readVoiceHidden.mockReturnValue(true);
+});
+
+describe('VoiceToggleButton — persistent mobile touch target', () => {
+ it('stays at least 44px until the desktop layout while keeping the icon compact', async () => {
+ render(<VoiceToggleButton />);
+
+ const button = await screen.findByRole('button', { name: 'Engage voice agent controls' });
+ expect(button.className).toContain('min-w-[44px]');
+ expect(button.className).toContain('min-h-[44px]');
+ expect(button.className).toContain('lg:min-w-0');
+ expect(button.className).toContain('lg:min-h-0');
+ expect(button.className).not.toContain('sm:min-w-0');
+ expect(button.className).not.toContain('sm:min-h-0');
+
+ const icon = button.querySelector('svg');
+ expect(icon).toHaveAttribute('width', '18');
+ expect(icon).toHaveAttribute('height', '18');
+ });
+});
diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsx
index c4c078778e..bf3672ca4e 100644
--- a/client/src/pages/VideoTimelineEditor.jsx
+++ b/client/src/pages/VideoTimelineEditor.jsx
@@ -43,9 +43,10 @@ const totalDuration = (clips) => clips.reduce((s, c) => s + Math.max(0, c.outSec
// Draggable+sortable timeline block. Snaps the trimmed duration to a width
// derived from `pxPerSec` so longer clips visibly take more horizontal space.
-function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {
+export function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSelect, onRemove }) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: clip._key });
const dur = Math.max(0.05, clip.outSec - clip.inSec);
+ const removeLabel = isMissing ? 'missing clip' : clipMeta?.prompt?.trim().slice(0, 40) || 'clip';
const width = Math.max(60, dur * pxPerSec);
const style = {
transform: CSS.Transform.toString(transform),
@@ -88,10 +89,13 @@ function TimelineBlock({ clip, clipMeta, isSelected, isMissing, pxPerSec, onSele
type="button"
onClick={(e) => { e.stopPropagation(); onRemove(clip._key); }}
onPointerDown={(e) => e.stopPropagation()}
- className="absolute top-1 right-1 p-0.5 bg-black/60 hover:bg-port-error rounded opacity-40 sm:opacity-0 sm:group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-white"
+ className="absolute top-0 right-0 inline-flex min-w-[44px] min-h-[44px] items-start justify-end p-1 rounded opacity-40 lg:opacity-0 lg:group-hover:opacity-100 focus-visible:opacity-100 transition-opacity text-white group/remove"
title="Remove from timeline"
+ aria-label={`Remove ${removeLabel} from timeline`}
>
- <X className="w-3 h-3" />
+ <span className="inline-flex items-center justify-center p-0.5 bg-black/60 group-hover/remove:bg-port-error rounded transition-colors" aria-hidden="true">
+ <X className="w-3 h-3" />
+ </span>
</button>
</div>
);
diff --git a/client/src/pages/VideoTimelineEditor.test.jsx b/client/src/pages/VideoTimelineEditor.test.jsx
new file mode 100644
index 0000000000..91b77d126f
--- /dev/null
+++ b/client/src/pages/VideoTimelineEditor.test.jsx
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+
+const dndPointerDown = vi.hoisted(() => vi.fn());
+
+vi.mock('@dnd-kit/sortable', async () => {
+ const actual = await vi.importActual('@dnd-kit/sortable');
+ return {
+ ...actual,
+ useSortable: () => ({
+ attributes: {},
+ listeners: { onPointerDown: dndPointerDown },
+ setNodeRef: () => {},
+ transform: null,
+ transition: null,
+ isDragging: false,
+ }),
+ };
+});
+
+import { TimelineBlock } from './VideoTimelineEditor';
+
+const clip = { _key: 'clip-key', clipId: 'clip-1', inSec: 0, outSec: 2 };
+const clipMeta = { prompt: 'A dramatic sunrise' };
+
+const renderBlock = (props = {}) => {
+ const onSelect = vi.fn();
+ const onRemove = vi.fn();
+ render(
+ <TimelineBlock
+ clip={clip}
+ clipMeta={clipMeta}
+ isSelected={false}
+ isMissing={false}
+ pxPerSec={60}
+ onSelect={onSelect}
+ onRemove={onRemove}
+ {...props}
+ />,
+ );
+ return { onSelect, onRemove };
+};
+
+beforeEach(() => {
+ dndPointerDown.mockClear();
+});
+
+describe('TimelineBlock — remove control', () => {
+ it('provides a 44px hit target and a clip-specific accessible label', () => {
+ renderBlock();
+
+ const remove = screen.getByRole('button', { name: 'Remove A dramatic sunrise from timeline' });
+ expect(remove.className).toContain('min-w-[44px]');
+ expect(remove.className).toContain('min-h-[44px]');
+ expect(remove.className).toContain('lg:opacity-0');
+ expect(remove.className).not.toContain('sm:opacity-0');
+ expect(remove).toHaveAttribute('title', 'Remove from timeline');
+ expect(remove.querySelector('svg').className.baseVal).toContain('w-3 h-3');
+ });
+
+ it('removes without starting a drag or selecting the parent timeline block', () => {
+ const { onSelect, onRemove } = renderBlock();
+ const remove = screen.getByRole('button', { name: 'Remove A dramatic sunrise from timeline' });
+
+ fireEvent.pointerDown(remove);
+ fireEvent.click(remove);
+
+ expect(dndPointerDown).not.toHaveBeenCalled();
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onRemove).toHaveBeenCalledOnce();
+ expect(onRemove).toHaveBeenCalledWith('clip-key');
+ });
+});
diff --git a/client/src/utils/cityMiniMap.js b/client/src/utils/cityMiniMap.js
index b00d62357f..8f64dfdcc6 100644
--- a/client/src/utils/cityMiniMap.js
+++ b/client/src/utils/cityMiniMap.js
@@ -36,6 +36,20 @@ export function computeBounds(positions) {
return { minX, maxX, minZ, maxZ };
}
+// Compute bounds for one layout district directly from the Map returned by
+// computeCityLayout. Keeping the filter + minimum-count gate beside the
+// canonical extrema reducer prevents visual layers from re-implementing the
+// Infinity/-Infinity sentinel loop (and forgetting the empty-district case).
+export function computeDistrictBounds(positions, district, { minCount = 1 } = {}) {
+ if (!positions || typeof positions.forEach !== 'function') return null;
+ const entries = [];
+ positions.forEach((position) => {
+ if (position?.district === district) entries.push(position);
+ });
+ if (entries.length < minCount) return null;
+ return computeBounds(entries);
+}
+
// Project a single world (x, z) into normalized 0..1 map coordinates given the world bounds.
// `nx` runs left→right with world +x; `ny` runs top→bottom with world +z (so the map reads
// like a top-down floor plan). A zero-width or zero-height span (one app, or a row/column)
diff --git a/client/src/utils/cityMiniMap.test.js b/client/src/utils/cityMiniMap.test.js
index dcdb99db15..d31c9b4217 100644
--- a/client/src/utils/cityMiniMap.test.js
+++ b/client/src/utils/cityMiniMap.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
MINI_MAP_PADDING,
computeBounds,
+ computeDistrictBounds,
projectPoint,
computeMiniMap,
geographyWorldPoints,
@@ -29,6 +30,32 @@ describe('computeBounds', () => {
});
});
+describe('computeDistrictBounds', () => {
+ it('returns null when a populated layout has no entries in the requested district', () => {
+ const positions = new Map([
+ ['archived-a', { x: -6, z: 16, district: 'warehouse' }],
+ ['archived-b', { x: 6, z: 16, district: 'warehouse' }],
+ ]);
+
+ expect(computeDistrictBounds(positions, 'downtown', { minCount: 2 })).toBeNull();
+ });
+
+ it('uses the canonical bounds reducer after applying the district and count gate', () => {
+ const positions = new Map([
+ ['a', { x: -4, z: 3, district: 'downtown' }],
+ ['b', { x: 7, z: -2, district: 'downtown' }],
+ ['archived', { x: 100, z: 100, district: 'warehouse' }],
+ ]);
+
+ expect(computeDistrictBounds(positions, 'downtown', { minCount: 2 })).toEqual({
+ minX: -4,
+ maxX: 7,
+ minZ: -2,
+ maxZ: 3,
+ });
+ });
+});
+
describe('projectPoint', () => {
const bounds = { minX: -10, maxX: 10, minZ: -10, maxZ: 10 };
const p = MINI_MAP_PADDING;
diff --git a/server/lib/platform.js b/server/lib/platform.js
index 880e46ffb2..842b4864d5 100644
--- a/server/lib/platform.js
+++ b/server/lib/platform.js
@@ -39,56 +39,77 @@ export function isAppleSilicon({ platform: plat = process.platform, arch = proce
}
/**
- * Get list of listening TCP ports
- * @returns {Promise<number[]>} Array of port numbers
+ * Parse a platform port-discovery command into a sorted unique list. Kept pure
+ * so command formats are covered deterministically instead of depending on the
+ * test host's current listeners or installed utilities.
+ * @param {string} stdout
+ * @param {string} targetPlatform
+ * @returns {number[]} Array of port numbers
*/
-export async function getListeningPorts() {
+export function parseListeningPorts(stdout, targetPlatform = platform) {
const ports = new Set();
+ const addPort = (value) => {
+ const port = Number(value);
+ if (Number.isInteger(port) && port >= 1 && port <= 65535) ports.add(port);
+ };
- if (platform === 'darwin') {
- // macOS: use lsof
- const { stdout } = await execAsync('lsof -iTCP -sTCP:LISTEN -n -P', { windowsHide: true }).catch(() => ({ stdout: '' }));
- const lines = stdout.split('\n').slice(1); // Skip header
- for (const line of lines) {
+ if (targetPlatform === 'darwin') {
+ for (const line of String(stdout || '').split('\n')) {
const match = line.match(/:(\d+)\s+\(LISTEN\)/);
- if (match) {
- ports.add(parseInt(match[1], 10));
- }
+ if (match) addPort(match[1]);
}
- } else if (platform === 'linux') {
- // Linux: use ss
- const { stdout } = await execAsync('ss -lntp', { windowsHide: true }).catch(() => ({ stdout: '' }));
- const lines = stdout.split('\n').slice(1); // Skip header
- for (const line of lines) {
+ } else if (targetPlatform === 'linux') {
+ for (const line of String(stdout || '').split('\n')) {
+ if (!/^\s*LISTEN\b/.test(line)) continue;
const match = line.match(/:(\d+)\s/);
- if (match) {
- ports.add(parseInt(match[1], 10));
- }
+ if (match) addPort(match[1]);
}
} else {
- // Windows: use netstat
- const { stdout } = await execAsync('netstat -an', { windowsHide: true }).catch(() => ({ stdout: '' }));
- const lines = stdout.split('\n');
- for (const line of lines) {
- if (line.includes('LISTENING')) {
- const match = line.match(/:(\d+)\s/);
- if (match) {
- ports.add(parseInt(match[1], 10));
- }
- }
+ for (const line of String(stdout || '').split('\n')) {
+ if (!/\bLISTENING\b/i.test(line)) continue;
+ const match = line.match(/^\s*TCP\s+\S+:(\d+)\s+/i);
+ if (match) addPort(match[1]);
}
}
return Array.from(ports).sort((a, b) => a - b);
}
+function portProbeFor(targetPlatform) {
+ if (targetPlatform === 'darwin') return 'lsof -iTCP -sTCP:LISTEN -n -P';
+ if (targetPlatform === 'linux') return 'ss -lntp';
+ return 'netstat -an';
+}
+
+/**
+ * Get list of listening TCP ports. Discovery failure is explicit: returning an
+ * empty array would be indistinguishable from a host with no listeners and let
+ * callers advertise occupied ports as free.
+ * @param {{platform?: string, exec?: Function}} options deterministic overrides
+ * @returns {Promise<number[]>} Array of port numbers
+ */
+export async function getListeningPorts({ platform: targetPlatform = platform, exec: run = execAsync } = {}) {
+ const command = portProbeFor(targetPlatform);
+ try {
+ const { stdout } = await run(command, { windowsHide: true });
+ return parseListeningPorts(stdout, targetPlatform);
+ } catch (cause) {
+ const error = new Error(`Unable to discover listening ports with ${command}: ${cause.message}`);
+ error.code = 'PORT_DISCOVERY_FAILED';
+ error.command = command;
+ error.platform = targetPlatform;
+ error.cause = cause;
+ throw error;
+ }
+}
+
/**
* Check if a specific port is in use
* @param {number} port Port to check
* @returns {Promise<boolean>} True if port is in use
*/
-export async function isPortInUse(port) {
- const ports = await getListeningPorts();
+export async function isPortInUse(port, probeOptions) {
+ const ports = await getListeningPorts(probeOptions);
return ports.includes(port);
}
@@ -99,12 +120,13 @@ export async function isPortInUse(port) {
* @param {number} count Number of ports to find
* @returns {Promise<number[]>} Available ports
*/
-export async function findAvailablePorts(start, end, count = 1) {
- const usedPorts = await getListeningPorts();
+export async function findAvailablePorts(start, end, count = 1, probeOptions) {
+ if (start > end || count <= 0) return [];
+ const usedPorts = new Set(await getListeningPorts(probeOptions));
const available = [];
for (let port = start; port <= end && available.length < count; port++) {
- if (!usedPorts.includes(port)) {
+ if (!usedPorts.has(port)) {
available.push(port);
}
}
diff --git a/server/lib/platform.test.js b/server/lib/platform.test.js
index ea34491452..c0d01adda5 100644
--- a/server/lib/platform.test.js
+++ b/server/lib/platform.test.js
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest'
-import { platform, getListeningPorts, isPortInUse, findAvailablePorts, isAppleSilicon } from './platform.js'
+import { describe, it, expect, vi } from 'vitest'
+import { platform, parseListeningPorts, getListeningPorts, isPortInUse, findAvailablePorts, isAppleSilicon } from './platform.js'
describe('platform module', () => {
describe('platform constant', () => {
@@ -10,57 +10,88 @@ describe('platform module', () => {
})
describe('getListeningPorts', () => {
- it('should return an array of numbers', async () => {
- const ports = await getListeningPorts()
- expect(Array.isArray(ports)).toBe(true)
- for (const port of ports) {
- expect(typeof port).toBe('number')
- expect(Number.isInteger(port)).toBe(true)
- }
+ it('parses, deduplicates, and sorts deterministic lsof output', () => {
+ const stdout = [
+ 'COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME',
+ 'node 1 user 20u IPv4 0 0t0 TCP *:6001 (LISTEN)',
+ 'node 2 user 21u IPv6 0 0t0 TCP [::1]:5555 (LISTEN)',
+ 'node 3 user 22u IPv4 0 0t0 TCP 127.0.0.1:6001 (LISTEN)',
+ ].join('\n')
+ expect(parseListeningPorts(stdout, 'darwin')).toEqual([5555, 6001])
})
- it('should return ports in sorted order', async () => {
- const ports = await getListeningPorts()
- for (let i = 1; i < ports.length; i++) {
- expect(ports[i]).toBeGreaterThanOrEqual(ports[i - 1])
- }
+ it('parses deterministic ss output', () => {
+ const stdout = [
+ 'State Recv-Q Send-Q Local Address:Port Peer Address:Port Process',
+ 'LISTEN 0 511 0.0.0.0:7000 0.0.0.0:* users:(("node",pid=1,fd=1))',
+ 'LISTEN 0 511 [::]:5555 [::]:* users:(("node",pid=2,fd=2))',
+ ].join('\n')
+ expect(parseListeningPorts(stdout, 'linux')).toEqual([5555, 7000])
+ })
+
+ it('parses only LISTENING rows from deterministic netstat output', () => {
+ const stdout = [
+ ' TCP 0.0.0.0:445 0.0.0.0:0 LISTENING',
+ ' TCP 127.0.0.1:6000 127.0.0.1:50000 ESTABLISHED',
+ ' TCP [::]:7000 [::]:0 LISTENING',
+ ].join('\n')
+ expect(parseListeningPorts(stdout, 'win32')).toEqual([445, 7000])
})
- it('should return unique ports', async () => {
- const ports = await getListeningPorts()
- const unique = new Set(ports)
- expect(unique.size).toBe(ports.length)
+ it('runs the platform probe and surfaces discovery failure explicitly', async () => {
+ const exec = vi.fn()
+ .mockResolvedValueOnce({ stdout: 'State Header\nLISTEN 0 511 0.0.0.0:6000 0.0.0.0:*' })
+ .mockRejectedValueOnce(new Error('ss: command not found'))
+
+ await expect(getListeningPorts({ platform: 'linux', exec })).resolves.toEqual([6000])
+ expect(exec).toHaveBeenCalledWith('ss -lntp', { windowsHide: true })
+ await expect(getListeningPorts({ platform: 'linux', exec })).rejects.toMatchObject({
+ code: 'PORT_DISCOVERY_FAILED',
+ command: 'ss -lntp',
+ })
})
})
describe('isPortInUse', () => {
- it('should return a boolean', async () => {
- const result = await isPortInUse(59999)
- expect(typeof result).toBe('boolean')
+ it('checks a port against deterministic discovery output', async () => {
+ const options = {
+ platform: 'linux',
+ exec: vi.fn().mockResolvedValue({ stdout: 'State Header\nLISTEN 0 511 0.0.0.0:6000 0.0.0.0:*' }),
+ }
+ await expect(isPortInUse(6000, options)).resolves.toBe(true)
+ await expect(isPortInUse(6001, options)).resolves.toBe(false)
})
})
describe('findAvailablePorts', () => {
- it('should return available ports within range', async () => {
- const ports = await findAvailablePorts(49000, 49100, 3)
- expect(Array.isArray(ports)).toBe(true)
- expect(ports.length).toBeLessThanOrEqual(3)
- for (const port of ports) {
- expect(port).toBeGreaterThanOrEqual(49000)
- expect(port).toBeLessThanOrEqual(49100)
+ it('excludes known occupied ports', async () => {
+ const options = {
+ platform: 'linux',
+ exec: vi.fn().mockResolvedValue({
+ stdout: 'State Header\nLISTEN 0 511 0.0.0.0:6000 0.0.0.0:*\nLISTEN 0 511 0.0.0.0:6002 0.0.0.0:*',
+ }),
}
- })
-
- it('should default to finding 1 port', async () => {
- const ports = await findAvailablePorts(49200, 49300)
- expect(ports.length).toBeLessThanOrEqual(1)
+ await expect(findAvailablePorts(6000, 6003, 2, options)).resolves.toEqual([6001, 6003])
})
it('should return empty array when range is exhausted', async () => {
// Range of 0 ports
- const ports = await findAvailablePorts(49400, 49399, 1)
+ const ports = await findAvailablePorts(49400, 49399, 1, {
+ platform: 'linux',
+ exec: vi.fn().mockResolvedValue({ stdout: '' }),
+ })
expect(ports).toEqual([])
})
+
+ it('does not advertise ports as free when discovery is unknown', async () => {
+ const options = {
+ platform: 'linux',
+ exec: vi.fn().mockRejectedValue(new Error('permission denied')),
+ }
+ await expect(findAvailablePorts(6000, 6003, 2, options)).rejects.toMatchObject({
+ code: 'PORT_DISCOVERY_FAILED',
+ })
+ })
})
describe('isAppleSilicon', () => {
diff --git a/server/routes/media.js b/server/routes/media.js
index 3302786d1e..2a8ff7a564 100644
--- a/server/routes/media.js
+++ b/server/routes/media.js
@@ -68,7 +68,13 @@ router.get('/video', (req, res) => {
let frameBuffer = Buffer.alloc(0);
- videoStream.on('data', (chunk) => {
+ const cleanup = () => {
+ videoStream.off('data', onData);
+ videoStream.off('end', onEnd);
+ res.off('close', onClose);
+ };
+
+ const onData = (chunk) => {
frameBuffer = Buffer.concat([frameBuffer, chunk]);
// Look for JPEG markers
@@ -85,15 +91,21 @@ router.get('/video', (req, res) => {
start = frameBuffer.indexOf(Buffer.from([0xFF, 0xD8]));
end = frameBuffer.indexOf(Buffer.from([0xFF, 0xD9]), start + 2);
}
- });
+ };
- videoStream.on('end', () => {
+ const onEnd = () => {
+ cleanup();
res.end();
- });
+ };
- req.on('close', () => {
+ const onClose = () => {
+ cleanup();
console.log('📹 Video client disconnected');
- });
+ };
+
+ videoStream.on('data', onData);
+ videoStream.on('end', onEnd);
+ res.once('close', onClose);
});
// Stream audio
@@ -112,7 +124,8 @@ router.get('/audio', (req, res) => {
audioStream.pipe(res);
- req.on('close', () => {
+ res.once('close', () => {
+ audioStream.unpipe(res);
console.log('🎤 Audio client disconnected');
});
});
diff --git a/server/routes/media.test.js b/server/routes/media.test.js
new file mode 100644
index 0000000000..2a916cb041
--- /dev/null
+++ b/server/routes/media.test.js
@@ -0,0 +1,70 @@
+import { EventEmitter } from 'events';
+import { PassThrough } from 'stream';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getVideoStream: vi.fn(),
+ getAudioStream: vi.fn(),
+}));
+
+vi.mock('../services/mediaService.js', () => ({
+ default: {
+ listDevices: vi.fn(),
+ isVideoStreaming: vi.fn(),
+ isAudioStreaming: vi.fn(),
+ startVideoStream: vi.fn(),
+ startAudioStream: vi.fn(),
+ stopAll: vi.fn(),
+ getVideoStream: (...args) => mocks.getVideoStream(...args),
+ getAudioStream: (...args) => mocks.getAudioStream(...args),
+ },
+}));
+
+const { default: router } = await import('./media.js');
+
+function routeHandler(path) {
+ return router.stack.find((layer) => layer.route?.path === path).route.stack[0].handle;
+}
+
+function responseStream() {
+ const res = new PassThrough();
+ res.setHeader = vi.fn();
+ return res;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('media stream client cleanup', () => {
+ it('detaches video data and end listeners when the client disconnects', () => {
+ const source = new PassThrough();
+ const req = new EventEmitter();
+ const res = responseStream();
+ mocks.getVideoStream.mockReturnValue(source);
+
+ routeHandler('/video')(req, res);
+ expect(source.listenerCount('data')).toBe(1);
+ expect(source.listenerCount('end')).toBe(1);
+
+ res.emit('close');
+
+ expect(source.listenerCount('data')).toBe(0);
+ expect(source.listenerCount('end')).toBe(0);
+ expect(res.listenerCount('close')).toBe(0);
+ });
+
+ it('unpipes the audio source when the client disconnects', () => {
+ const source = new PassThrough();
+ const req = new EventEmitter();
+ const res = responseStream();
+ mocks.getAudioStream.mockReturnValue(source);
+
+ routeHandler('/audio')(req, res);
+ expect(source.listenerCount('data')).toBeGreaterThan(0);
+
+ res.emit('close');
+
+ expect(source.listenerCount('data')).toBe(0);
+ });
+});
diff --git a/server/services/apps.js b/server/services/apps.js
index 53ab80f24e..46871b851c 100644
--- a/server/services/apps.js
+++ b/server/services/apps.js
@@ -584,11 +584,22 @@ export async function updateAppTaskTypeOverride(id, taskType, { enabled, interva
* baselines on the next tick instead of waiting out the prior 30-min custom
* interval — otherwise PRs opened in that delayed window slip past the firstRun
* baseline. Dynamic import avoids a static apps↔taskSchedule cycle (taskSchedule
- * already imports this module). Best-effort: a missing history is a no-op.
+ * already imports this module). Best-effort: a missing history is a no-op and a
+ * storage failure must not block the primary app-disable write, but it is logged
+ * with app context instead of disappearing.
*/
async function resetPrWatcherCooldown(appId) {
- const { resetExecutionHistory } = await import('./taskSchedule.js');
- await resetExecutionHistory('pr-watcher', appId).catch(() => {});
+ try {
+ const { resetExecutionHistory } = await import('./taskSchedule.js');
+ const result = await resetExecutionHistory('pr-watcher', appId);
+ if (result?.error && result.error !== 'No execution history found') {
+ console.error(`❌ Failed to reset pr-watcher cooldown for app ${appId}: ${result.error}`);
+ }
+ return result;
+ } catch (err) {
+ console.error(`❌ Failed to reset pr-watcher cooldown for app ${appId}: ${err.message}`);
+ return { error: err.message };
+ }
}
/**
diff --git a/server/services/apps.test.js b/server/services/apps.test.js
index 0c477d4f2b..56a0681964 100644
--- a/server/services/apps.test.js
+++ b/server/services/apps.test.js
@@ -22,6 +22,7 @@ vi.mock('../lib/ports.js', () => ({
vi.mock('./taskSchedule.js', () => ({
SELF_IMPROVEMENT_TASK_TYPES: [],
+ resetExecutionHistory: vi.fn().mockResolvedValue({ error: 'No execution history found' }),
}));
vi.mock('./pm2.js', () => ({
@@ -30,9 +31,52 @@ vi.mock('./pm2.js', () => ({
listProcessesStrict: vi.fn().mockResolvedValue([]),
}));
-import { readJSONFile } from '../lib/fileUtils.js';
+import { atomicWrite, readJSONFile } from '../lib/fileUtils.js';
import { listProcessesStrict } from './pm2.js';
-import { getAppStatuses, getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID } from './apps.js';
+import { resetExecutionHistory } from './taskSchedule.js';
+import { getAppStatuses, getAppStatusSummary, getReservedPorts, invalidateCache, PORTOS_APP_ID, updateAppTaskTypeOverride } from './apps.js';
+
+describe('pr-watcher cooldown reset', () => {
+ beforeEach(() => {
+ invalidateCache();
+ vi.clearAllMocks();
+ readJSONFile.mockResolvedValue({
+ apps: {
+ 'app-1': {
+ name: 'App One',
+ prWatcherState: { lastSeenPr: 42 },
+ taskTypeOverrides: { 'pr-watcher': { enabled: true } },
+ },
+ },
+ });
+ });
+
+ it('keeps the primary disable successful but logs a contextual storage failure', async () => {
+ resetExecutionHistory.mockRejectedValueOnce(new Error('ENOSPC: schedule write failed'));
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const updated = await updateAppTaskTypeOverride('app-1', 'pr-watcher', { enabled: false });
+
+ expect(updated.taskTypeOverrides['pr-watcher'].enabled).toBe(false);
+ expect(updated.prWatcherState).toBeUndefined();
+ expect(atomicWrite).toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining(
+ 'Failed to reset pr-watcher cooldown for app app-1: ENOSPC: schedule write failed'
+ ));
+ errorSpy.mockRestore();
+ });
+
+ it('treats missing execution history as a quiet no-op', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const updated = await updateAppTaskTypeOverride('app-1', 'pr-watcher', { enabled: false });
+
+ expect(updated.taskTypeOverrides['pr-watcher'].enabled).toBe(false);
+ expect(resetExecutionHistory).toHaveBeenCalledWith('pr-watcher', 'app-1');
+ expect(errorSpy).not.toHaveBeenCalled();
+ errorSpy.mockRestore();
+ });
+});
describe('getReservedPorts', () => {
beforeEach(() => {
diff --git a/server/services/backup.js b/server/services/backup.js
index 60ad231db1..d02bb516b2 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -100,10 +100,18 @@ export function backupStatusForPg(pgResult) {
* Run rsync from srcDir to destDir with optional flags.
* Resolves with array of changed file lines. Rejects on non-zero exit (except 24).
*/
+export function resolveRsyncBinary(env = process.env) {
+ const override = typeof env.PORTOS_RSYNC === 'string' ? env.PORTOS_RSYNC.trim() : '';
+ // A bare command lets spawn resolve rsync through PATH on macOS, Linux,
+ // Windows/MSYS, and non-standard Unix layouts. PORTOS_RSYNC remains the
+ // explicit escape hatch for bundled or custom installations.
+ return override || 'rsync';
+}
+
function runRsync(srcDir, destDir, flags = []) {
return new Promise((resolve, reject) => {
const args = ['--archive', '--itemize-changes', ...flags, srcDir + '/', destDir];
- const proc = spawn('/usr/bin/rsync', args, { shell: false });
+ const proc = spawn(resolveRsyncBinary(), args, { shell: false });
const changed = [];
let stderr = '';
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 1b9d4fc4cd..7149163836 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -53,6 +53,7 @@ import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots, restoreSnaps
// Helper: build a fake child process whose close/error we can drive.
function fakeProc() {
const proc = new EventEmitter();
+ proc.stdout = new EventEmitter();
proc.stderr = new EventEmitter();
return proc;
}
@@ -681,4 +682,51 @@ describe('restoreSnapshot subdirFilter guard', () => {
.rejects.toThrow(/Invalid subdirFilter/);
expect(spawn).not.toHaveBeenCalled();
});
+
+ it('uses PORTOS_RSYNC when configured and keeps shell execution disabled', async () => {
+ const previous = process.env.PORTOS_RSYNC;
+ process.env.PORTOS_RSYNC = '/custom/bin/rsync';
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+
+ try {
+ const restore = restoreSnapshot('/dest', 'snap-1');
+ await flush();
+ proc.stdout.emit('data', Buffer.from('>f+++++++++ settings.json\n'));
+ proc.emit('close', 0);
+
+ await expect(restore).resolves.toMatchObject({
+ dryRun: true,
+ changedFiles: ['>f+++++++++ settings.json'],
+ });
+ expect(spawn).toHaveBeenCalledWith(
+ '/custom/bin/rsync',
+ expect.arrayContaining(['--archive', '--itemize-changes', '--dry-run']),
+ { shell: false },
+ );
+ } finally {
+ if (previous === undefined) delete process.env.PORTOS_RSYNC;
+ else process.env.PORTOS_RSYNC = previous;
+ }
+ });
+
+ it('falls back to the PATH-resolved rsync command when no override is configured', async () => {
+ const previous = process.env.PORTOS_RSYNC;
+ delete process.env.PORTOS_RSYNC;
+ const proc = fakeProc();
+ spawn.mockReturnValue(proc);
+
+ try {
+ const restore = restoreSnapshot('/dest', 'snap-1');
+ await flush();
+ proc.emit('close', 0);
+ await restore;
+
+ expect(spawn.mock.calls[0][0]).toBe('rsync');
+ expect(spawn.mock.calls[0][2]).toEqual({ shell: false });
+ } finally {
+ if (previous === undefined) delete process.env.PORTOS_RSYNC;
+ else process.env.PORTOS_RSYNC = previous;
+ }
+ });
});
diff --git a/server/services/mediaService.js b/server/services/mediaService.js
index 8e657faaa4..5dd7e30deb 100644
--- a/server/services/mediaService.js
+++ b/server/services/mediaService.js
@@ -67,10 +67,10 @@ function startVideoStream(deviceId = '0') {
stopVideoStream();
}
- videoStream = new PassThrough();
+ const stream = new PassThrough();
// Use MJPEG format for compatibility and low latency
- videoProcess = spawn('ffmpeg', [
+ const process = spawn('ffmpeg', [
'-f', 'avfoundation',
'-video_size', '1280x720',
'-framerate', '30',
@@ -79,26 +79,29 @@ function startVideoStream(deviceId = '0') {
'-q:v', '5',
'-'
], { env: safeChildProcessEnv() });
+ videoProcess = process;
+ videoStream = stream;
- videoProcess.stdout.pipe(videoStream);
+ process.stdout.pipe(stream);
- videoProcess.stderr.on('data', (data) => {
+ process.stderr.on('data', (data) => {
const msg = data.toString();
if (!msg.includes('frame=') && !msg.includes('fps=')) {
console.log(`📹 FFmpeg video: ${msg.trim()}`);
}
});
- videoProcess.on('error', (err) => {
+ process.on('error', (err) => {
console.error(`❌ Video stream error: ${err.message}`);
});
- videoProcess.on('close', () => {
+ process.on('close', () => {
console.log('📹 Video stream stopped');
- videoStream = null;
+ if (videoProcess === process) videoProcess = null;
+ if (videoStream === stream) videoStream = null;
});
- return videoStream;
+ return stream;
}
function startAudioStream(deviceId = '0') {
@@ -107,10 +110,10 @@ function startAudioStream(deviceId = '0') {
stopAudioStream();
}
- audioStream = new PassThrough();
+ const stream = new PassThrough();
// Use WebM format with Opus codec for web compatibility
- audioProcess = spawn('ffmpeg', [
+ const process = spawn('ffmpeg', [
'-f', 'avfoundation',
'-i', `:${deviceId}`,
'-f', 'webm',
@@ -120,26 +123,29 @@ function startAudioStream(deviceId = '0') {
'-b:a', '128k',
'-'
], { env: safeChildProcessEnv() });
+ audioProcess = process;
+ audioStream = stream;
- audioProcess.stdout.pipe(audioStream);
+ process.stdout.pipe(stream);
- audioProcess.stderr.on('data', (data) => {
+ process.stderr.on('data', (data) => {
const msg = data.toString();
if (!msg.includes('frame=') && !msg.includes('size=')) {
console.log(`🎤 FFmpeg audio: ${msg.trim()}`);
}
});
- audioProcess.on('error', (err) => {
+ process.on('error', (err) => {
console.error(`❌ Audio stream error: ${err.message}`);
});
- audioProcess.on('close', () => {
+ process.on('close', () => {
console.log('🎤 Audio stream stopped');
- audioStream = null;
+ if (audioProcess === process) audioProcess = null;
+ if (audioStream === stream) audioStream = null;
});
- return audioStream;
+ return stream;
}
function stopVideoStream() {
diff --git a/server/services/mediaService.test.js b/server/services/mediaService.test.js
new file mode 100644
index 0000000000..513c020ce2
--- /dev/null
+++ b/server/services/mediaService.test.js
@@ -0,0 +1,68 @@
+import { EventEmitter } from 'events';
+import { PassThrough } from 'stream';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const spawn = vi.hoisted(() => vi.fn());
+vi.mock('child_process', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: (...args) => spawn(...args),
+}));
+
+const { default: mediaService } = await import('./mediaService.js');
+
+function fakeProcess() {
+ const proc = new EventEmitter();
+ proc.stdout = new PassThrough();
+ proc.stderr = new PassThrough();
+ proc.kill = vi.fn();
+ return proc;
+}
+
+beforeEach(() => {
+ mediaService.stopAll();
+ spawn.mockReset();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ mediaService.stopAll();
+ vi.restoreAllMocks();
+});
+
+describe('mediaService stream ownership', () => {
+ it('ignores a replaced video process close event', () => {
+ const oldProcess = fakeProcess();
+ const replacementProcess = fakeProcess();
+ spawn.mockReturnValueOnce(oldProcess).mockReturnValueOnce(replacementProcess);
+
+ mediaService.startVideoStream('0');
+ const replacement = mediaService.startVideoStream('1');
+ oldProcess.emit('close', 0);
+
+ expect(oldProcess.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(mediaService.getVideoStream()).toBe(replacement);
+ expect(mediaService.isVideoStreaming()).toBe(true);
+
+ replacementProcess.emit('close', 0);
+ expect(mediaService.getVideoStream()).toBeNull();
+ expect(mediaService.isVideoStreaming()).toBe(false);
+ });
+
+ it('ignores a replaced audio process close event', () => {
+ const oldProcess = fakeProcess();
+ const replacementProcess = fakeProcess();
+ spawn.mockReturnValueOnce(oldProcess).mockReturnValueOnce(replacementProcess);
+
+ mediaService.startAudioStream('0');
+ const replacement = mediaService.startAudioStream('1');
+ oldProcess.emit('close', 0);
+
+ expect(oldProcess.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(mediaService.getAudioStream()).toBe(replacement);
+ expect(mediaService.isAudioStreaming()).toBe(true);
+
+ replacementProcess.emit('close', 0);
+ expect(mediaService.getAudioStream()).toBeNull();
+ expect(mediaService.isAudioStreaming()).toBe(false);
+ });
+});
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index 7e4f60a2b9..cebf627aee 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -156,7 +156,9 @@ function ownPortsOf(app) {
async function gatherTakenPorts(excludePorts = []) {
const [reserved, listening] = await Promise.all([
getReservedPorts().catch(() => []),
- getListeningPorts().catch(() => []),
+ // Port discovery is safety-critical here: an unknown listener set must abort
+ // analysis instead of being rendered as "none detected" and reassigned over.
+ getListeningPorts(),
]);
// Exempt the app's own ports ONLY from the reserved-app registry — so
// re-standardizing keeps them. Do NOT exempt them from `listening`: if the
diff --git a/server/services/runner.js b/server/services/runner.js
index b12bf8d539..6a68ab00ca 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -266,85 +266,74 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
abortForImmediateFallbackSignal(text);
});
- childProcess.on('error', async (err) => {
- if (timeoutHandle) clearTimeout(timeoutHandle);
- toolkit.services.runner.unregisterExternalRun(runId);
- cleanupPromptFile();
- console.error(`❌ Run ${runId} spawn error: ${err.message}`);
-
- const metadata = {
- endTime: new Date().toISOString(),
- duration: Date.now() - startTime,
- exitCode: -1,
- success: false,
- error: `Spawn failed: ${err.message}`,
- errorCategory: 'spawn_error',
- outputSize: Buffer.byteLength(output)
- };
-
- await writeFile(outputPath, output).catch(() => {});
- await atomicWrite(metadataPath, metadata).catch(() => {});
- // Isolate the hook from onComplete — a throwing onRunFailed must not block
- // the caller from settling, and an uncaught throw here would crash the
- // process (this runs outside the request lifecycle).
- safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);
- safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);
- });
+ // Node emits `error` for a spawn failure and commonly follows it with `close`.
+ // Funnel both events through one promise so terminal persistence + hooks run
+ // exactly once. The finalizer always merges into createRun's metadata instead
+ // of replacing attribution fields on the spawn-error path.
+ let finalizationPromise = null;
+ const finalizeTerminal = async ({ exitCode, spawnError = null }) => {
+ const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');
+ let metadata = {};
+ try {
+ const parsed = JSON.parse(metadataStr);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) metadata = parsed;
+ } catch {
+ console.log('⚠️ Corrupted metadata for run, using fresh');
+ }
+
+ // Direct callers may not have gone through createRun. Fill only absent
+ // attribution fields; never overwrite the persisted provider/workspace.
+ metadata.id ??= runId;
+ if (metadata.providerId == null && provider.id) metadata.providerId = provider.id;
+ if (metadata.providerName == null && (provider.name || provider.id)) metadata.providerName = provider.name || provider.id;
+ if (metadata.model == null && provider.defaultModel) metadata.model = provider.defaultModel;
+ if (metadata.workspacePath == null && workspacePath) metadata.workspacePath = workspacePath;
- childProcess.on('close', async (code) => {
- // This runs outside the Express request lifecycle — an uncaught throw
- // (e.g. a failed metadata write) would crash the Node process, so wrap
- // the whole body and log via the emoji-prefixed convention.
try {
if (timeoutHandle) clearTimeout(timeoutHandle);
toolkit.services.runner.unregisterExternalRun(runId);
cleanupPromptFile();
+ if (spawnError) console.error(`❌ Run ${runId} spawn error: ${spawnError.message}`);
await writeFile(outputPath, output);
- const metadataStr = await readFile(metadataPath, 'utf-8').catch(() => '{}');
- let metadata = {};
- try { metadata = JSON.parse(metadataStr); } catch { console.log('⚠️ Corrupted metadata for run, using fresh'); }
metadata.endTime = new Date().toISOString();
metadata.duration = Date.now() - startTime;
- metadata.exitCode = code;
- // A mid-stream fallback signal (e.g. usage-limit hit) SIGTERM-kills the
- // child; if it happens to exit 0 in that race, don't record the run as
- // successful — the fallback path (onRunFailed) must fire. Mirrors the TUI
- // finish({ success: false }) handling of the same signal.
- metadata.success = code === 0 && !immediateFallbackAnalysis;
+ metadata.exitCode = exitCode;
+ metadata.success = spawnError ? false : exitCode === 0 && !immediateFallbackAnalysis;
metadata.outputSize = Buffer.byteLength(output);
- // Analyze errors if the run failed (delegate to toolkit's error detection)
- if (!metadata.success && toolkit.services.errorDetection) {
- const errorAnalysis = immediateFallbackAnalysis || toolkit.services.errorDetection.analyzeError(output, code);
- metadata.error = errorAnalysis.message || `Process exited with code ${code}`;
+ if (spawnError) {
+ metadata.error = `Spawn failed: ${spawnError.message}`;
+ metadata.errorCategory = 'spawn_error';
+ } else if (!metadata.success && toolkit.services.errorDetection) {
+ // A mid-stream fallback signal (e.g. usage-limit hit) SIGTERM-kills the
+ // child; even an exit 0 must remain a failure so fallback can run.
+ const errorAnalysis = immediateFallbackAnalysis || toolkit.services.errorDetection.analyzeError(output, exitCode);
+ metadata.error = errorAnalysis.message || `Process exited with code ${exitCode}`;
metadata.errorCategory = errorAnalysis.category;
metadata.errorAnalysis = errorAnalysis;
}
await atomicWrite(metadataPath, metadata);
- // Isolate the completion hooks + onComplete from the outer catch — a
- // throwing onRunCompleted must NOT be reinterpreted as a finalization
- // failure that flips a successful run to success:false for the caller.
+ // Isolate lifecycle hooks from onComplete so a hook failure never changes
+ // the terminal result or prevents the caller from settling.
if (metadata.success) {
safeSettle(() => runnerConfig.hooks?.onRunCompleted?.(metadata, output), `Run ${runId} onRunCompleted hook`);
} else {
safeSettle(() => runnerConfig.hooks?.onRunFailed?.(metadata, metadata.error, output), `Run ${runId} onRunFailed hook`);
}
safeSettle(() => onComplete?.(metadata), `Run ${runId} onComplete`);
+ return metadata;
} catch (err) {
- console.error(`❌ Run ${runId} close handler error: ${err.message}`);
- // The timeout was already cleared and the child has closed, so callers
- // waiting on onComplete would hang forever if we only logged. Settle them
- // with failure metadata so a disk/hook failure surfaces as a failed run.
- // The hook and onComplete are isolated from each other — a throwing
- // onRunFailed must NOT prevent onComplete from settling the caller.
+ const handler = spawnError ? 'error' : 'close';
+ console.error(`❌ Run ${runId} ${handler} handler error: ${err.message}`);
const failMetadata = {
+ ...metadata,
endTime: new Date().toISOString(),
duration: Date.now() - startTime,
- exitCode: code,
+ exitCode,
success: false,
error: `Run finalization failed: ${err.message}`,
errorCategory: 'finalization_error',
@@ -352,7 +341,20 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
};
safeSettle(() => runnerConfig.hooks?.onRunFailed?.(failMetadata, failMetadata.error, output), `Run ${runId} onRunFailed hook`);
safeSettle(() => onComplete?.(failMetadata), `Run ${runId} onComplete`);
+ return failMetadata;
}
+ };
+ const finalizeOnce = (terminal) => {
+ if (!finalizationPromise) finalizationPromise = finalizeTerminal(terminal);
+ return finalizationPromise;
+ };
+
+ childProcess.on('error', (err) => {
+ void finalizeOnce({ exitCode: -1, spawnError: err });
+ });
+
+ childProcess.on('close', (code) => {
+ void finalizeOnce({ exitCode: code });
});
return runId;
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index 09ecc3312c..d465e1c0e1 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -39,7 +39,8 @@ vi.mock('fs/promises', () => ({
}));
const { spawn } = await import('child_process');
-const { writeFile } = await import('fs/promises');
+const { writeFile, readFile } = await import('fs/promises');
+const { atomicWrite } = await import('../lib/fileUtils.js');
const runner = await import('./runner.js');
const { analyzeError, ERROR_CATEGORIES } = await import('../lib/aiToolkit/errorDetection.js');
const { setAIToolkit, executeCliRun, buildCliArgs, hasModelFlag, extractBakedModel, emitRunStarted } = runner;
@@ -355,6 +356,64 @@ describe('executeCliRun — close handler crash guard', () => {
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('onRunCompleted hook threw during recovery'));
errorSpy.mockRestore();
});
+
+ it('finalizes a spawn error exactly once when error is followed by close', async () => {
+ const child = makeChild();
+ spawn.mockReturnValue(child);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const onRunFailed = vi.fn();
+ const onComplete = vi.fn();
+ setAIToolkit(fakeToolkit(), {
+ dataDir: '/tmp/test-runner',
+ hooks: { onRunFailed },
+ });
+ readFile.mockResolvedValueOnce(JSON.stringify({
+ id: 'run-spawn-error',
+ providerId: 'configured-provider',
+ providerName: 'Configured Provider',
+ model: 'configured-model',
+ workspacePath: '/configured/workspace',
+ workspaceName: 'configured-workspace',
+ source: 'test-source',
+ startTime: '2026-07-10T00:00:00.000Z',
+ }));
+
+ const provider = {
+ id: 'codex', name: 'Codex', command: 'codex', args: [],
+ defaultModel: 'codex-configured-default', timeout: 5000,
+ };
+ await executeCliRun({
+ runId: 'run-spawn-error',
+ provider,
+ prompt: 'test prompt',
+ workspacePath: '/workspace',
+ onComplete,
+ });
+
+ child.emit('error', new Error('spawn ENOENT'));
+ child.emit('close', -1);
+
+ await vi.waitFor(() => expect(onComplete).toHaveBeenCalledTimes(1));
+ expect(onRunFailed).toHaveBeenCalledTimes(1);
+ expect(atomicWrite).toHaveBeenCalledTimes(1);
+
+ const persisted = atomicWrite.mock.calls[0][1];
+ expect(persisted).toMatchObject({
+ id: 'run-spawn-error',
+ providerId: 'configured-provider',
+ providerName: 'Configured Provider',
+ model: 'configured-model',
+ workspacePath: '/configured/workspace',
+ workspaceName: 'configured-workspace',
+ source: 'test-source',
+ exitCode: -1,
+ success: false,
+ error: 'Spawn failed: spawn ENOENT',
+ errorCategory: 'spawn_error',
+ });
+ expect(onComplete).toHaveBeenCalledWith(persisted);
+ errorSpy.mockRestore();
+ });
});
describe('buildCliArgs — claude-code defaultModel honoring', () => {
diff --git a/server/services/spotifySync.js b/server/services/spotifySync.js
index 940d8941e7..72998ef3ec 100644
--- a/server/services/spotifySync.js
+++ b/server/services/spotifySync.js
@@ -21,6 +21,7 @@
* and unit-tested with fixture payloads — no network or DB required.
*/
import { dataPath, ensureDir, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { getSettings } from './settings.js';
import { getAccessToken, getAuthStatus } from './spotifyAuth.js';
@@ -29,6 +30,7 @@ import { getAccessToken, getAuthStatus } from './spotifyAuth.js';
// ---------------------------------------------------------------------------
const RECENTLY_PLAYED_URL = 'https://api.spotify.com/v1/me/player/recently-played';
+const RECENTLY_PLAYED_TIMEOUT_MS = 15_000;
// The API caps this at 50; the cursor + fast cadence keep us from missing plays.
const SCAN_LIMIT = 50;
@@ -183,7 +185,18 @@ async function doRunSync() {
url.searchParams.set('limit', String(SCAN_LIMIT));
if (state.cursorAfter) url.searchParams.set('after', String(state.cursorAfter));
- const res = await fetch(url, { headers: { Authorization: `Bearer ${accessToken}` } });
+ let res;
+ try {
+ res = await fetchWithTimeout(
+ url,
+ { headers: { Authorization: `Bearer ${accessToken}` } },
+ RECENTLY_PLAYED_TIMEOUT_MS,
+ );
+ } catch (err) {
+ const reason = err?.message || String(err);
+ console.error(`❌ Spotify recently-played fetch failed: ${reason}`);
+ return { ok: false, error: `Spotify API request failed: ${reason}` };
+ }
if (!res.ok) {
const body = await res.text().catch(() => '');
console.error(`❌ Spotify recently-played fetch failed: ${res.status} ${body.slice(0, 200)}`);
diff --git a/server/services/spotifySync.test.js b/server/services/spotifySync.test.js
index fce2bffdff..aa037ec720 100644
--- a/server/services/spotifySync.test.js
+++ b/server/services/spotifySync.test.js
@@ -1,10 +1,45 @@
-import { describe, it, expect } from 'vitest';
+import { beforeEach, describe, it, expect, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ fetchWithTimeout: vi.fn(),
+ getAccessToken: vi.fn(),
+ getAuthStatus: vi.fn(),
+ getSettings: vi.fn(),
+ tryReadFile: vi.fn(),
+ atomicWrite: vi.fn(),
+ ensureDir: vi.fn(),
+}));
+
+vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: (...args) => mocks.fetchWithTimeout(...args) }));
+vi.mock('./spotifyAuth.js', () => ({
+ getAccessToken: (...args) => mocks.getAccessToken(...args),
+ getAuthStatus: (...args) => mocks.getAuthStatus(...args),
+}));
+vi.mock('./settings.js', () => ({ getSettings: (...args) => mocks.getSettings(...args) }));
+vi.mock('../lib/fileUtils.js', () => ({
+ dataPath: (...parts) => `/tmp/${parts.join('/')}`,
+ ensureDir: (...args) => mocks.ensureDir(...args),
+ atomicWrite: (...args) => mocks.atomicWrite(...args),
+ tryReadFile: (...args) => mocks.tryReadFile(...args),
+ safeJSONParse: (raw, fallback) => {
+ try { return JSON.parse(raw); } catch { return fallback; }
+ },
+}));
+
import {
spotifyListenCandidate,
spotifyListenCandidates,
maxPlayedAtMs,
+ runSync,
} from './spotifySync.js';
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getAccessToken.mockResolvedValue('access-token');
+ mocks.getSettings.mockResolvedValue({});
+ mocks.tryReadFile.mockResolvedValue(null);
+});
+
// A minimal recently-played item, shaped like the Spotify Web API response.
function makeItem(overrides = {}) {
return {
@@ -136,3 +171,21 @@ describe('spotifySync pure helpers', () => {
});
});
});
+
+describe('runSync network boundary', () => {
+ it('uses the bounded fetch helper and returns an error result when it times out', async () => {
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.fetchWithTimeout.mockRejectedValue(new Error('request timed out'));
+
+ const result = await runSync();
+
+ expect(mocks.fetchWithTimeout).toHaveBeenCalledWith(
+ expect.any(URL),
+ { headers: { Authorization: 'Bearer access-token' } },
+ 15_000,
+ );
+ expect(result).toEqual({ ok: false, error: 'Spotify API request failed: request timed out' });
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('request timed out'));
+ log.mockRestore();
+ });
+});
diff --git a/server/services/taskWatcher.js b/server/services/taskWatcher.js
index da964ac181..7746c11aad 100644
--- a/server/services/taskWatcher.js
+++ b/server/services/taskWatcher.js
@@ -16,6 +16,25 @@ let watcher = null;
let isWatching = false;
let lastUserTasks = null;
let lastCosTasks = null;
+const pendingFileEvents = new Map();
+
+// Chokidar does not await async listeners. Keep one promise tail per watched
+// file so a quick add/change/unlink burst cannot race the cached snapshot, and
+// keep each lane alive after a failed read.
+function queueFileEvent(path, event, operation) {
+ const previous = pendingFileEvents.get(path) || Promise.resolve();
+ const tail = previous
+ .then(operation)
+ .catch((error) => {
+ console.error(`❌ Task watcher ${event} failed for ${path}: ${error?.message || error}`);
+ cosEvents.emit('watcher:error', { error: error?.message || String(error), event, file: path });
+ })
+ .finally(() => {
+ if (pendingFileEvents.get(path) === tail) pendingFileEvents.delete(path);
+ });
+ pendingFileEvents.set(path, tail);
+ return tail;
+}
/**
* Start watching task files
@@ -42,32 +61,38 @@ export async function startWatching() {
}
});
- watcher.on('change', async (path) => {
- if (path.endsWith(config.userTasksFile)) {
- await handleUserTasksChange();
- } else if (path.endsWith(config.cosTasksFile)) {
- await handleCosTasksChange();
- }
+ watcher.on('change', (path) => {
+ queueFileEvent(path, 'change', async () => {
+ if (path.endsWith(config.userTasksFile)) {
+ await handleUserTasksChange();
+ } else if (path.endsWith(config.cosTasksFile)) {
+ await handleCosTasksChange();
+ }
+ });
});
- watcher.on('add', async (path) => {
- if (path.endsWith(config.userTasksFile)) {
- lastUserTasks = await getUserTasks();
- cosEvents.emit('tasks:user:created', lastUserTasks);
- } else if (path.endsWith(config.cosTasksFile)) {
- lastCosTasks = await getCosTasks();
- cosEvents.emit('tasks:cos:created', lastCosTasks);
- }
+ watcher.on('add', (path) => {
+ queueFileEvent(path, 'add', async () => {
+ if (path.endsWith(config.userTasksFile)) {
+ lastUserTasks = await getUserTasks();
+ cosEvents.emit('tasks:user:created', lastUserTasks);
+ } else if (path.endsWith(config.cosTasksFile)) {
+ lastCosTasks = await getCosTasks();
+ cosEvents.emit('tasks:cos:created', lastCosTasks);
+ }
+ });
});
- watcher.on('unlink', async (path) => {
- if (path.endsWith(config.userTasksFile)) {
- cosEvents.emit('tasks:user:deleted', { file: path });
- lastUserTasks = null;
- } else if (path.endsWith(config.cosTasksFile)) {
- cosEvents.emit('tasks:cos:deleted', { file: path });
- lastCosTasks = null;
- }
+ watcher.on('unlink', (path) => {
+ queueFileEvent(path, 'unlink', async () => {
+ if (path.endsWith(config.userTasksFile)) {
+ cosEvents.emit('tasks:user:deleted', { file: path });
+ lastUserTasks = null;
+ } else if (path.endsWith(config.cosTasksFile)) {
+ cosEvents.emit('tasks:cos:deleted', { file: path });
+ lastCosTasks = null;
+ }
+ });
});
watcher.on('error', (error) => {
@@ -91,6 +116,7 @@ export async function stopWatching() {
}
await watcher.close();
+ await Promise.all([...pendingFileEvents.values()]);
watcher = null;
isWatching = false;
diff --git a/server/services/taskWatcher.test.js b/server/services/taskWatcher.test.js
new file mode 100644
index 0000000000..ddda902ba9
--- /dev/null
+++ b/server/services/taskWatcher.test.js
@@ -0,0 +1,104 @@
+import { EventEmitter } from 'events';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ watch: vi.fn(),
+ emit: vi.fn(),
+ getUserTasks: vi.fn(),
+ getCosTasks: vi.fn(),
+ getConfig: vi.fn(),
+}));
+
+vi.mock('chokidar', () => ({ watch: (...args) => mocks.watch(...args) }));
+vi.mock('./cos.js', () => ({
+ cosEvents: { emit: (...args) => mocks.emit(...args) },
+ getUserTasks: (...args) => mocks.getUserTasks(...args),
+ getCosTasks: (...args) => mocks.getCosTasks(...args),
+ getConfig: (...args) => mocks.getConfig(...args),
+}));
+
+const { getWatcherStatus, startWatching, stopWatching } = await import('./taskWatcher.js');
+
+class FakeWatcher extends EventEmitter {
+ close = vi.fn(async () => {});
+}
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((r) => { resolve = r; });
+ return { promise, resolve };
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getConfig.mockResolvedValue({ userTasksFile: 'TASKS.md', cosTasksFile: 'COS-TASKS.md' });
+ mocks.getUserTasks.mockResolvedValue({ tasks: [] });
+ mocks.getCosTasks.mockResolvedValue({ tasks: [] });
+});
+
+afterEach(async () => {
+ if (getWatcherStatus().watching) await stopWatching();
+ vi.restoreAllMocks();
+});
+
+describe('taskWatcher event queue', () => {
+ it('serializes callbacks for one file and waits for the tail during stop', async () => {
+ const watcher = new FakeWatcher();
+ const first = deferred();
+ const order = [];
+ mocks.watch.mockReturnValue(watcher);
+ mocks.getUserTasks
+ .mockResolvedValueOnce({ tasks: [] })
+ .mockImplementationOnce(async () => {
+ order.push('first:start');
+ await first.promise;
+ order.push('first:end');
+ return { tasks: [{ id: 'a', status: 'pending' }] };
+ })
+ .mockImplementationOnce(async () => {
+ order.push('second:start');
+ return { tasks: [{ id: 'a', status: 'completed' }] };
+ });
+
+ await startWatching();
+ watcher.emit('change', '/repo/TASKS.md');
+ watcher.emit('change', '/repo/TASKS.md');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(order).toEqual(['first:start']);
+ let stopped = false;
+ const stopping = stopWatching().then(() => { stopped = true; });
+ await Promise.resolve();
+ expect(stopped).toBe(false);
+
+ first.resolve();
+ await stopping;
+
+ expect(order).toEqual(['first:start', 'first:end', 'second:start']);
+ expect(watcher.close).toHaveBeenCalledOnce();
+ });
+
+ it('catches a failed callback and continues the same file lane', async () => {
+ const watcher = new FakeWatcher();
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.watch.mockReturnValue(watcher);
+ mocks.getUserTasks
+ .mockResolvedValueOnce({ tasks: [] })
+ .mockRejectedValueOnce(new Error('read failed'))
+ .mockResolvedValueOnce({ tasks: [{ id: 'a', status: 'pending' }] });
+
+ await startWatching();
+ watcher.emit('change', '/repo/TASKS.md');
+ watcher.emit('change', '/repo/TASKS.md');
+ await stopWatching();
+
+ expect(mocks.getUserTasks).toHaveBeenCalledTimes(3);
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('read failed'));
+ expect(mocks.emit).toHaveBeenCalledWith('watcher:error', expect.objectContaining({
+ error: 'read failed',
+ event: 'change',
+ file: '/repo/TASKS.md',
+ }));
+ });
+});