refactor: atomic, DRY, and logging improvements across codebase

- Split llmModerationClient.ts (2170 lines) into 5 focused sub-modules
- Split aiAnalyzer.ts (1282 lines) into 4 modular pipelines
- Split messages.db.ts (826 lines) into 5 domain-specific modules
- Moved shared schema to @bete/shared, eliminated backend duplication
- Added createChildLogger to all voice-recording and AI moderation modules
- Extracted tryCommandThenFallback, normalizeMediaState, DEFAULT_VOICE_STATUS
- Created shared pagination.ts utility, eliminated 5+ cursor-pagination duplications
- Created shared messageMapper.ts for row mapping
- Standardized backend error handling with asyncHandler
- Added frontend createLogger utility and useAsyncAction hook
- Added structured logging to frontend hooks, socket, and API client

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MythEclipse
2026-06-09 19:46:08 +07:00
co-authored by Claude Opus 4.8
parent b68789fffc
commit 07032ab521
61 changed files with 3808 additions and 3043 deletions
@@ -0,0 +1,37 @@
// ─── Generic async action state hook ──────────────────────────────────────
import { useCallback, useState } from "react";
interface AsyncActionState {
loading: boolean;
error: string | null;
}
export function useAsyncAction() {
const [state, setState] = useState<AsyncActionState>({
loading: false,
error: null,
});
const execute = useCallback(
async <T>(fn: () => Promise<T>): Promise<T | null> => {
setState({ loading: true, error: null });
try {
const result = await fn();
setState({ loading: false, error: null });
return result;
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
setState({ loading: false, error: message });
return null;
}
},
[],
);
const clearError = useCallback(() => {
setState((prev) => ({ ...prev, error: null }));
}, []);
return { ...state, execute, clearError };
}
@@ -1,5 +1,8 @@
// ─── Audio playback hook — receives PCM from WebSocket and plays through Web Audio API ──
import { useCallback, useRef, useState } from "react";
import { createLogger } from "../lib/logger.js";
const logger = createLogger("use-audio-playback");
const SAMPLE_RATE = 24000;
const CHANNELS = 1;
@@ -15,56 +18,64 @@ export function useAudioPlayback() {
const handleIncomingPcm = useCallback(
(data: { userId: string; pcm: string }) => {
// Decode base64 PCM data
const binaryString = atob(data.pcm);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const int16Array = new Int16Array(bytes.buffer);
try {
const binaryString = atob(data.pcm);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
const int16Array = new Int16Array(bytes.buffer);
// Calculate audio levels for visualization
let sum = 0;
for (const sample of int16Array) sum += Math.abs(sample / 32768);
const average = int16Array.length ? sum / int16Array.length : 0;
setLevels((prev) =>
prev.map((_, index) =>
Math.max(
0.04,
average *
(0.5 + Math.sin(index * 0.6 + Date.now() / 140) * 0.35 + 0.65) *
5,
// Calculate audio levels for visualization
let sum = 0;
for (const sample of int16Array) sum += Math.abs(sample / 32768);
const average = int16Array.length ? sum / int16Array.length : 0;
setLevels((prev) =>
prev.map((_, index) =>
Math.max(
0.04,
average *
(0.5 + Math.sin(index * 0.6 + Date.now() / 140) * 0.35 + 0.65) *
5,
),
),
),
);
);
const audioContext = audioContextRef.current;
if (!isListening || !audioContext) return;
const audioContext = audioContextRef.current;
if (!isListening || !audioContext) return;
// Convert to float32 for Web Audio API
const float32Array = new Float32Array(int16Array.length);
for (let i = 0; i < int16Array.length; i++)
float32Array[i] = int16Array[i] / 32768;
// Convert to float32 for Web Audio API
const float32Array = new Float32Array(int16Array.length);
for (let i = 0; i < int16Array.length; i++)
float32Array[i] = int16Array[i] / 32768;
const audioBuffer = audioContext.createBuffer(
CHANNELS,
float32Array.length,
SAMPLE_RATE,
);
audioBuffer.getChannelData(0).set(float32Array);
const audioBuffer = audioContext.createBuffer(
CHANNELS,
float32Array.length,
SAMPLE_RATE,
);
audioBuffer.getChannelData(0).set(float32Array);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
// Schedule playback per user to avoid overlaps
const currentTime = audioContext.currentTime;
let nextStart = userTimelinesRef.current.get(data.userId) || 0;
if (nextStart < currentTime) nextStart = currentTime + 0.05;
source.start(nextStart);
userTimelinesRef.current.set(
data.userId,
nextStart + audioBuffer.duration,
);
// Schedule playback per user to avoid overlaps
const currentTime = audioContext.currentTime;
let nextStart = userTimelinesRef.current.get(data.userId) || 0;
if (nextStart < currentTime) nextStart = currentTime + 0.05;
source.start(nextStart);
userTimelinesRef.current.set(
data.userId,
nextStart + audioBuffer.duration,
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error("Failed to decode PCM audio", {
userId: data.userId,
error: message,
});
}
},
[isListening],
);
@@ -74,6 +85,7 @@ export function useAudioPlayback() {
await audioContextRef.current?.suspend();
userTimelinesRef.current.clear();
setIsListening(false);
logger.info("Audio playback paused");
return;
}
const AudioContextCtor =
@@ -85,6 +97,7 @@ export function useAudioPlayback() {
});
await audioContextRef.current.resume();
setIsListening(true);
logger.info("Audio playback started");
}, [isListening]);
return {