Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-11741]): recover Security monitor errors and bound media parsing (#11788)
[._.]/5e60f355aa4c
diff --git a/client/src/pages/Security.jsx b/client/src/pages/Security.jsxindex e51dc05f5f..34efbb6e1c 100644--- a/client/src/pages/Security.jsx+++ b/client/src/pages/Security.jsx@@ -17,6 +17,8 @@ export default function Security() {const analyserRef = useRef(null);const animationFrameRef = useRef(null);const deviceRestartTimerRef = useRef(null);+ const playbackGenerationRef = useRef(0);+ const streamingRef = useRef(false);// The monitor routes the host's microphone stream through its OWN// AudioContext to the speakers, so it can't inherit the shared lookahead@@ -29,6 +31,7 @@ export default function Security() {const { claim: claimAudioSession, release: releaseAudioSession } = useAudioSessionClaim('playback');const [streaming, setStreaming] = useState(false);+ const [streamRevision, setStreamRevision] = useState(0);const [videoEnabled, setVideoEnabled] = useState(true);const [audioEnabled, setAudioEnabled] = useState(true);const [devices, setDevices] = useState({ video: [], audio: [] });@@ -65,18 +68,37 @@ export default function Security() {// Fetch available devices from serverconst fetchDevices = useCallback(async () => {- const response = await api.get('/media/devices');- setDevices(response.data);+ const response = await api.get('/media/devices', { silent: true });+ setDevices(response);// Set default selections if not already set- if (!selectedVideo && response.data.video.length > 0) {- setSelectedVideo(response.data.video[0].id);+ if (!selectedVideo && response.video.length > 0) {+ setSelectedVideo(response.video[0].id);}- if (!selectedAudio && response.data.audio.length > 0) {- setSelectedAudio(response.data.audio[0].id);+ if (!selectedAudio && response.audio.length > 0) {+ setSelectedAudio(response.audio[0].id);}}, [selectedVideo, selectedAudio]);+ const cleanupPlayback = useCallback((audioElement = audioRef.current) => {+ playbackGenerationRef.current += 1;+ streamingRef.current = false;+ if (deviceRestartTimerRef.current) clearTimeout(deviceRestartTimerRef.current);+ deviceRestartTimerRef.current = null;+ if (videoRef.current) videoRef.current.removeAttribute('src');+ if (audioElement) {+ audioElement.pause();+ audioElement.removeAttribute('src');+ }+ audioContextRef.current?.suspend?.()?.catch(() => {});+ if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);+ animationFrameRef.current = null;+ releaseAudioSession();+ setStreaming(false);+ setAudioLevel(0);+ setAudioNeedsInteraction(false);+ }, [releaseAudioSession]);+// Set up audio level monitoring from audio element. An HTMLMediaElement can be// attached to only one MediaElementAudioSourceNode for its lifetime (Web Audio// spec) — the <audio> element here is never remounted, so the AudioContext and@@ -84,7 +106,7 @@ export default function Security() {// restart. A restart only resumes the existing context and restarts the meter// loop; the context itself is closed exclusively on unmount (see the cleanup// effect below).- const setupAudioAnalyser = useCallback(async (audioElement) => {+ const setupAudioAnalyser = useCallback(async (audioElement, generation) => {if (animationFrameRef.current) {cancelAnimationFrame(animationFrameRef.current);animationFrameRef.current = null;@@ -102,6 +124,7 @@ export default function Security() {// resume has to happen with the claim in force, so the context comes up// on the right session.audioContext = new (window.AudioContext || window.webkitAudioContext)();+ audioContextRef.current = audioContext;analyser = audioContext.createAnalyser();const source = audioContext.createMediaElementSource(audioElement);@@ -121,9 +144,15 @@ export default function Security() {// Bring the context up if it isn't running (browser autoplay policy, or// iOS's `'interrupted'` after a call/lock) — see lib/audioContext.js.await resumeAudioContext(audioContext).catch(() => {- setAudioNeedsInteraction(true);+ if (generation === playbackGenerationRef.current) setAudioNeedsInteraction(true);});+ if (generation !== playbackGenerationRef.current) {+ // A restart reuses this context; only silence it if no newer stream owns it.+ if (!streamingRef.current) audioContext.suspend?.()?.catch(() => {});+ return;+ }+// Use time-domain data for better audio level detectionconst dataArray = new Uint8Array(analyser.fftSize);@@ -148,13 +177,19 @@ export default function Security() {if (audioRef.current && audioContextRef.current) {// Resume AudioContext — the whole point of this button, so it has to cover// every non-running state, not just `'suspended'`.- await resumeAudioContext(audioContextRef.current);-- // Play audio element- await audioRef.current.play();-- setAudioNeedsInteraction(false);- setError(null);+ const generation = playbackGenerationRef.current;+ await resumeAudioContext(audioContextRef.current).then(() => {+ if (generation !== playbackGenerationRef.current || !streamingRef.current) return;+ return audioRef.current?.play();+ }).then(() => {+ if (generation !== playbackGenerationRef.current) return;+ setAudioNeedsInteraction(false);+ setError(null);+ }).catch(err => {+ if (generation !== playbackGenerationRef.current) return;+ setAudioNeedsInteraction(true);+ setError(`Failed to enable audio: ${err.message}`);+ });}}, []);@@ -164,6 +199,7 @@ export default function Security() {// stale-closure restart would tell the server to keep streaming the OLD// enabled/disabled flag for one more round-trip.const startMedia = useCallback(async (overrides = {}) => {+ cleanupPlayback();setIsLoading(true);setError(null);setAudioNeedsInteraction(false);@@ -172,16 +208,25 @@ export default function Security() {const audio = overrides.audio !== undefined ? overrides.audio : audioEnabled;// Start streaming on server- await api.post('/media/start', {- videoDeviceId: selectedVideo,- audioDeviceId: selectedAudio,+ const generation = ++playbackGenerationRef.current;+ const started = await api.post('/media/start', {+ videoDeviceId: overrides.videoDeviceId ?? selectedVideo,+ audioDeviceId: overrides.audioDeviceId ?? selectedAudio,video,audio- });-- setStreaming(true);- setIsLoading(false);- }, [videoEnabled, audioEnabled, selectedVideo, selectedAudio]);+ }, { silent: true }).then(() => true).catch(err => {+ cleanupPlayback();+ setError(`Failed to start media: ${err.message}`);+ return false;+ }).finally(() => setIsLoading(false));+ if (generation === playbackGenerationRef.current && started) {+ streamingRef.current = true;+ setStreaming(true);+ setStreamRevision(revision => revision + 1);+ } else if (started) {+ api.post('/media/stop', undefined, { silent: true }).catch(() => {});+ }+ }, [videoEnabled, audioEnabled, selectedVideo, selectedAudio, cleanupPlayback]);// Set up media sources when streaming startsuseEffect(() => {@@ -193,6 +238,7 @@ export default function Security() {// to hand it back. `active` drops both continuations once this effect run is// superseded.let active = true;+ const generation = playbackGenerationRef.current;const timestamp = Date.now();@@ -206,48 +252,34 @@ export default function Security() {audioRef.current.src = `/api/media/audio?t=${timestamp}`;audioRef.current.play().then(() => {- if (active) setupAudioAnalyser(audioRef.current).catch(() => {});+ if (active) setupAudioAnalyser(audioRef.current, generation).catch(() => {});}).catch(() => {if (!active) return;// On mobile browsers, autoplay is often blocked - show interaction promptsetAudioNeedsInteraction(true);- setupAudioAnalyser(audioRef.current).catch(() => {}); // Set up analyser anyway for when user enables+ setupAudioAnalyser(audioRef.current, generation).catch(() => {}); // Set up analyser anyway for when user enables});}- return () => { active = false; };- }, [streaming, videoEnabled, audioEnabled, setupAudioAnalyser]);+ return () => {+ active = false;+ if (audioRef.current) {+ audioRef.current.pause();+ audioRef.current.removeAttribute('src');+ }+ audioContextRef.current?.suspend?.()?.catch(() => {});+ if (animationFrameRef.current) cancelAnimationFrame(animationFrameRef.current);+ animationFrameRef.current = null;+ releaseAudioSession();+ };+ }, [streaming, streamRevision, videoEnabled, audioEnabled, setupAudioAnalyser, releaseAudioSession]);- // Stop media streamconst stopMedia = useCallback(async () => {- // Stop streaming on server- await api.post('/media/stop');-- if (videoRef.current) {- videoRef.current.src = '';- }- if (audioRef.current) {- audioRef.current.pause();- audioRef.current.src = '';- }- if (audioContextRef.current) {- // Suspend, don't close — the context and its MediaElementSourceNode are- // scoped to the <audio> element's lifetime (it can only ever be wired to- // ONE source node), so they're reused on the next start. Only the- // unmount cleanup effect below closes the context.- audioContextRef.current.suspend?.()?.catch(() => {});- }- if (animationFrameRef.current) {- cancelAnimationFrame(animationFrameRef.current);- animationFrameRef.current = null;- }- // Nothing is sounding any more, so hand the session back — holding it would- // follow the user (SPA, no reload) onto every other page and refuse the- // globally-mounted VoiceWidget's microphone.- releaseAudioSession();- setStreaming(false);- setAudioLevel(0);- }, [releaseAudioSession]);+ cleanupPlayback();+ await api.post('/media/stop', undefined, { silent: true }).catch(err => {+ setError(`Failed to stop server media: ${err.message}`);+ });+ }, [cleanupPlayback]);// Toggle videoconst toggleVideo = useCallback(() => {@@ -279,14 +311,15 @@ export default function Security() {});}, [fetchDevices]);- // Cleanup on unmountuseEffect(() => {+ // React detaches refs before passive unmount cleanup.+ const audioElement = audioRef.current;return () => {- if (streaming) {- stopMedia();- }+ const wasStreaming = streamingRef.current;+ cleanupPlayback(audioElement);+ if (wasStreaming) api.post('/media/stop', undefined, { silent: true }).catch(() => {});};- }, [streaming, stopMedia]);+ }, [cleanupPlayback]);// The AudioContext and its MediaElementSourceNode are scoped to the <audio>// element's lifetime (setupAudioAnalyser builds them once and reuses them@@ -319,17 +352,11 @@ export default function Security() {if (deviceRestartTimerRef.current) clearTimeout(deviceRestartTimerRef.current);deviceRestartTimerRef.current = setTimeout(() => {deviceRestartTimerRef.current = null;- startMedia();+ startMedia({ [`${type}DeviceId`]: deviceId });}, 100);}}, [streaming, startMedia]);- // Cancel any pending device-change restart on unmount so a deferred- // startMedia() can't fire into a component that's no longer mounted.- useEffect(() => () => {- if (deviceRestartTimerRef.current) clearTimeout(deviceRestartTimerRef.current);- }, []);-return (<div>{/* Header */}@@ -510,7 +537,7 @@ export default function Security() {)}<button- onClick={fetchDevices}+ onClick={() => fetchDevices().catch(err => setError(`Failed to fetch devices: ${err.message}`))}disabled={isLoading}className="p-3 rounded-full bg-port-card border border-port-border text-gray-400 hover:text-white hover:bg-port-border transition-colors disabled:opacity-50 disabled:cursor-not-allowed"title="Refresh devices" aria-label="Refresh devices"diff --git a/client/src/pages/Security.test.jsx b/client/src/pages/Security.test.jsxindex b24308946c..6857941964 100644--- a/client/src/pages/Security.test.jsx+++ b/client/src/pages/Security.test.jsx@@ -12,8 +12,8 @@ import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'vi.mock('../services/api', () => ({default: {- get: vi.fn(async () => ({ data: { video: [{ id: 'cam-1', name: 'Camera 1' }], audio: [{ id: 'mic-1', name: 'Mic 1' }] } })),- post: vi.fn(async () => ({ data: {} })),+ get: vi.fn(async () => ({ video: [{ id: 'cam-1', name: 'Camera 1' }], audio: [{ id: 'mic-1', name: 'Mic 1' }] })),+ post: vi.fn(async () => ({})),},}));@@ -219,6 +219,99 @@ describe('Security monitor toggle posts the new flag value', () => {await waitFor(() => expect(api.post).toHaveBeenCalledWith('/media/start', expect.objectContaining({audio: false,- })));+ }), { silent: true }));});++ it('shows unwrapped devices on mount and refresh', async () => {+ const api = (await import('../services/api')).default;+ render(<Security />);+ await act(async () => {});+ fireEvent.click(screen.getByRole('button', { name: /Settings/i }));+ expect(screen.getByRole('option', { name: 'Camera 1' })).toBeTruthy();+ api.get.mockResolvedValueOnce({ video: [{ id: '2', name: 'Example replacement camera' }], audio: [] });+ fireEvent.click(screen.getByRole('button', { name: /Refresh devices/i }));+ expect(await screen.findByRole('option', { name: 'Example replacement camera' })).toBeTruthy();+ });++ it('allows another start after a failed start request', async () => {+ const api = (await import('../services/api')).default;+ api.post.mockRejectedValueOnce(new Error('Example start refusal'));+ render(<Security />);+ await act(async () => {});+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));+ expect(await screen.findByText(/Failed to start media: Example start refusal/)).toBeTruthy();+ expect(screen.getByRole('button', { name: /Start Media/i }).disabled).toBe(false);+ expect(screen.getByRole('button', { name: /Refresh devices/i }).disabled).toBe(false);+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));+ await waitFor(() => expect(sessionType()).toBe('playback'));+ });++ it('cleans up local playback when the server stop fails and preserves the microphone preference', async () => {+ const api = (await import('../services/api')).default;+ const { container } = await startMonitor();+ api.post.mockRejectedValueOnce(new Error('Example stop failure'));+ fireEvent.click(screen.getByRole('button', { name: /Stop Media/i }));+ expect(await screen.findByText(/Failed to stop server media: Example stop failure/)).toBeTruthy();+ expect(sessionType()).toBe('auto');+ expect(container.querySelector('audio').hasAttribute('src')).toBe(false);+ expect(window.HTMLMediaElement.prototype.pause).toHaveBeenCalled();+ expect(cancelAnimationFrame).toHaveBeenCalled();+ expect(screen.getByRole('button', { name: /Mute microphone/i })).toBeTruthy();+ expect(screen.getByRole('button', { name: /Start Media/i }).disabled).toBe(false);+ });++ it('reports a rejected interaction playback and keeps the enable button usable', async () => {+ window.HTMLMediaElement.prototype.play = vi.fn().mockRejectedValue(new Error('Example playback block'));+ await startMonitor();+ const enable = screen.getByRole('button', { name: /Enable Audio/i });+ fireEvent.click(enable);+ expect(await screen.findByText(/Failed to enable audio: Example playback block/)).toBeTruthy();+ expect(screen.getByRole('button', { name: /Enable Audio/i }).disabled).toBe(false);+ });+++ it('does not suspend a restarted monitor when the previous resume settles late', async () => {+ let resolveOldResume;+ let context;+ let resumes = 0;+ let suspends = 0;+ window.AudioContext = class extends FakeAudioContext {+ constructor() { super(); this.state = 'suspended'; context = this; }+ resume() {+ resumes += 1;+ if (resumes === 1) return new Promise(resolve => { resolveOldResume = resolve; });+ return super.resume();+ }+ suspend() { suspends += 1; return super.suspend(); }+ };+ await startMonitor();+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Stop Media/i })); });+ fireEvent.click(screen.getByRole('button', { name: /Start Media/i }));+ await waitFor(() => expect(context.state).toBe('running'));+ const suspendsBeforeOldResume = suspends;+ await act(async () => { resolveOldResume(); });+ expect(suspends).toBe(suspendsBeforeOldResume);+ expect(context.state).toBe('running');+ expect(sessionType()).toBe('playback');+ });+++ it('does not play after stop when interaction resume settles late', async () => {+ let context;+ window.AudioContext = class extends FakeAudioContext {+ constructor() { super(); context = this; }+ };+ window.HTMLMediaElement.prototype.play = vi.fn().mockRejectedValue(new Error('Example autoplay block'));+ await startMonitor();+ let resolveResume;+ context.state = 'suspended';+ context.resume = () => new Promise(resolve => { resolveResume = resolve; });+ fireEvent.click(screen.getByRole('button', { name: /Enable Audio/i }));+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: /Stop Media/i })); });+ const playsBeforeResume = window.HTMLMediaElement.prototype.play.mock.calls.length;+ await act(async () => { resolveResume(); });+ expect(window.HTMLMediaElement.prototype.play).toHaveBeenCalledTimes(playsBeforeResume);+ expect(sessionType()).toBe('auto');+ });+});diff --git a/server/routes/media.js b/server/routes/media.jsindex ee16f18b73..53b0ff609d 100644--- a/server/routes/media.js+++ b/server/routes/media.js@@ -5,6 +5,9 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';const router = express.Router();+const MAX_JPEG_FRAME_BYTES = 8 * 1024 * 1024;+const JPEG_START = Buffer.from([0xFF, 0xD8]);+const JPEG_END = Buffer.from([0xFF, 0xD9]);// Validation schemasconst startMediaSchema = z.object({@@ -78,19 +81,33 @@ router.get('/video', (req, res) => {const onData = (chunk) => {frameBuffer = Buffer.concat([frameBuffer, chunk]);- // Look for JPEG markers- let start = frameBuffer.indexOf(Buffer.from([0xFF, 0xD8])); // JPEG start- let end = frameBuffer.indexOf(Buffer.from([0xFF, 0xD9]), start + 2); // JPEG end-- while (start !== -1 && end !== -1) {- const frame = frameBuffer.slice(start, end + 2);- res.write(`--frame\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);- res.write(frame);- res.write('\r\n');-- frameBuffer = frameBuffer.slice(end + 2);- start = frameBuffer.indexOf(Buffer.from([0xFF, 0xD8]));- end = frameBuffer.indexOf(Buffer.from([0xFF, 0xD9]), start + 2);+ while (frameBuffer.length) {+ const start = frameBuffer.indexOf(JPEG_START);+ if (start === -1) {+ // A marker can straddle chunks; retain only its possible first byte.+ frameBuffer = frameBuffer.at(-1) === 0xFF ? Buffer.from([0xFF]) : Buffer.alloc(0);+ break;+ }+ frameBuffer = frameBuffer.subarray(start);+ const end = frameBuffer.indexOf(JPEG_END, 2);+ const nextStart = frameBuffer.indexOf(JPEG_START, 2);+ if (nextStart !== -1 && (end === -1 || nextStart < end)) {+ frameBuffer = frameBuffer.subarray(nextStart);+ continue;+ }+ if (end === -1) {+ if (frameBuffer.length > MAX_JPEG_FRAME_BYTES) {+ frameBuffer = frameBuffer.at(-1) === 0xFF ? Buffer.from([0xFF]) : Buffer.alloc(0);+ }+ break;+ }+ if (end + 2 <= MAX_JPEG_FRAME_BYTES) {+ const frame = frameBuffer.subarray(0, end + 2);+ res.write(`--frame\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);+ res.write(frame);+ res.write('\r\n');+ }+ frameBuffer = frameBuffer.subarray(end + 2);}};diff --git a/server/routes/media.test.js b/server/routes/media.test.jsindex 2a916cb041..6614cf08b6 100644--- a/server/routes/media.test.js+++ b/server/routes/media.test.js@@ -68,3 +68,31 @@ describe('media stream client cleanup', () => {expect(source.listenerCount('data')).toBe(0);});});++describe('MJPEG framing recovery', () => {+ it('preserves split markers and recovers after garbage and an oversized incomplete frame', () => {+ const source = new PassThrough();+ const res = responseStream();+ const output = [];+ res.on('data', chunk => output.push(chunk));+ mocks.getVideoStream.mockReturnValue(source);+ routeHandler('/video')(new EventEmitter(), res);++ source.write(Buffer.alloc(9 * 1024 * 1024, 0x61));+ source.write(Buffer.from([0xFF]));+ source.write(Buffer.from([0xD8, 1, 0xFF]));+ source.write(Buffer.from([0xD9]));+ source.write(Buffer.from([0xFF, 0xD8]));+ source.write(Buffer.alloc(9 * 1024 * 1024, 0x62));+ // A new start marker supersedes a malformed incomplete frame.+ source.write(Buffer.from([0xFF, 0xD8, 2, 0xFF, 0xD8, 3, 0xFF]));+ source.write(Buffer.from([0xD9]));+ source.end();++ const payload = Buffer.concat(output);+ expect(payload.toString('latin1').match(/Content-Length: 5/g)).toHaveLength(2);+ expect(payload.includes(Buffer.from([0xFF, 0xD8, 1, 0xFF, 0xD9]))).toBe(true);+ expect(payload.includes(Buffer.from([0xFF, 0xD8, 3, 0xFF, 0xD9]))).toBe(true);+ expect(payload.length).toBeLessThan(200);+ });+});diff --git a/server/services/mediaService.js b/server/services/mediaService.jsindex d19c700919..02646017c5 100644--- a/server/services/mediaService.js+++ b/server/services/mediaService.js@@ -7,6 +7,8 @@ let audioProcess = null;let videoStream = null;let audioStream = null;let devices = { video: [], audio: [] };+const DEVICE_PROBE_TIMEOUT_MS = 10_000;+const MAX_DEVICE_OUTPUT_BYTES = 1024 * 1024;async function listDevices() {return new Promise((resolve, reject) => {@@ -14,15 +16,34 @@ async function listDevices() {'-f', 'avfoundation','-list_devices', 'true','-i', ''- ], safeChildProcessOptions());+ ], { ...safeChildProcessOptions(), stdio: ['ignore', 'ignore', 'pipe'] });let output = '';-- ffmpeg.stderr.on('data', (data) => {+ let settled = false;+ const finish = (err) => {+ if (settled) return false;+ settled = true;+ clearTimeout(timer);+ ffmpeg.stderr.off('data', onData);+ if (err) reject(err);+ return true;+ };+ const onData = (data) => {+ if (Buffer.byteLength(output) + data.length > MAX_DEVICE_OUTPUT_BYTES) {+ finish(new Error('Media device probe output exceeded limit'));+ ffmpeg.kill('SIGKILL');+ return;+ }output += data.toString();- });-- ffmpeg.on('close', () => {+ };+ const timer = setTimeout(() => {+ finish(new Error('Media device probe timed out'));+ ffmpeg.kill('SIGKILL');+ }, DEVICE_PROBE_TIMEOUT_MS);+ ffmpeg.stderr.on('data', onData);++ ffmpeg.once('close', () => {+ if (!finish()) return;const videoDevices = [];const audioDevices = [];@@ -57,7 +78,7 @@ async function listDevices() {resolve(devices);});- ffmpeg.on('error', reject);+ ffmpeg.once('error', err => finish(err));});}@@ -93,6 +114,9 @@ function startVideoStream(deviceId = '0') {child.on('error', (err) => {console.error(`❌ Video stream error: ${err.message}`);+ stream.end();+ if (videoProcess === child) videoProcess = null;+ if (videoStream === stream) videoStream = null;});child.on('close', () => {@@ -137,6 +161,9 @@ function startAudioStream(deviceId = '0') {child.on('error', (err) => {console.error(`❌ Audio stream error: ${err.message}`);+ stream.end();+ if (audioProcess === child) audioProcess = null;+ if (audioStream === stream) audioStream = null;});child.on('close', () => {@@ -151,6 +178,7 @@ function startAudioStream(deviceId = '0') {function stopVideoStream() {if (videoProcess) {videoProcess.kill('SIGTERM');+ videoStream?.end();videoProcess = null;videoStream = null;}@@ -159,6 +187,7 @@ function stopVideoStream() {function stopAudioStream() {if (audioProcess) {audioProcess.kill('SIGTERM');+ audioStream?.end();audioProcess = null;audioStream = null;}diff --git a/server/services/mediaService.test.js b/server/services/mediaService.test.jsindex 92fc06a0fe..bbdffbca1e 100644--- a/server/services/mediaService.test.js+++ b/server/services/mediaService.test.js@@ -25,6 +25,7 @@ beforeEach(() => {});afterEach(() => {+ vi.useRealTimers();mediaService.stopAll();vi.restoreAllMocks();});@@ -66,3 +67,32 @@ describe('mediaService stream ownership', () => {expect(mediaService.isAudioStreaming()).toBe(false);});});++describe('media device probe bounds', () => {+ it('kills a hung probe and rejects without retaining its output listener', async () => {+ vi.useFakeTimers();+ const proc = fakeProcess();+ spawn.mockReturnValue(proc);+ const result = expect(mediaService.listDevices()).rejects.toThrow('timed out');+ await vi.advanceTimersByTimeAsync(10_000);+ await result;+ expect(proc.kill).toHaveBeenCalledWith('SIGKILL');+ expect(proc.stderr.listenerCount('data')).toBe(0);+ proc.emit('close', 1);+ vi.useRealTimers();+ });++ it('rejects oversized probe output and still parses the next normal probe', async () => {+ const oversized = fakeProcess();+ const normal = fakeProcess();+ spawn.mockReturnValueOnce(oversized).mockReturnValueOnce(normal);+ const failure = expect(mediaService.listDevices()).rejects.toThrow('exceeded limit');+ oversized.stderr.emit('data', Buffer.alloc(1024 * 1024 + 1));+ await failure;+ expect(oversized.kill).toHaveBeenCalledWith('SIGKILL');+ const devices = mediaService.listDevices();+ normal.stderr.emit('data', '[AVFoundation] AVFoundation video devices:\n[AVFoundation] [0] Example Camera\n[AVFoundation] AVFoundation audio devices:\n[AVFoundation] [1] Example Microphone\n');+ normal.emit('close', 1);+ await expect(devices).resolves.toEqual({ video: [{ id: '0', name: 'Example Camera' }], audio: [{ id: '1', name: 'Example Microphone' }] });+ });+});