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 Morse trainer audio on mobile Safari by awaiting AudioContext resume

Adam Eivy47d7090abc19
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8cb6befd95..bf40e6b37f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,3 +3,7 @@
## Media
- **[issue-2036] Sketch & Annotation Canvas (phase 2): re-render an image guided by your annotations.** The annotate page (`/media/annotate/:mediaKey`) gained a "Re-render" action: draw over a generated image, then feed your markup back through local img2img so the marks reshape the render. A confirmation dialog names the exact local model it will run (no surprise AI calls) and lets you add an optional prompt and tune how much to change before it starts; the new render is queued and appears in Media History. Requires a local FLUX img2img runner — the action explains when one isn't available. Phase 3 (blank-canvas storyboard) remains open on #2036.
+
+## MeatSpace POST
+
+- **Morse trainer audio now works on mobile Safari.** iOS Safari starts the Web Audio context suspended and only unlocks it once `resume()` fully settles. The trainer fired `resume()` without awaiting it, so the first tones were scheduled against a still-suspended clock and never sounded on iPhone/iPad. It now awaits the resume before scheduling any tone (matching the app's other audio modules), so Copy, Head Copy, and Send-mode keying all produce sound on mobile Safari.
diff --git a/client/src/components/meatspace/post/MorseTrainer.jsx b/client/src/components/meatspace/post/MorseTrainer.jsx
index 365a2cdd18..c4f17125d9 100644
--- a/client/src/components/meatspace/post/MorseTrainer.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.jsx
@@ -215,12 +215,17 @@ function pickSendPrompt() {
function useAudioContext() {
const ctxRef = useRef(null);
- const ensureCtx = useCallback(() => {
+ const ensureCtx = useCallback(async () => {
if (!ctxRef.current) {
const Ctor = window.AudioContext || window.webkitAudioContext;
ctxRef.current = new Ctor();
}
- if (ctxRef.current.state === 'suspended') ctxRef.current.resume();
+ // Autoplay policy starts the context suspended until a user gesture — and on
+ // iOS Safari resume() is async, so we MUST await it before scheduling any
+ // oscillator. Firing resume() without awaiting (the old behavior) laid tones
+ // down against a still-suspended clock: silent on mobile Safari. Mirrors the
+ // await-resume idiom in metronome.js / scorePlayback.js / songPlayback.js.
+ if (ctxRef.current.state === 'suspended') await ctxRef.current.resume();
return ctxRef.current;
}, []);
useEffect(() => () => {
@@ -252,8 +257,12 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {
const [decoded, setDecoded] = useState('');
const [pressing, setPressing] = useState(false);
- const startTone = useCallback(() => {
- const ctx = ensureCtx();
+ const startTone = useCallback(async () => {
+ const ctx = await ensureCtx();
+ // A fast tap can release (endPress → stopTone) before the first-press-only
+ // resume await settles. Bail so we don't spin up an orphan oscillator that
+ // has no matching stop and drones on.
+ if (!pressingRef.current) return;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = 'sine';
@@ -272,8 +281,10 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {
const osc = oscRef.current;
const gain = gainRef.current;
if (!osc || !gain) return;
- const ctx = ensureCtx();
- const now = ctx.currentTime;
+ // Read the clock straight off the live oscillator's context — a tone is only
+ // playing on an already-running context, so there's nothing to resume here
+ // (and stopTone stays synchronous, which endPress/clear/cleanup rely on).
+ const now = osc.context.currentTime;
gain.gain.cancelScheduledValues(now);
gain.gain.setValueAtTime(gain.gain.value, now);
gain.gain.linearRampToValueAtTime(0, now + RAMP_SEC);
@@ -281,7 +292,7 @@ function useKeyingDecoder({ unitMs, hz, ensureCtx, enabled = false }) {
osc.onended = () => { osc.disconnect(); gain.disconnect(); };
oscRef.current = null;
gainRef.current = null;
- }, [ensureCtx]);
+ }, []);
const flushLetter = useCallback(() => {
const buf = patternRef.current;
@@ -795,7 +806,7 @@ function CopyDrill({ prefs, updatePrefs, ensureCtx, onExit, onSessionComplete, h
}
async function playPrompt(isNew) {
- const ctx = ensureCtx();
+ const ctx = await ensureCtx();
const text = isNew ? pickKochPrompt(prefs.kochLevel) : prompt;
if (isNew) {
setPrompt(text);
diff --git a/client/src/components/meatspace/post/MorseTrainer.test.jsx b/client/src/components/meatspace/post/MorseTrainer.test.jsx
index 4128d85b0e..311b98c0e7 100644
--- a/client/src/components/meatspace/post/MorseTrainer.test.jsx
+++ b/client/src/components/meatspace/post/MorseTrainer.test.jsx
@@ -22,7 +22,9 @@ import { submitTrainingEntry, getTrainingStats } from '../../../services/api';
// own) — mirrors that convention. `stop()` resolves playMorse's promise on
// the next tick, matching the real oscillator's `onended` callback shape.
class MockOscillator {
- constructor() { this.onended = null; this.frequency = { value: 0 }; }
+ // `context` mirrors the real AudioNode.context — stopTone reads currentTime
+ // off it instead of re-resolving the AudioContext.
+ constructor(context = { currentTime: 0 }) { this.onended = null; this.frequency = { value: 0 }; this.context = context; }
connect() { return this; }
start() {}
stop() { if (this.onended) setTimeout(() => this.onended(), 0); }
@@ -188,6 +190,44 @@ describe('MorseTrainer training log integration', () => {
});
});
+describe('MorseTrainer iOS audio unlock', () => {
+ // Regression for "audio doesn't work on mobile Safari": iOS starts the
+ // AudioContext suspended and resume() is async. If a tone is scheduled before
+ // resume() settles, it's laid down against a still-suspended clock and never
+ // sounds. The trainer must await resume() (like metronome.js / scorePlayback.js)
+ // so no oscillator is ever created while the context is still 'suspended'.
+ let createdWhileSuspended;
+ class SuspendedAudioContext {
+ constructor() { this.currentTime = 0; this.destination = {}; this.state = 'suspended'; }
+ // Resolve on a later microtask, mirroring the real async resume — the
+ // component must await this before touching createOscillator.
+ resume() { return Promise.resolve().then(() => { this.state = 'running'; }); }
+ createOscillator() {
+ if (this.state === 'suspended') createdWhileSuspended = true;
+ return new MockOscillator();
+ }
+ createGain() { return new MockGainNode(); }
+ close() {}
+ }
+
+ beforeEach(() => {
+ createdWhileSuspended = false;
+ submitTrainingEntry.mockClear();
+ getTrainingStats.mockClear();
+ window.AudioContext = SuspendedAudioContext;
+ });
+ afterEach(() => { delete window.AudioContext; });
+
+ it('awaits resume() before scheduling any tone (no oscillator while suspended)', async () => {
+ renderMorse({ mode: 'copy', onSelectMode: vi.fn(), onExitMode: vi.fn() });
+ fireEvent.click(await screen.findByRole('button', { name: /Start Round/i }));
+ // The round input only renders once playMorse has finished, so by here the
+ // first tone has been scheduled and played.
+ await screen.findByPlaceholderText('????');
+ expect(createdWhileSuspended).toBe(false);
+ });
+});
+
describe('MorseTrainer Tree reference view', () => {
it('renders a labeled, reachable node for all 41 characters', () => {
const { container } = renderMorse({ mode: null, onSelectMode: vi.fn() });