🌊 Волна 6: frontend данные + утечки (8 багов)

Утечки памяти:
- animated_cat_timeout_leak: timersRef + cleanup (AnimatedCat.tsx)
- compress_fallback_objecturl_leak: revokeObjectURL в onload/onerror (FeedPostComposer.tsx)
- lightbox_timeout_leak: safeTimeout + timersRef (ImageLightbox.tsx)
- OBJECT_URL_LEAK_TTS: audioUrlRef + revoke на onended/onerror (TeacherChatPage.tsx)

Данные:
- existing_image_removal_no_delete: removed_images в payload (FeedPostComposer.tsx + api.ts, ТРЕБУЕТ BACKEND)
- post_created_images_failed: пост создан → не даём дубль (FeedPostComposer.tsx)
- GET_INIT_DATA_EMPTY_STRING: логирование + безопасный fallback (telegram.ts)
- unvalidated_lang_from_url: валидация ['pl','ru','uk','en'] (LanguageContext.tsx)

Производительность:
- LEADERBOARD_O_N2_FILTER: filter вынесен из map (LeaderboardPage.tsx)

TTS_VOICE_NOT_ENCODED — уже сделано в Волне 4.

Аудит: Issue #3, frontend 8/34 задач
This commit is contained in:
2026-09-23 17:52:46 +03:00
parent fa9b678255
commit 97541e78ec
8 changed files with 152 additions and 23 deletions
+3
View File
@@ -613,6 +613,9 @@ export interface FeedPostPayload {
is_published?: boolean; is_published?: boolean;
expires_at?: string | null; expires_at?: string | null;
translate_again?: boolean; translate_again?: boolean;
// 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete —
// список URL существующих картинок, которые юзер удалил в UI.
removed_images?: string[];
} }
export interface FeedListResponse { export interface FeedListResponse {
+17 -3
View File
@@ -1,4 +1,4 @@
import { useState, useRef, useCallback } from 'react'; import { useState, useRef, useCallback, useEffect } from 'react';
interface AnimatedCatProps { interface AnimatedCatProps {
size?: number; size?: number;
@@ -22,10 +22,12 @@ const AnimatedCat: React.FC<AnimatedCatProps> = ({ size = 48, onClick, place = 1
const [isPressed, setIsPressed] = useState(false); const [isPressed, setIsPressed] = useState(false);
const [particles, setParticles] = useState<Particle[]>([]); const [particles, setParticles] = useState<Particle[]>([]);
const idRef = useRef(0); const idRef = useRef(0);
// 🔧 ФИКС (23.09.2026): animated_cat_timeout_leak — храним таймеры,
// чтобы очищать их при размонтировании.
const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);
const handleClick = useCallback(() => { const handleClick = useCallback(() => {
setIsPressed(true); setIsPressed(true);
setTimeout(() => setIsPressed(false), 200);
const newParticles: Particle[] = []; const newParticles: Particle[] = [];
@@ -48,13 +50,25 @@ const AnimatedCat: React.FC<AnimatedCatProps> = ({ size = 48, onClick, place = 1
} }
setParticles(prev => [...prev, ...newParticles]); setParticles(prev => [...prev, ...newParticles]);
setTimeout(() => {
// 🔧 ФИКС (23.09.2026): сохраняем таймеры для очистки
const t1 = setTimeout(() => setIsPressed(false), 200);
const t2 = setTimeout(() => {
setParticles(prev => prev.filter(p => !newParticles.find(np => np.id === p.id))); setParticles(prev => prev.filter(p => !newParticles.find(np => np.id === p.id)));
}, 2000); }, 2000);
timersRef.current.push(t1, t2);
if (onClick) onClick(); if (onClick) onClick();
}, [onClick]); }, [onClick]);
// 🔧 ФИКС (23.09.2026): animated_cat_timeout_leak — очистка таймеров при размонтировании
useEffect(() => {
return () => {
timersRef.current.forEach(clearTimeout);
timersRef.current = [];
};
}, []);
const medal = place === 1 ? '🥇' : place === 2 ? '🥈' : '🥉'; const medal = place === 1 ? '🥇' : place === 2 ? '🥈' : '🥉';
const glowColor = place === 1 ? '255,215,0' : place === 2 ? '192,192,192' : '205,127,50'; const glowColor = place === 1 ? '255,215,0' : place === 2 ? '192,192,192' : '205,127,50';
+37 -6
View File
@@ -77,9 +77,18 @@ async function compressImage(
} catch { } catch {
bitmap = await new Promise<HTMLImageElement>((resolve, reject) => { bitmap = await new Promise<HTMLImageElement>((resolve, reject) => {
const img = new Image(); const img = new Image();
img.onload = () => resolve(img); // 🔧 ФИКС (23.09.2026): compress_fallback_objecturl_leak — сохраняем URL,
img.onerror = () => reject(new Error('image load failed')); // чтобы освободить после загрузки.
img.src = URL.createObjectURL(blob); const objectUrl = URL.createObjectURL(blob);
img.onload = () => {
URL.revokeObjectURL(objectUrl);
resolve(img);
};
img.onerror = () => {
URL.revokeObjectURL(objectUrl);
reject(new Error('image load failed'));
};
img.src = objectUrl;
}); });
} }
@@ -165,6 +174,9 @@ const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
const [slots, setSlots] = useState<(ImageSlot | null)[]>([null, null, null]); const [slots, setSlots] = useState<(ImageSlot | null)[]>([null, null, null]);
// Существующие картинки (режим редактирования) — занимают слоты в начале // Существующие картинки (режим редактирования) — занимают слоты в начале
const [existingImages, setExistingImages] = useState<string[]>([]); const [existingImages, setExistingImages] = useState<string[]>([]);
// 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete — трекаем удалённые URL,
// чтобы передать их на бэк при сохранении.
const [removedImages, setRemovedImages] = useState<string[]>([]);
// Три отдельных input[type=file] — по одному на слот. Без multiple. // Три отдельных input[type=file] — по одному на слот. Без multiple.
const slotInputRef0 = useRef<HTMLInputElement>(null); const slotInputRef0 = useRef<HTMLInputElement>(null);
@@ -207,6 +219,8 @@ const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
setTranslationPreview(null); setTranslationPreview(null);
setError(null); setError(null);
setSuccess(false); setSuccess(false);
// 🔧 ФИКС (23.09.2026): сбрасываем удалённые картинки при открытии
setRemovedImages([]);
}, [isOpen, editingPost, language]); }, [isOpen, editingPost, language]);
// 🔧 ФИКС (22.09.2026): утечка ObjectURL при размонтировании. // 🔧 ФИКС (22.09.2026): утечка ObjectURL при размонтировании.
@@ -307,6 +321,12 @@ const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
}; };
const handleRemoveExistingImage = (index: number) => { const handleRemoveExistingImage = (index: number) => {
const url = existingImages[index];
if (url) {
// 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete —
// запоминаем URL, чтобы удалить на бэке при сохранении.
setRemovedImages(prev => [...prev, url]);
}
setExistingImages((prev) => prev.filter((_, i) => i !== index)); setExistingImages((prev) => prev.filter((_, i) => i !== index));
}; };
@@ -359,6 +379,8 @@ const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
is_pinned: isPinned, is_pinned: isPinned,
expires_at: expiresAt ? new Date(expiresAt).toISOString() : null, expires_at: expiresAt ? new Date(expiresAt).toISOString() : null,
translate_again: translateAgain, translate_again: translateAgain,
// 🔧 ФИКС (23.09.2026): existing_image_removal_no_delete
removed_images: removedImages,
}); });
postId = result.post_id; postId = result.post_id;
} else { } else {
@@ -395,12 +417,21 @@ const FeedPostComposer: React.FC<FeedPostComposerProps> = ({
} }
} }
// 🔧 ФИКС: если хоть одна загрузка упала — не считаем публикацию успешной // 🔧 ФИКС (23.09.2026): post_created_images_failed — пост уже СОЗДАН,
// поэтому не даём юзеру нажать «опубликовать» повторно (иначе дубль).
// Показываем уведомление, но закрываем composer как «успех».
if (failedUploads.length > 0) { if (failedUploads.length > 0) {
setError( setError(
`Не удалось загрузить: ${failedUploads.join(', ')}. ` + `Пост создан, но не все фото загрузились: ${failedUploads.join(', ')}. ` +
`Загружено ${uploadResults.length} из ${imagesToUpload.length} фото.` `Загружено ${uploadResults.length} из ${imagesToUpload.length}. ` +
`Открой пост и добавь фото заново.`
); );
// Не даём повторно публиковать — переходим в success через 2с
setSuccess(true);
setTimeout(() => {
onSuccess();
onClose();
}, 2500);
return; return;
} }
+22 -5
View File
@@ -22,6 +22,15 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
const touchStartX = useRef(0); const touchStartX = useRef(0);
const touchStartY = useRef(0); const touchStartY = useRef(0);
const isHorizontal = useRef<boolean | null>(null); const isHorizontal = useRef<boolean | null>(null);
// 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — храним таймеры для очистки.
const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);
// 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — обёртка для автоочистки
const safeTimeout = (fn: () => void, ms: number) => {
const t = setTimeout(fn, ms);
timersRef.current.push(t);
return t;
};
// Сброс индекса при открытии // Сброс индекса при открытии
useEffect(() => { useEffect(() => {
@@ -32,6 +41,14 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
} }
}, [isOpen, initialIndex]); }, [isOpen, initialIndex]);
// 🔧 ФИКС (23.09.2026): lightbox_timeout_leak — очистка таймеров при размонтировании
useEffect(() => {
return () => {
timersRef.current.forEach(clearTimeout);
timersRef.current = [];
};
}, []);
const goNext = useCallback(() => { const goNext = useCallback(() => {
setCurrentIndex(prev => (prev < images.length - 1 ? prev + 1 : prev)); setCurrentIndex(prev => (prev < images.length - 1 ? prev + 1 : prev));
}, [images.length]); }, [images.length]);
@@ -113,7 +130,7 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
if (currentIndex > 0) { if (currentIndex > 0) {
setIsAnimating(true); setIsAnimating(true);
setOffsetX(window.innerWidth); // улетаем вправо setOffsetX(window.innerWidth); // улетаем вправо
setTimeout(() => { safeTimeout(() => {
goPrev(); goPrev();
setOffsetX(0); setOffsetX(0);
setIsAnimating(false); setIsAnimating(false);
@@ -122,14 +139,14 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
// Отскок назад // Отскок назад
setIsAnimating(true); setIsAnimating(true);
setOffsetX(0); setOffsetX(0);
setTimeout(() => setIsAnimating(false), 250); safeTimeout(() => setIsAnimating(false), 250);
} }
} else if (offsetX < -threshold) { } else if (offsetX < -threshold) {
// Свайп влево → следующая // Свайп влево → следующая
if (currentIndex < images.length - 1) { if (currentIndex < images.length - 1) {
setIsAnimating(true); setIsAnimating(true);
setOffsetX(-window.innerWidth); // улетаем влево setOffsetX(-window.innerWidth); // улетаем влево
setTimeout(() => { safeTimeout(() => {
goNext(); goNext();
setOffsetX(0); setOffsetX(0);
setIsAnimating(false); setIsAnimating(false);
@@ -138,13 +155,13 @@ const ImageLightbox: React.FC<ImageLightboxProps> = ({
// Отскок назад // Отскок назад
setIsAnimating(true); setIsAnimating(true);
setOffsetX(0); setOffsetX(0);
setTimeout(() => setIsAnimating(false), 250); safeTimeout(() => setIsAnimating(false), 250);
} }
} else { } else {
// Не дотянули — плавно возвращаем на место // Не дотянули — плавно возвращаем на место
setIsAnimating(true); setIsAnimating(true);
setOffsetX(0); setOffsetX(0);
setTimeout(() => setIsAnimating(false), 250); safeTimeout(() => setIsAnimating(false), 250);
} }
isHorizontal.current = null; isHorizontal.current = null;
+14 -2
View File
@@ -19,14 +19,26 @@ export const useLanguage = () => useContext(LanguageContext);
export const LanguageProvider: React.FC<{ children: ReactNode }> = ({ children }) => { export const LanguageProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [language, setLanguageState] = useState(() => { const [language, setLanguageState] = useState(() => {
// 🔧 ФИКС (23.09.2026): unvalidated_lang_from_url — валидация обоих источников.
const SUPPORTED = ['pl', 'ru', 'uk', 'en'];
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const langFromUrl = urlParams.get('lang'); const langFromUrl = urlParams.get('lang');
const langFromStorage = localStorage.getItem('filwords_lang'); const langFromStorage = localStorage.getItem('filwords_lang');
return langFromUrl || langFromStorage || 'pl';
if (langFromUrl && SUPPORTED.includes(langFromUrl)) return langFromUrl;
if (langFromStorage && SUPPORTED.includes(langFromStorage)) return langFromStorage;
return 'pl';
}); });
useEffect(() => { useEffect(() => {
localStorage.setItem('filwords_lang', language); const SUPPORTED = ['pl', 'ru', 'uk', 'en'];
if (SUPPORTED.includes(language)) {
localStorage.setItem('filwords_lang', language);
} else {
// 🔧 ФИКС (23.09.2026): unvalidated_lang_from_url — очищаем мусор
localStorage.removeItem('filwords_lang');
return;
}
if (getUserId()) { if (getUserId()) {
setLanguage(language).catch(() => {}); setLanguage(language).catch(() => {});
} }
+6 -2
View File
@@ -219,6 +219,10 @@ const LeaderboardPage: React.FC = () => {
return orderA - orderB; return orderA - orderB;
}); });
// 🔧 ФИКС (23.09.2026): LEADERBOARD_O_N2_FILTER — выносим filter из .map(),
// чтобы не делать O(n²) на каждой строке.
const restEntries = entries.filter(e => e.rank > 3);
const labels: Record<string, string> = { const labels: Record<string, string> = {
achievements: language === 'pl' ? 'Osiągnięcia' : language === 'ru' ? 'Достижения' : language === 'uk' ? 'Досягнення' : 'Achievements', achievements: language === 'pl' ? 'Osiągnięcia' : language === 'ru' ? 'Достижения' : language === 'uk' ? 'Досягнення' : 'Achievements',
unlocked: language === 'pl' ? 'odblokowano' : language === 'ru' ? 'получено' : language === 'uk' ? 'отримано' : 'unlocked', unlocked: language === 'pl' ? 'odblokowano' : language === 'ru' ? 'получено' : language === 'uk' ? 'отримано' : 'unlocked',
@@ -565,7 +569,7 @@ const LeaderboardPage: React.FC = () => {
<span style={{ textAlign: 'right' }}>{t('score')}</span> <span style={{ textAlign: 'right' }}>{t('score')}</span>
</div> </div>
{entries.filter(e => e.rank > 3).map((entry, index) => { {restEntries.map((entry, index) => {
const isCurrentUser = entry.telegram_id === currentUserId; const isCurrentUser = entry.telegram_id === currentUserId;
const displayName = isCurrentUser ? 'You' : truncateName(entry.username, 15); const displayName = isCurrentUser ? 'You' : truncateName(entry.username, 15);
@@ -577,7 +581,7 @@ const LeaderboardPage: React.FC = () => {
gridTemplateColumns: '40px 1fr 80px', gridTemplateColumns: '40px 1fr 80px',
gap: '6px', gap: '6px',
padding: '12px 14px', padding: '12px 14px',
borderBottom: index < entries.filter(e => e.rank > 3).length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none', borderBottom: index < restEntries.length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none',
alignItems: 'center', alignItems: 'center',
fontSize: '13px', fontSize: '13px',
animation: `fadeInUp 0.3s ease ${0.3 + index * 0.02}s both`, animation: `fadeInUp 0.3s ease ${0.3 + index * 0.02}s both`,
+48 -5
View File
@@ -103,6 +103,8 @@ const TeacherChatPage: React.FC = () => {
const messagesEndRef = useRef<HTMLDivElement>(null); const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null); const inputRef = useRef<HTMLInputElement>(null);
const audioRef = useRef<HTMLAudioElement | null>(null); const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — храним URL для revoke.
const audioUrlRef = useRef<string | null>(null);
const idRef = useRef(messages.length > 0 ? Math.max(...messages.map(m => m.id)) + 1 : 0); const idRef = useRef(messages.length > 0 ? Math.max(...messages.map(m => m.id)) + 1 : 0);
const startTimeRef = useRef<number>(Date.now()); const startTimeRef = useRef<number>(Date.now());
@@ -277,7 +279,11 @@ const TeacherChatPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — освобождаем предыдущий 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();
} }
@@ -287,12 +293,26 @@ const TeacherChatPage: 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 = () => setIsPlaying(null); audio.onended = () => {
audio.onerror = () => setIsPlaying(null); setIsPlaying(null);
// 🔧 ФИКС (23.09.2026): освобождаем URL после воспроизведения
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
audio.onerror = () => {
setIsPlaying(null);
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
await audio.play(); await audio.play();
} catch (e) { } catch (e) {
@@ -314,6 +334,11 @@ const TeacherChatPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS
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();
} }
@@ -323,10 +348,23 @@ const TeacherChatPage: 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;
const audio = new Audio(audioUrl); const audio = new Audio(audioUrl);
audioRef.current = audio; audioRef.current = audio;
audio.onended = () => setPlayingExampleLine(null); audio.onended = () => {
audio.onerror = () => setPlayingExampleLine(null); setPlayingExampleLine(null);
if (audioUrlRef.current === audioUrl) {
try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ }
audioUrlRef.current = null;
}
};
audio.onerror = () => {
setPlayingExampleLine(null);
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);
@@ -356,6 +394,11 @@ const TeacherChatPage: React.FC = () => {
audioRef.current.pause(); audioRef.current.pause();
audioRef.current = null; audioRef.current = null;
} }
// 🔧 ФИКС (23.09.2026): OBJECT_URL_LEAK_TTS — освобождаем 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();
} }
+5
View File
@@ -2,6 +2,11 @@ export const getInitData = (): string => {
if (typeof window !== 'undefined' && window.Telegram?.WebApp?.initData) { if (typeof window !== 'undefined' && window.Telegram?.WebApp?.initData) {
return window.Telegram.WebApp.initData; return window.Telegram.WebApp.initData;
} }
// 🔧 ФИКС (23.09.2026): GET_INIT_DATA_EMPTY_STRING — логируем,
// чтобы понимать, что приложение открыто вне Telegram.
// Само значение "" оставляем для обратной совместимости с auth.py,
// который сам вернёт 401 "initData required" — это понятнее для дебага.
console.warn('[telegram] getInitData: no Telegram WebApp context');
return ""; return "";
}; };