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: release memo microphones after pending starts (#8094)

[._.]/ Adam Eivy35def96bf205
diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsx
index a51c47600e..fed24ec8cb 100644
--- a/client/src/components/songs/SongRecordings.jsx
+++ b/client/src/components/songs/SongRecordings.jsx
@@ -16,7 +16,7 @@
import { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { Mic, Square, Play, Trash2, Volume2, VolumeX, Loader2, Target } from 'lucide-react';
import toast from '../ui/Toast';
-import { startMemoRecording } from '../../lib/audioRecorder';
+import useMemoRecorder from '../../hooks/useMemoRecorder';
import { createLayeredPlayer } from '../../lib/songPlayback';
import { uploadFile, getUploadUrl } from '../../services/api';
import { formatDurationMs } from '../../utils/formatters';
@@ -39,14 +39,12 @@ let tempSeq = 0;
const tempRecordingId = () => `rec-new-${tempSeq++}`;
export default function SongRecordings({ recordings = [], layers = [], onChange, tempo = null, score = '' }) {
- const [recording, setRecording] = useState(false);
+ const { recording, starting, start: startMemo, stop: stopMemo, stream: liveStream } = useMemoRecorder();
const [saving, setSaving] = useState(false);
const [playing, setPlaying] = useState(false);
const [targetLayerId, setTargetLayerId] = useState('');
// Live mic stream while recording — passed to the tuner so it taps the SAME
// mic (no second getUserMedia). Null whenever a take isn't in flight.
- const [liveStream, setLiveStream] = useState(null);
- const handleRef = useRef(null); // active MediaRecorder handle
const playerRef = useRef(null); // active layered player
// Live color-match grading is owned HERE (not inside <ColorMatch>) so the
@@ -87,11 +85,9 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
// live take is grading (the live run owns the staff then).
const [reviewId, setReviewId] = useState(null);
- // Tear down any live player/recorder on unmount so a navigation-away can't
- // leave the mic open or audio playing into the void.
+ // Tear down the layered player on unmount. The recorder hook owns the mic.
useEffect(() => () => {
if (playerRef.current) playerRef.current.stop();
- if (handleRef.current) handleRef.current.cancel();
}, []);
const layerLabel = useCallback((layerId) => {
@@ -103,20 +99,12 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
setReviewId(null); // a fresh take takes over the staff from any saved-take review
armedThisTakeRef.current = false; // until the auto-arm effect fires for THIS take
if (playerRef.current) { playerRef.current.stop(); setPlaying(false); }
- const handle = await startMemoRecording().catch((err) => {
+ await startMemo().catch((err) => {
toast.error(err?.message || 'Microphone access denied');
- return null;
});
- if (!handle) return;
- handleRef.current = handle;
- setLiveStream(handle.stream || null); // feed the tuner the recording mic
- setRecording(true);
- }, []);
+ }, [startMemo]);
const stopRecording = useCallback(async () => {
- const handle = handleRef.current;
- if (!handle) return;
- handleRef.current = null;
// Stop grading FIRST (while the analyser graph is still alive) to harvest the
// finished take's pitch trace + accuracy summary, THEN drop the stream. Only
// trust the harvest when grading armed for THIS take — otherwise stopMatch()
@@ -126,10 +114,10 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
const armed = armedThisTakeRef.current;
armedThisTakeRef.current = false;
const analysis = armed ? stopMatch() : null;
- setLiveStream(null); // stream is being torn down with the take
- setRecording(false);
+ const pendingTake = stopMemo(); // stream is torn down with the take
+ if (!pendingTake) return;
setSaving(true);
- const take = await handle.stop().catch((err) => {
+ const take = await pendingTake.catch((err) => {
toast.error(err?.message || 'Recording failed');
return null;
});
@@ -166,7 +154,7 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
onChange([...recordings, entry]);
toast.success('Take recorded — Save the song to keep it');
- }, [recordings, targetLayerId, layerLabel, onChange, stopMatch]);
+ }, [recordings, targetLayerId, layerLabel, onChange, stopMatch, stopMemo]);
const removeRecording = useCallback((id) => {
setReviewId((cur) => (cur === id ? null : cur));
@@ -248,9 +236,9 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
<Square size={14} /> Stop & save
</button>
) : (
- <button type="button" onClick={startRecording} disabled={saving} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50">
- {saving ? <Loader2 size={14} className="animate-spin" /> : <Mic size={14} />}
- {saving ? 'Saving…' : 'Record take'}
+ <button type="button" onClick={startRecording} disabled={saving || starting} className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50">
+ {saving || starting ? <Loader2 size={14} className="animate-spin" /> : <Mic size={14} />}
+ {saving ? 'Saving…' : starting ? 'Opening mic…' : 'Record take'}
</button>
)}
</div>
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 2701204cc4..a169075044 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -91,6 +91,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
| `useCharacterAugmentation` | The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns `preview`/`accepted`/`proposing`/`applying` and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an `onApplied`. | A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
+| `useMemoRecorder` | Owns one memo recorder through permission prompts, stop/cancel, and unmount; exposes `{ recording, starting, start, stop, cancel, stream }`. | Catalog voice memos and song takes. |
| `usePortosRestartWatch` | Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on `portos:update:complete`, or on a socket disconnect confirmed unreachable, then polls `/api/system/health` for a version change, a down→up dip, or an uptime reset. `update.sh` pm2-deletes the server mid-run, so there is no completion event to await. | Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. `useAppOperation` already wires it, so App Management surfaces read `restarting` from there instead. |
| `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. |
| `usePreviousSync` | Same shape, but snapshot updated *during* render. | The prior value gates an in-render `setState` (React's "adjusting state on prop change" pattern); the during-render update avoids an extra discard/rerun cycle. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 3868c3e93a..2d7b8f5192 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -68,6 +68,7 @@ export { default as useBeeperRealtime } from './useBeeperRealtime.js';
export { default as useMoltworldWs } from './useMoltworldWs.js';
export { default as useCharacterAugmentation } from './useCharacterAugmentation.js';
export { default as useMounted } from './useMounted.js';
+export { default as useMemoRecorder } from './useMemoRecorder.js';
export { default as usePendingListRows } from './usePendingListRows.js';
export { default as usePopoverPosition } from './usePopoverPosition.js';
export { default as useAgyModels } from './useAgyModels.js';
diff --git a/client/src/hooks/useMemoRecorder.js b/client/src/hooks/useMemoRecorder.js
new file mode 100644
index 0000000000..85dcc7d559
--- /dev/null
+++ b/client/src/hooks/useMemoRecorder.js
@@ -0,0 +1,71 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { startMemoRecording } from '../lib/audioRecorder.js';
+import useMounted from './useMounted.js';
+
+/** Owns a memo recorder across permission prompts, repeated starts, and unmount. */
+export default function useMemoRecorder() {
+ const mountedRef = useMounted();
+ const handleRef = useRef(null);
+ const startingRef = useRef(false);
+ const generationRef = useRef(0);
+ const [starting, setStarting] = useState(false);
+ const [recording, setRecording] = useState(false);
+ const [stream, setStream] = useState(null);
+
+ const cancel = useCallback(() => {
+ generationRef.current += 1;
+ startingRef.current = false;
+ const handle = handleRef.current;
+ handleRef.current = null;
+ handle?.cancel();
+ if (mountedRef.current) {
+ setStarting(false);
+ setRecording(false);
+ setStream(null);
+ }
+ }, [mountedRef]);
+
+ useEffect(() => () => { cancel(); }, [cancel]);
+
+ const start = useCallback(async () => {
+ if (!mountedRef.current || startingRef.current || handleRef.current) return null;
+ startingRef.current = true;
+ const generation = ++generationRef.current;
+ setStarting(true);
+ let handle;
+ try {
+ handle = await startMemoRecording();
+ } catch (error) {
+ if (generation === generationRef.current && mountedRef.current) {
+ startingRef.current = false;
+ setStarting(false);
+ throw error;
+ }
+ return null;
+ }
+ if (generation !== generationRef.current || !mountedRef.current) {
+ handle.cancel();
+ return null;
+ }
+ startingRef.current = false;
+ handleRef.current = handle;
+ setStarting(false);
+ setRecording(true);
+ setStream(handle.stream || null);
+ return handle;
+ }, [mountedRef]);
+
+ const stop = useCallback(() => {
+ const handle = handleRef.current;
+ if (!handle) return null;
+ handleRef.current = null;
+ generationRef.current += 1;
+ if (mountedRef.current) {
+ setRecording(false);
+ setStream(null);
+ }
+ return handle.stop();
+ }, [mountedRef]);
+
+ return { recording, starting, start, stop, cancel, stream };
+}
diff --git a/client/src/hooks/useMemoRecorder.test.js b/client/src/hooks/useMemoRecorder.test.js
new file mode 100644
index 0000000000..d8bbf8bff2
--- /dev/null
+++ b/client/src/hooks/useMemoRecorder.test.js
@@ -0,0 +1,63 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, renderHook } from '@testing-library/react';
+import { acquireAudioSession } from '../lib/audioContext.js';
+import useMemoRecorder from './useMemoRecorder.js';
+
+const { startMemoRecording } = vi.hoisted(() => ({ startMemoRecording: vi.fn() }));
+vi.mock('../lib/audioRecorder.js', () => ({ startMemoRecording }));
+
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+};
+
+describe('useMemoRecorder', () => {
+ beforeEach(() => {
+ startMemoRecording.mockReset();
+ navigator.audioSession = { type: 'auto' };
+ });
+
+ afterEach(() => { delete navigator.audioSession; });
+
+ it('cancels a recorder that arrives after unmount', async () => {
+ const pending = deferred();
+ const handle = { stream: {}, cancel: vi.fn() };
+ startMemoRecording.mockReturnValue(pending.promise);
+ const { result, unmount } = renderHook(() => useMemoRecorder());
+
+ let startPromise;
+ act(() => { startPromise = result.current.start(); });
+ unmount();
+ await act(async () => { pending.resolve(handle); await startPromise; });
+
+ expect(handle.cancel).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens once across repeated starts and releases its audio session after stop', async () => {
+ const pending = deferred();
+ const release = acquireAudioSession('play-and-record');
+ const handle = {
+ stream: {},
+ cancel: vi.fn(release),
+ stop: vi.fn(async () => { release(); return { audioBase64: 'example' }; }),
+ };
+ startMemoRecording.mockReturnValue(pending.promise);
+ const { result } = renderHook(() => useMemoRecorder());
+
+ let first;
+ act(() => {
+ first = result.current.start();
+ result.current.start();
+ });
+ expect(result.current.starting).toBe(true);
+ expect(startMemoRecording).toHaveBeenCalledTimes(1);
+ await act(async () => { pending.resolve(handle); await first; });
+ expect(result.current.recording).toBe(true);
+ expect(navigator.audioSession.type).toBe('play-and-record');
+
+ await act(async () => { await result.current.stop(); });
+ expect(handle.stop).toHaveBeenCalledTimes(1);
+ expect(navigator.audioSession.type).toBe('auto');
+ });
+});
diff --git a/client/src/pages/CatalogIngest.jsx b/client/src/pages/CatalogIngest.jsx
index e280fc2c5c..53e6810073 100644
--- a/client/src/pages/CatalogIngest.jsx
+++ b/client/src/pages/CatalogIngest.jsx
@@ -15,7 +15,7 @@ import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
import Modal from '../components/ui/Modal';
import socket from '../services/socket';
-import { startMemoRecording } from '../lib/audioRecorder';
+import useMemoRecorder from '../hooks/useMemoRecorder';
import { getRelationKind } from '../lib/catalogTypes';
import {
createCatalogScrap,
@@ -120,8 +120,7 @@ export default function CatalogIngest() {
// immediately on select, so it has no persistent mode.
const [sourceMode, setSourceMode] = useState('paste'); // 'paste' | 'url'
const [url, setUrl] = useState('');
- const [recording, setRecording] = useState(false);
- const recorderRef = useRef(null);
+ const { recording, starting, start: startMemo, stop: stopMemo, cancel: cancelMemo } = useMemoRecorder();
// "Catalogue into" — the universe every committed ingredient binds to
// (#7615). Populated on mount; defaulted per-ingest in enterReviewFromResult.
// Mirrored into a ref because the brain-bridge handoff runs from the
@@ -147,10 +146,6 @@ export default function CatalogIngest() {
// catalog stage pin.
const brainRouteRef = useRef(null);
- // Stop the mic if the page unmounts mid-recording (navigating away), so the
- // MediaRecorder stream isn't left live with no UI to stop it.
- useEffect(() => () => { recorderRef.current?.cancel?.(); }, []);
-
// Load the "Catalogue into" options once. Best-effort — an empty list just
// leaves Unassigned as the only choice.
useEffect(() => {
@@ -177,17 +172,12 @@ export default function CatalogIngest() {
return reality?.id || UNASSIGNED_UNIVERSE;
};
- // Any transition OUT of the paste phase that isn't the voice flow's own
- // stop-and-transcribe (which nulls recorderRef before switching) must release
- // the mic — otherwise starting File/URL/Paste ingest mid-recording hides the
+ // Any transition OUT of the paste phase must release the mic — otherwise
+ // starting File/URL/Paste ingest mid-recording hides the
// stop control while the stream stays live.
useEffect(() => {
- if (phase !== 'paste' && recorderRef.current) {
- recorderRef.current.cancel?.();
- recorderRef.current = null;
- setRecording(false);
- }
- }, [phase]);
+ if (phase !== 'paste') cancelMemo();
+ }, [phase, cancelMemo]);
// Track active runId so a stale frame from an earlier scrap can't mutate the
// current stage list (server fans these to all sockets — single-user trust
@@ -226,9 +216,7 @@ export default function CatalogIngest() {
creativeNoteIdsRef.current = [];
creativeNoteScrapIdRef.current = null;
brainRouteRef.current = null;
- recorderRef.current?.cancel?.();
- recorderRef.current = null;
- setRecording(false);
+ cancelMemo();
setPhase('paste');
setScrapId(null);
setStages(INITIAL_STAGES);
@@ -396,21 +384,15 @@ export default function CatalogIngest() {
};
const startRecording = async () => {
- const handle = await startMemoRecording().catch((err) => {
+ await startMemo().catch((err) => {
toast.error(err?.message || 'Microphone unavailable');
- return null;
});
- if (!handle) return;
- recorderRef.current = handle;
- setRecording(true);
};
const stopRecordingAndIngest = async () => {
- const handle = recorderRef.current;
- if (!handle) return;
- recorderRef.current = null;
- setRecording(false);
- const clip = await handle.stop().catch((err) => {
+ const pendingClip = stopMemo();
+ if (!pendingClip) return;
+ const clip = await pendingClip.catch((err) => {
toast.error(err?.message || 'Recording failed');
return null;
});
@@ -734,7 +716,7 @@ export default function CatalogIngest() {
<FileText size={14} aria-hidden="true" /> File
</FilePickerButton>
{!recording ? (
- <button type="button" onClick={startRecording} disabled={submitting}
+ <button type="button" onClick={startRecording} disabled={submitting || starting}
className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm border border-port-border text-gray-300 hover:text-white disabled:opacity-50">
<Mic size={14} aria-hidden="true" /> Voice Memo
</button>
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index f89389daf4..4b079c03cc 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -5,7 +5,7 @@
* pipeline series / issues / writers-room). Full-width page; owns its scroll.
*/
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams, Link } from 'react-router';
import { Sparkles, Save, Trash2, ArrowLeft, Loader2, ExternalLink, Plus, X, History, RotateCcw, Image as ImageIcon, Star, ChevronDown, Upload, Mic, Square } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -31,7 +31,8 @@ import {
uploadCatalogIngredientMediaFile,
recordCatalogIngredientVoiceMemo,
} from '../services/apiCatalog';
-import { startMemoRecording, arrayBufferToBase64 } from '../lib/audioRecorder';
+import { arrayBufferToBase64 } from '../lib/audioRecorder';
+import useMemoRecorder from '../hooks/useMemoRecorder';
import { useGalleryPage } from '../hooks/useGalleryPage';
import { generateImage } from '../services/apiSystem';
import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';
@@ -1202,16 +1203,12 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
const [pickerOpen, setPickerOpen] = useState(false);
const [dragOver, setDragOver] = useState(false);
const [busy, setBusy] = useState(false); // upload or transcription in flight
- const [recording, setRecording] = useState(false);
+ const { recording, starting, start: startMemo, stop: stopMemo } = useMemoRecorder();
const [armedDetach, setArmedDetach] = useState(null);
- const recorderRef = useRef(null);
const list = Array.isArray(media) ? media : [];
const portrait = list.find((m) => m.kind === 'portrait');
const others = list.filter((m) => m.kind !== 'portrait');
- // Release the mic if the panel unmounts mid-recording (navigating away).
- useEffect(() => () => { recorderRef.current?.cancel?.(); }, []);
-
const doUpload = async (file) => {
if (!file || busy) return;
setBusy(true);
@@ -1236,21 +1233,15 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
};
const startRecording = async () => {
- const handle = await startMemoRecording().catch((err) => {
+ await startMemo().catch((err) => {
toast.error(err?.message || 'Microphone unavailable');
- return null;
});
- if (!handle) return;
- recorderRef.current = handle;
- setRecording(true);
};
const stopRecording = async () => {
- const handle = recorderRef.current;
- if (!handle) return;
- recorderRef.current = null;
- setRecording(false);
- const clip = await handle.stop().catch((err) => { toast.error(err?.message || 'Recording failed'); return null; });
+ const pendingClip = stopMemo();
+ if (!pendingClip) return;
+ const clip = await pendingClip.catch((err) => { toast.error(err?.message || 'Recording failed'); return null; });
if (!clip?.audioBase64) return;
if (clip.peak !== undefined && clip.peak < 0.01) {
toast.error('That memo was silent — check your microphone and try again.');
@@ -1278,7 +1269,7 @@ function MediaPanel({ media, missingMedia, onAttach, onSetPortrait, onDetach, on
<Upload size={12} aria-hidden="true" /> Upload file
</FilePickerButton>
{!recording ? (
- <button type="button" onClick={startRecording} disabled={busy}
+ <button type="button" onClick={startRecording} disabled={busy || starting}
className="inline-flex items-center gap-1 text-xs px-2 py-1 rounded border border-port-border text-gray-300 hover:text-white hover:border-port-accent disabled:opacity-40">
<Mic size={12} aria-hidden="true" /> Record memo
</button>