🌊 Волна 12: frontend утечки + достижения (7 багов)

Утечки ObjectURL:
- URL_LEAK_FLASHCARDS: audioUrlRef + revoke (FlashcardsPage.tsx)
- URL_LEAK_PRONUNCIATION: audioUrlRef + revoke (PronunciationPage.tsx)
- URL_LEAK_TYPING: audioUrlRef + revoke (TypingPage.tsx)
- URL_LEAK_TESTVIEW: audioUrlRef + revoke (TestViewPage.tsx)

UI:
- ALERT_IN_TELEGRAM_MINIAPP: toast вместо alert() в TestViewPage (3 места)

Достижения:
- achievements_queue_overwrite_loses_new_items: функциональный update очереди (useAchievements.ts)
- achievements_reset_does_not_clear_timeout: clearTimeout в reset (useAchievements.ts)

Аудит v2: Issue #4, frontend 7/14 задач
This commit is contained in:
2026-09-24 12:44:32 +03:00
parent f041d46418
commit f878411dce
5 changed files with 187 additions and 30 deletions
+29 -22
View File
@@ -17,29 +17,31 @@ export const useAchievements = () => {
setAchievementQueue(prev => [...prev, ach]); setAchievementQueue(prev => [...prev, ach]);
}, []); }, []);
const processQueue = useCallback(() => { // 🔧 ФИКС (24.09.2026): achievements_queue_overwrite_loses_new_items +
setAchievementQueue(prev => { // achievements_reset_does_not_clear_timeout —
if (prev.length === 0) return prev; // 1) раньше в таймауте очередь перезаписывалась захваченным `rest`,
const [next, ...rest] = prev; // поэтому если во время показа приходило новое — оно терялось.
setActiveAchievement(next); // 2) resetAchievements не чистил таймаут, и через 3 сек очередь «воскресала».
// Теперь: active ставится из очереди, таймаут только снимает active —
if (achievementTimeoutRef.current) clearTimeout(achievementTimeoutRef.current); // очередь обновляется функционально, ничего не теряется.
achievementTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) {
setActiveAchievement(null);
setAchievementQueue(rest);
}
}, 3000);
return rest;
});
}, []);
useEffect(() => { useEffect(() => {
if (activeAchievement === null && achievementQueue.length > 0) { if (activeAchievement !== null) return;
processQueue(); if (achievementQueue.length === 0) return;
}
}, [activeAchievement, achievementQueue, processQueue]); // Берём первый из очереди как active
const next = achievementQueue[0];
setActiveAchievement(next);
// Убираем его из очереди
setAchievementQueue(prev => prev.filter(a => a.id !== next.id || a.icon !== next.icon || a.name !== next.name));
// Таймаут: через 3 сек снимаем active
if (achievementTimeoutRef.current) clearTimeout(achievementTimeoutRef.current);
achievementTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) {
setActiveAchievement(null);
}
}, 3000);
}, [activeAchievement, achievementQueue]);
useEffect(() => { useEffect(() => {
isMountedRef.current = true; isMountedRef.current = true;
@@ -49,7 +51,12 @@ export const useAchievements = () => {
}; };
}, []); }, []);
// 🔧 ФИКС (24.09.2026): resetAchievements теперь чистит таймаут.
const resetAchievements = useCallback(() => { const resetAchievements = useCallback(() => {
if (achievementTimeoutRef.current) {
clearTimeout(achievementTimeoutRef.current);
achievementTimeoutRef.current = null;
}
setAchievementQueue([]); setAchievementQueue([]);
setActiveAchievement(null); setActiveAchievement(null);
}, []); }, []);
+24
View File
@@ -30,6 +30,8 @@ const FlashcardsPage: React.FC = () => {
const { activeAchievement, showAchievement } = useAchievements(); const { activeAchievement, showAchievement } = useAchievements();
const isMountedRef = useRef(true); const isMountedRef = useRef(true);
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const brandColor = '#2ECC71'; const brandColor = '#2ECC71';
const textColor = '#1A1A2E'; const textColor = '#1A1A2E';
@@ -82,6 +84,12 @@ const FlashcardsPage: React.FC = () => {
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — освобождаем предыдущий URL
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
@@ -91,15 +99,26 @@ const FlashcardsPage: React.FC = () => {
try { try {
const audioBlob = await getTTS(word, 'male'); const audioBlob = await getTTS(word, 'male');
const audioUrl = URL.createObjectURL(audioBlob); const audioUrl = URL.createObjectURL(audioBlob);
audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke
const audio = new Audio(audioUrl); const audio = new Audio(audioUrl);
audioRef.current = audio; audioRef.current = audio;
audio.onended = () => { audio.onended = () => {
if (isMountedRef.current) setIsPlayingLetter(false); if (isMountedRef.current) setIsPlayingLetter(false);
// 🔧 ФИКС (24.09.2026): освобождаем URL после воспроизведения
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
}; };
audio.onerror = () => { audio.onerror = () => {
// 🔧 Освобождаем URL перед fallback
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
playWebSpeech(word); playWebSpeech(word);
}; };
@@ -153,6 +172,11 @@ const FlashcardsPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — освобождаем URL при unmount
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
+24
View File
@@ -29,6 +29,8 @@ const PronunciationPage: React.FC = () => {
const [isPlaying, setIsPlaying] = useState(false); const [isPlaying, setIsPlaying] = useState(false);
const [showRules, setShowRules] = useState(false); const [showRules, setShowRules] = useState(false);
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const isMountedRef = useRef(true); const isMountedRef = useRef(true);
const rulesShownRef = useRef(false); const rulesShownRef = useRef(false);
const trackedRef = useRef(false); const trackedRef = useRef(false);
@@ -57,6 +59,12 @@ const PronunciationPage: React.FC = () => {
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — освобождаем предыдущий URL
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// Останавливаем Web Speech API, если он что-то говорит // Останавливаем Web Speech API, если он что-то говорит
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
@@ -68,15 +76,26 @@ const PronunciationPage: React.FC = () => {
// Пробуем Edge TTS через бэкенд // Пробуем Edge TTS через бэкенд
const audioBlob = await getTTS(word, 'male'); const audioBlob = await getTTS(word, 'male');
const audioUrl = URL.createObjectURL(audioBlob); const audioUrl = URL.createObjectURL(audioBlob);
audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke
const audio = new Audio(audioUrl); const audio = new Audio(audioUrl);
audioRef.current = audio; audioRef.current = audio;
audio.onended = () => { audio.onended = () => {
if (isMountedRef.current) setIsPlaying(false); if (isMountedRef.current) setIsPlaying(false);
// 🔧 ФИКС (24.09.2026): освобождаем URL
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
}; };
audio.onerror = () => { audio.onerror = () => {
// 🔧 Освобождаем URL перед fallback
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// Edge TTS не сработал — пробуем Web Speech API // Edge TTS не сработал — пробуем Web Speech API
playWebSpeech(word); playWebSpeech(word);
}; };
@@ -169,6 +188,11 @@ const PronunciationPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — освобождаем URL при unmount
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
// Останавливаем Web Speech API при уходе со страницы // Останавливаем Web Speech API при уходе со страницы
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
+76 -6
View File
@@ -51,7 +51,11 @@ const TestViewPage: React.FC = () => {
const [examplesError, setExamplesError] = useState<string | null>(null); const [examplesError, setExamplesError] = useState<string | null>(null);
const [isPlayingExamples, setIsPlayingExamples] = useState(false); const [isPlayingExamples, setIsPlayingExamples] = useState(false);
const [isStartingPractice, setIsStartingPractice] = useState(false); const [isStartingPractice, setIsStartingPractice] = useState(false);
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert().
const [toastMessage, setToastMessage] = useState<string | null>(null);
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const brandColor = '#A970D6'; const brandColor = '#A970D6';
const textColor = '#1A1A2E'; const textColor = '#1A1A2E';
@@ -68,6 +72,12 @@ const TestViewPage: React.FC = () => {
...extra, ...extra,
}); });
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast.
const showToast = (msg: string) => {
setToastMessage(msg);
setTimeout(() => setToastMessage(null), 2500);
};
useEffect(() => { useEffect(() => {
if (topicId) { if (topicId) {
setLoading(true); setLoading(true);
@@ -91,6 +101,23 @@ const TestViewPage: React.FC = () => {
} }
}, [topicId]); }, [topicId]);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — cleanup при unmount.
useEffect(() => {
return () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, []);
// 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS — сигнатура // 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS — сигнатура
// приведена к общему виду (isFinalAnswer, usedHint) — как в LessonViewPage // приведена к общему виду (isFinalAnswer, usedHint) — как в LessonViewPage
// и PracticeViewPage. Раньше тест не передавал usedHint, и статистика // и PracticeViewPage. Раньше тест не передавал usedHint, и статистика
@@ -219,6 +246,11 @@ const TestViewPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — освобождаем предыдущий URL
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
@@ -228,10 +260,24 @@ const TestViewPage: React.FC = () => {
try { try {
const audioBlob = await getTTS(polishText, 'male'); const audioBlob = await getTTS(polishText, 'male');
const audioUrl = URL.createObjectURL(audioBlob); const audioUrl = URL.createObjectURL(audioBlob);
audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke
const audio = new Audio(audioUrl); const audio = new Audio(audioUrl);
audioRef.current = audio; audioRef.current = audio;
audio.onended = () => setIsPlayingExamples(false); audio.onended = () => {
audio.onerror = () => setIsPlayingExamples(false); setIsPlayingExamples(false);
// 🔧 ФИКС (24.09.2026): освобождаем URL
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
audio.onerror = () => {
setIsPlayingExamples(false);
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
await audio.play(); await audio.play();
} catch (e) { } catch (e) {
console.error('TTS error:', e); console.error('TTS error:', e);
@@ -248,8 +294,8 @@ const TestViewPage: React.FC = () => {
// Проверяем, есть ли слабые темы // Проверяем, есть ли слабые темы
const analytics = await getLearningAnalytics(); const analytics = await getLearningAnalytics();
if (!analytics.has_practice_available) { if (!analytics.has_practice_available) {
// Нет слабых тем — показываем сообщение // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert()
alert(t('testPracticeNoWeak')); showToast(t('testPracticeNoWeak'));
setIsStartingPractice(false); setIsStartingPractice(false);
return; return;
} }
@@ -264,12 +310,14 @@ const TestViewPage: React.FC = () => {
}, },
}); });
} else { } else {
alert(data.message || t('testPracticeNoWeak')); // 🔧 ФИКС (24.09.2026): toast вместо alert()
showToast(data.message || t('testPracticeNoWeak'));
setIsStartingPractice(false); setIsStartingPractice(false);
} }
} catch (e) { } catch (e) {
console.error('Error starting practice:', e); console.error('Error starting practice:', e);
alert(t('teacherAIError')); // 🔧 ФИКС (24.09.2026): toast вместо alert()
showToast(t('teacherAIError'));
setIsStartingPractice(false); setIsStartingPractice(false);
} }
}; };
@@ -309,6 +357,28 @@ const TestViewPage: React.FC = () => {
justifyContent: 'center', justifyContent: 'center',
padding: '24px', padding: '24px',
}}> }}>
{/* 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() */}
{toastMessage && (
<div style={{
position: 'fixed',
top: '20px',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 999,
padding: '12px 20px',
background: 'rgba(26,26,46,0.95)',
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 600,
borderRadius: radius.md,
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
maxWidth: '90vw',
textAlign: 'center',
}}>
{toastMessage}
</div>
)}
<div style={{ fontSize: '64px', marginBottom: '16px' }}> <div style={{ fontSize: '64px', marginBottom: '16px' }}>
{percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'} {percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'}
</div> </div>
+34 -2
View File
@@ -24,6 +24,8 @@ const TypingPage: React.FC = () => {
const [totalSentences, setTotalSentences] = useState(0); const [totalSentences, setTotalSentences] = useState(0);
const [isPlaying, setIsPlaying] = useState(false); const [isPlaying, setIsPlaying] = useState(false);
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TYPING — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const brandColor = '#2ECC71'; const brandColor = '#2ECC71';
const textColor = '#1A1A2E'; const textColor = '#1A1A2E';
@@ -52,6 +54,11 @@ const TypingPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_TYPING — освобождаем URL при новом запросе
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
getNextTypingSentence() getNextTypingSentence()
.then((data: any) => { .then((data: any) => {
@@ -81,6 +88,11 @@ const TypingPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_TYPING — освобождаем URL при unmount
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
@@ -125,6 +137,12 @@ const TypingPage: React.FC = () => {
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (24.09.2026): URL_LEAK_TYPING — освобождаем предыдущий URL
if (audioUrlRef.current) {
try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ }
audioUrlRef.current = null;
}
if ('speechSynthesis' in window) { if ('speechSynthesis' in window) {
window.speechSynthesis.cancel(); window.speechSynthesis.cancel();
} }
@@ -134,11 +152,25 @@ const TypingPage: React.FC = () => {
try { try {
const audioBlob = await getTTS(correctAnswer, 'male'); const audioBlob = await getTTS(correctAnswer, 'male');
const audioUrl = URL.createObjectURL(audioBlob); const audioUrl = URL.createObjectURL(audioBlob);
audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke
const audio = new Audio(audioUrl); const audio = new Audio(audioUrl);
audioRef.current = audio; audioRef.current = audio;
audio.onended = () => setIsPlaying(false); audio.onended = () => {
audio.onerror = () => setIsPlaying(false); setIsPlaying(false);
// 🔧 ФИКС (24.09.2026): освобождаем URL
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
audio.onerror = () => {
setIsPlaying(false);
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
await audio.play(); await audio.play();
} catch (e) { } catch (e) {