feat(system): implement graceful shutdown and expand websocket events
Improve system reliability and real-time capabilities by implementing a robust lifecycle management system and adding new broadcast events for attachments and voice recordings. - Implement asynchronous graceful shutdown in backend to close HTTP, WebSocket, Redis, and database connections. - Add new WebSocket broadcast events: `attachment_created`, `voice_recording_started`, `voice_recording_stopped`, `voice_recording_uploaded`, and `analysis_queue_status`. - Refactor media status handling to use boolean `playing` state instead of string-based status. - Centralize `PageResult` and `VoiceRecording` types to improve consistency between frontend and backend. - Update frontend API client to include `listRecordings` and handle new WebSocket event types. - Fix type mismatches in voice command handling and media status reporting.
This commit is contained in:
@@ -1,6 +1,10 @@
|
|||||||
import type { Server } from "node:http";
|
import type { Server } from "node:http";
|
||||||
import { createChildLogger } from "@bete/shared/logger";
|
import { createChildLogger } from "@bete/shared/logger";
|
||||||
import { startHttpServer } from "./http/server.js";
|
import { startHttpServer } from "./http/server.js";
|
||||||
|
import { closeDatabase } from "./shared/database/index.js";
|
||||||
|
import { stopCommandBridge } from "./shared/redis/index.js";
|
||||||
|
import { stopRedisBridge as stopEventBridge } from "./ws/redis-bridge.js";
|
||||||
|
import { closeWebSocketServer } from "./ws/server.js";
|
||||||
|
|
||||||
const logger = createChildLogger("backend");
|
const logger = createChildLogger("backend");
|
||||||
|
|
||||||
@@ -17,22 +21,43 @@ async function main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function shutdown(signal: string) {
|
async function shutdown(signal: string) {
|
||||||
logger.info({ signal }, "Shutting down gracefully");
|
logger.info({ signal }, "Shutting down gracefully");
|
||||||
|
|
||||||
if (httpServer) {
|
try {
|
||||||
httpServer.close(() => {
|
// 1. Stop accepting new HTTP connections
|
||||||
logger.info("HTTP server closed");
|
if (httpServer) {
|
||||||
process.exit(0);
|
await new Promise<void>((resolve) => {
|
||||||
});
|
httpServer!.close(() => {
|
||||||
|
logger.info("HTTP server closed");
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Force exit after 10s if connections don't close
|
// 2. Close WebSocket server
|
||||||
setTimeout(() => {
|
closeWebSocketServer();
|
||||||
logger.error("Forced shutdown after timeout");
|
|
||||||
process.exit(1);
|
// 3. Stop Redis bridges (event subscriptions + command channel)
|
||||||
}, 10_000).unref();
|
await Promise.allSettled([
|
||||||
} else {
|
stopEventBridge().catch((err) =>
|
||||||
|
logger.warn({ err }, "Error stopping event bridge"),
|
||||||
|
),
|
||||||
|
stopCommandBridge().catch((err) =>
|
||||||
|
logger.warn({ err }, "Error stopping command bridge"),
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 4. Close database pool
|
||||||
|
await closeDatabase().catch((err) =>
|
||||||
|
logger.warn({ err }, "Error closing database"),
|
||||||
|
);
|
||||||
|
|
||||||
|
logger.info("Graceful shutdown completed");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error({ err }, "Error during graceful shutdown");
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,12 +66,12 @@ process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|||||||
|
|
||||||
process.on("uncaughtException", (err) => {
|
process.on("uncaughtException", (err) => {
|
||||||
logger.error({ err }, "Uncaught exception");
|
logger.error({ err }, "Uncaught exception");
|
||||||
process.exit(1);
|
shutdown("uncaughtException");
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on("unhandledRejection", (reason) => {
|
process.on("unhandledRejection", (reason) => {
|
||||||
logger.error({ reason }, "Unhandled rejection");
|
logger.error({ reason }, "Unhandled rejection");
|
||||||
process.exit(1);
|
shutdown("unhandledRejection");
|
||||||
});
|
});
|
||||||
|
|
||||||
main();
|
main();
|
||||||
|
|||||||
@@ -47,8 +47,14 @@ export async function getStatus(): Promise<MediaState> {
|
|||||||
const cached = await readRedisStatus("media:status");
|
const cached = await readRedisStatus("media:status");
|
||||||
|
|
||||||
if (cached) {
|
if (cached) {
|
||||||
|
const rawPlaying = cached.playing;
|
||||||
|
// Handle both boolean (new) and string (legacy from String(discordPlayer.getStatus()))
|
||||||
|
const playing =
|
||||||
|
rawPlaying === true ||
|
||||||
|
rawPlaying === "playing" ||
|
||||||
|
rawPlaying === "buffering";
|
||||||
return {
|
return {
|
||||||
playing: Boolean(cached.playing),
|
playing,
|
||||||
musicVolume: Number(cached.musicVolume ?? 1.0),
|
musicVolume: Number(cached.musicVolume ?? 1.0),
|
||||||
current: (cached.current as MediaItem | null) ?? null,
|
current: (cached.current as MediaItem | null) ?? null,
|
||||||
queue: (cached.queue as MediaItem[]) ?? [],
|
queue: (cached.queue as MediaItem[]) ?? [],
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import type { PageResult } from "@bete/shared";
|
||||||
import { createChildLogger } from "@bete/shared/logger";
|
import { createChildLogger } from "@bete/shared/logger";
|
||||||
import { getPool } from "../../shared/database/index.js";
|
import { getPool } from "../../shared/database/index.js";
|
||||||
import type {
|
import type {
|
||||||
@@ -8,11 +9,6 @@ import type {
|
|||||||
|
|
||||||
const logger = createChildLogger("messages.repository");
|
const logger = createChildLogger("messages.repository");
|
||||||
|
|
||||||
export interface PageResult<T> {
|
|
||||||
data: T[];
|
|
||||||
nextCursor: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface AttachmentResult {
|
export interface AttachmentResult {
|
||||||
id: string;
|
id: string;
|
||||||
message_id: string;
|
message_id: string;
|
||||||
|
|||||||
@@ -12,13 +12,15 @@ export async function handleGetVoiceStatus(_req: Request, res: Response) {
|
|||||||
res.json(status);
|
res.json(status);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Safely extract a string value that may be a single string or string array. */
|
||||||
|
function asString(val: unknown): string {
|
||||||
|
if (Array.isArray(val)) return String(val[0] ?? "");
|
||||||
|
return String(val ?? "");
|
||||||
|
}
|
||||||
|
|
||||||
export async function handleConnectVoice(req: Request, res: Response) {
|
export async function handleConnectVoice(req: Request, res: Response) {
|
||||||
const guildId = Array.isArray(req.body.guildId)
|
const guildId = asString(req.body.guildId);
|
||||||
? req.body.guildId[0]
|
const channelId = asString(req.body.channelId);
|
||||||
: req.body.guildId;
|
|
||||||
const channelId = Array.isArray(req.body.channelId)
|
|
||||||
? req.body.channelId[0]
|
|
||||||
: req.body.channelId;
|
|
||||||
if (!guildId || !channelId) {
|
if (!guildId || !channelId) {
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
error: "VALIDATION_ERROR",
|
error: "VALIDATION_ERROR",
|
||||||
@@ -35,17 +37,13 @@ export async function handleDisconnectVoice(_req: Request, res: Response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function handleGetVoiceChannels(req: Request, res: Response) {
|
export async function handleGetVoiceChannels(req: Request, res: Response) {
|
||||||
const guildId = Array.isArray(req.params.guildId)
|
const guildId = asString(req.params.guildId);
|
||||||
? req.params.guildId[0]
|
|
||||||
: req.params.guildId;
|
|
||||||
const channels = await getVoiceChannels(guildId);
|
const channels = await getVoiceChannels(guildId);
|
||||||
res.json(channels);
|
res.json(channels);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function handleVoiceCommand(req: Request, res: Response) {
|
export async function handleVoiceCommand(req: Request, res: Response) {
|
||||||
const command = Array.isArray(req.body.command)
|
const command = asString(req.body.command);
|
||||||
? req.body.command[0]
|
|
||||||
: req.body.command;
|
|
||||||
|
|
||||||
if (!command) {
|
if (!command) {
|
||||||
return res.status(400).json({
|
return res.status(400).json({
|
||||||
@@ -55,7 +53,7 @@ export async function handleVoiceCommand(req: Request, res: Response) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await publishCommandNoReply(command as string);
|
await publishCommandNoReply(command);
|
||||||
res.json({ success: true, command });
|
res.json({ success: true, command });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
|
|||||||
@@ -260,7 +260,7 @@ export async function writeRedisStatus(
|
|||||||
// Lifecycle
|
// Lifecycle
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
export async function startRedisBridge(): Promise<void> {
|
export async function startCommandBridge(): Promise<void> {
|
||||||
if (!ensureRedisConfig()) {
|
if (!ensureRedisConfig()) {
|
||||||
logger.info("Redis not configured, skipping command channel bridge");
|
logger.info("Redis not configured, skipping command channel bridge");
|
||||||
return;
|
return;
|
||||||
@@ -272,7 +272,7 @@ export async function startRedisBridge(): Promise<void> {
|
|||||||
logger.info("Redis command channel initialized");
|
logger.info("Redis command channel initialized");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function stopRedisBridge(): Promise<void> {
|
export async function stopCommandBridge(): Promise<void> {
|
||||||
if (publisherClient) {
|
if (publisherClient) {
|
||||||
await publisherClient.quit();
|
await publisherClient.quit();
|
||||||
publisherClient = null;
|
publisherClient = null;
|
||||||
|
|||||||
@@ -18,9 +18,14 @@ export interface BroadcastFunctions {
|
|||||||
messageUpdated: BroadcastFn;
|
messageUpdated: BroadcastFn;
|
||||||
messageDeleted: BroadcastFn;
|
messageDeleted: BroadcastFn;
|
||||||
messageAnalyzed: BroadcastFn;
|
messageAnalyzed: BroadcastFn;
|
||||||
|
attachmentCreated: BroadcastFn;
|
||||||
attachmentUploaded: BroadcastFn;
|
attachmentUploaded: BroadcastFn;
|
||||||
|
voiceRecordingStarted: BroadcastFn;
|
||||||
|
voiceRecordingStopped: BroadcastFn;
|
||||||
|
voiceRecordingUploaded: BroadcastFn;
|
||||||
voicePcmData: BroadcastFn;
|
voicePcmData: BroadcastFn;
|
||||||
voiceActiveUser: BroadcastFn;
|
voiceActiveUser: BroadcastFn;
|
||||||
|
analysisQueueStatus: BroadcastFn;
|
||||||
raw: BroadcastRawFn;
|
raw: BroadcastRawFn;
|
||||||
binary: BroadcastBinaryFn;
|
binary: BroadcastBinaryFn;
|
||||||
}
|
}
|
||||||
@@ -53,18 +58,33 @@ export const broadcastMessageUpdated: BroadcastFn = (data) =>
|
|||||||
export const broadcastMessageDeleted: BroadcastFn = (data) =>
|
export const broadcastMessageDeleted: BroadcastFn = (data) =>
|
||||||
(_fns?.messageDeleted ?? noop)(data);
|
(_fns?.messageDeleted ?? noop)(data);
|
||||||
|
|
||||||
|
export const broadcastAttachmentCreated: BroadcastFn = (data) =>
|
||||||
|
(_fns?.attachmentCreated ?? noop)(data);
|
||||||
|
|
||||||
export const broadcastAttachmentUploaded: BroadcastFn = (data) =>
|
export const broadcastAttachmentUploaded: BroadcastFn = (data) =>
|
||||||
(_fns?.attachmentUploaded ?? noop)(data);
|
(_fns?.attachmentUploaded ?? noop)(data);
|
||||||
|
|
||||||
export const broadcastMessageAnalyzed: BroadcastFn = (data) =>
|
export const broadcastMessageAnalyzed: BroadcastFn = (data) =>
|
||||||
(_fns?.messageAnalyzed ?? noop)(data);
|
(_fns?.messageAnalyzed ?? noop)(data);
|
||||||
|
|
||||||
|
export const broadcastVoiceRecordingStarted: BroadcastFn = (data) =>
|
||||||
|
(_fns?.voiceRecordingStarted ?? noop)(data);
|
||||||
|
|
||||||
|
export const broadcastVoiceRecordingStopped: BroadcastFn = (data) =>
|
||||||
|
(_fns?.voiceRecordingStopped ?? noop)(data);
|
||||||
|
|
||||||
|
export const broadcastVoiceRecordingUploaded: BroadcastFn = (data) =>
|
||||||
|
(_fns?.voiceRecordingUploaded ?? noop)(data);
|
||||||
|
|
||||||
export const broadcastVoicePcmData: BroadcastFn = (data) =>
|
export const broadcastVoicePcmData: BroadcastFn = (data) =>
|
||||||
(_fns?.voicePcmData ?? noop)(data);
|
(_fns?.voicePcmData ?? noop)(data);
|
||||||
|
|
||||||
export const broadcastVoiceActiveUser: BroadcastFn = (data) =>
|
export const broadcastVoiceActiveUser: BroadcastFn = (data) =>
|
||||||
(_fns?.voiceActiveUser ?? noop)(data);
|
(_fns?.voiceActiveUser ?? noop)(data);
|
||||||
|
|
||||||
|
export const broadcastAnalysisQueueStatus: BroadcastFn = (data) =>
|
||||||
|
(_fns?.analysisQueueStatus ?? noop)(data);
|
||||||
|
|
||||||
export const broadcastRaw: BroadcastRawFn = (type, data) =>
|
export const broadcastRaw: BroadcastRawFn = (type, data) =>
|
||||||
(_fns?.raw ?? noopRaw)(type, data);
|
(_fns?.raw ?? noopRaw)(type, data);
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ interface BroadcastEvent {
|
|||||||
timestamp: string;
|
timestamp: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Track the active WebSocket server for lifecycle management
|
||||||
|
let _wss: WebSocketServer | null = null;
|
||||||
|
|
||||||
async function sendInitialStates(ws: WebSocket): Promise<void> {
|
async function sendInitialStates(ws: WebSocket): Promise<void> {
|
||||||
// Send initial user state
|
// Send initial user state
|
||||||
ws.send(
|
ws.send(
|
||||||
@@ -51,10 +54,18 @@ async function sendInitialStates(ws: WebSocket): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function closeWebSocketServer(): void {
|
||||||
|
if (!_wss) return;
|
||||||
|
logger.info("Closing WebSocket server");
|
||||||
|
_wss.close(() => logger.info("WebSocket server closed"));
|
||||||
|
_wss = null;
|
||||||
|
}
|
||||||
|
|
||||||
export function createWebSocketServer(server: Server): WebSocketServer {
|
export function createWebSocketServer(server: Server): WebSocketServer {
|
||||||
const clients = new Set<WebSocket>();
|
const clients = new Set<WebSocket>();
|
||||||
|
|
||||||
const wss = new WebSocketServer({ server, path: "/ws" });
|
const wss = new WebSocketServer({ server, path: "/ws" });
|
||||||
|
_wss = wss;
|
||||||
|
|
||||||
wss.on("connection", (ws: WebSocket) => {
|
wss.on("connection", (ws: WebSocket) => {
|
||||||
clients.add(ws);
|
clients.add(ws);
|
||||||
@@ -188,12 +199,22 @@ export function createWebSocketServer(server: Server): WebSocketServer {
|
|||||||
broadcast({ type: "message_deleted", data }),
|
broadcast({ type: "message_deleted", data }),
|
||||||
messageAnalyzed: (data: unknown) =>
|
messageAnalyzed: (data: unknown) =>
|
||||||
broadcast({ type: "message_analyzed", data }),
|
broadcast({ type: "message_analyzed", data }),
|
||||||
|
attachmentCreated: (data: unknown) =>
|
||||||
|
broadcast({ type: "attachment_created", data }),
|
||||||
attachmentUploaded: (data: unknown) =>
|
attachmentUploaded: (data: unknown) =>
|
||||||
broadcast({ type: "attachment_uploaded", data }),
|
broadcast({ type: "attachment_uploaded", data }),
|
||||||
|
voiceRecordingStarted: (data: unknown) =>
|
||||||
|
broadcast({ type: "voice_recording_started", data }),
|
||||||
|
voiceRecordingStopped: (data: unknown) =>
|
||||||
|
broadcast({ type: "voice_recording_stopped", data }),
|
||||||
|
voiceRecordingUploaded: (data: unknown) =>
|
||||||
|
broadcast({ type: "voice_recording_uploaded", data }),
|
||||||
voicePcmData: (data: unknown) =>
|
voicePcmData: (data: unknown) =>
|
||||||
broadcast({ type: "voice_pcm_data", data }),
|
broadcast({ type: "voice_pcm_data", data }),
|
||||||
voiceActiveUser: (data: unknown) =>
|
voiceActiveUser: (data: unknown) =>
|
||||||
broadcast({ type: "voice_active_user", data }),
|
broadcast({ type: "voice_active_user", data }),
|
||||||
|
analysisQueueStatus: (data: unknown) =>
|
||||||
|
broadcast({ type: "analysis_queue_status", data }),
|
||||||
raw: (type: string, data: unknown) => broadcast({ type, data }),
|
raw: (type: string, data: unknown) => broadcast({ type, data }),
|
||||||
binary: broadcastBinary,
|
binary: broadcastBinary,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ interface VoiceStatusPayload {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface MediaStatusPayload {
|
interface MediaStatusPayload {
|
||||||
playing: string;
|
playing: boolean;
|
||||||
musicVolume: number;
|
musicVolume: number;
|
||||||
current: unknown;
|
current: unknown;
|
||||||
queue: unknown[];
|
queue: unknown[];
|
||||||
@@ -341,25 +341,34 @@ export class CommandHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleMediaQueue(_cmd: BackendCommand): Promise<CommandReply> {
|
private getCurrentMediaStatus(): MediaStatusPayload {
|
||||||
|
return {
|
||||||
|
playing: discordPlayer.getStatus() === "playing",
|
||||||
|
musicVolume: discordPlayer.getMusicVolume(),
|
||||||
|
current: null,
|
||||||
|
queue: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async handleMediaQueue(cmd: BackendCommand): Promise<CommandReply> {
|
||||||
// Media queueing is handled at a higher level (frontend / backend streams
|
// Media queueing is handled at a higher level (frontend / backend streams
|
||||||
// audio directly). Log the request for now.
|
// audio directly). Log the request for now.
|
||||||
logger.info("media:queue received — media queueing is handled externally");
|
logger.info("media:queue received — media queueing is handled externally");
|
||||||
return {
|
return {
|
||||||
id: _cmd.id,
|
id: cmd.id,
|
||||||
success: true,
|
success: true,
|
||||||
data: { note: "media queueing handled externally" },
|
data: this.getCurrentMediaStatus(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleMediaSkip(cmd: BackendCommand): Promise<CommandReply> {
|
private async handleMediaSkip(cmd: BackendCommand): Promise<CommandReply> {
|
||||||
discordPlayer.stop("music");
|
discordPlayer.stop("music");
|
||||||
return { id: cmd.id, success: true, data: { action: "skipped" } };
|
return { id: cmd.id, success: true, data: this.getCurrentMediaStatus() };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleMediaStop(cmd: BackendCommand): Promise<CommandReply> {
|
private async handleMediaStop(cmd: BackendCommand): Promise<CommandReply> {
|
||||||
discordPlayer.stop("music");
|
discordPlayer.stop("music");
|
||||||
return { id: cmd.id, success: true, data: { action: "stopped" } };
|
return { id: cmd.id, success: true, data: this.getCurrentMediaStatus() };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleMediaVolume(cmd: BackendCommand): Promise<CommandReply> {
|
private async handleMediaVolume(cmd: BackendCommand): Promise<CommandReply> {
|
||||||
@@ -376,7 +385,7 @@ export class CommandHandler {
|
|||||||
return {
|
return {
|
||||||
id: cmd.id,
|
id: cmd.id,
|
||||||
success: true,
|
success: true,
|
||||||
data: { volume: discordPlayer.getMusicVolume() },
|
data: this.getCurrentMediaStatus(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -579,14 +588,7 @@ export class CommandHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private publishMediaStatus(): void {
|
private publishMediaStatus(): void {
|
||||||
const status: MediaStatusPayload = {
|
this.setKey(MEDIA_STATUS_KEY, JSON.stringify(this.getCurrentMediaStatus()));
|
||||||
playing: String(discordPlayer.getStatus()),
|
|
||||||
musicVolume: discordPlayer.getMusicVolume(),
|
|
||||||
current: null,
|
|
||||||
queue: [],
|
|
||||||
};
|
|
||||||
|
|
||||||
this.setKey(MEDIA_STATUS_KEY, JSON.stringify(status));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -88,6 +88,10 @@ export default function App() {
|
|||||||
messages
|
messages
|
||||||
.fetchMessages(monitorGuildId || undefined)
|
.fetchMessages(monitorGuildId || undefined)
|
||||||
.catch(() => undefined),
|
.catch(() => undefined),
|
||||||
|
onAttachmentCreated: () =>
|
||||||
|
messages
|
||||||
|
.fetchMessages(monitorGuildId || undefined)
|
||||||
|
.catch(() => undefined),
|
||||||
onMediaState: (state) => media.setMediaState(state as MediaState),
|
onMediaState: (state) => media.setMediaState(state as MediaState),
|
||||||
onVoiceRecordingUploaded: (d) =>
|
onVoiceRecordingUploaded: (d) =>
|
||||||
window.dispatchEvent(
|
window.dispatchEvent(
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ export type {
|
|||||||
AISeverity,
|
AISeverity,
|
||||||
AIStatus,
|
AIStatus,
|
||||||
MessageRecord,
|
MessageRecord,
|
||||||
|
PageResult,
|
||||||
} from "@bete/shared";
|
} from "@bete/shared";
|
||||||
|
|
||||||
export interface MessageMetadata {
|
export interface MessageMetadata {
|
||||||
@@ -26,8 +27,3 @@ export function parseMetadata(value: string | null): MessageMetadata {
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PageResult<T> {
|
|
||||||
data: T[];
|
|
||||||
nextCursor: string | null;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,43 +1,24 @@
|
|||||||
// ─── Recordings Sub-Panel — BUG 1 FIX: useEffect instead of useMemo for side effects ──
|
// ─── Recordings Sub-Panel ──
|
||||||
|
|
||||||
import { Download, Mic } from "lucide-react";
|
import { Download, Mic } from "lucide-react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import type { VoiceRecording } from "../../../shared/api/client";
|
||||||
|
import { listRecordings } from "../../../shared/api/client";
|
||||||
import { formatBytes, formatDate } from "../../../shared/lib/utils";
|
import { formatBytes, formatDate } from "../../../shared/lib/utils";
|
||||||
import { Badge, Button, EmptyStateMascot, Skeleton } from "../../../shared/ui";
|
import { Badge, Button, EmptyStateMascot, Skeleton } from "../../../shared/ui";
|
||||||
|
|
||||||
interface VoiceRecording {
|
|
||||||
id: string;
|
|
||||||
user_id: string;
|
|
||||||
username: string;
|
|
||||||
avatar_url: string | null;
|
|
||||||
guild_id: string | null;
|
|
||||||
channel_id: string | null;
|
|
||||||
channel_name: string | null;
|
|
||||||
filename: string;
|
|
||||||
size_bytes: number;
|
|
||||||
download_url: string | null;
|
|
||||||
upload_status: "pending" | "uploaded" | "failed";
|
|
||||||
upload_error: string | null;
|
|
||||||
created_at: number;
|
|
||||||
uploaded_at: number | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RecordingsSubPanel() {
|
export function RecordingsSubPanel() {
|
||||||
const [recordings, setRecordings] = useState<VoiceRecording[]>([]);
|
const [recordings, setRecordings] = useState<VoiceRecording[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
// BUG 1 FIX: proper useEffect for async data fetching
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
async function loadRecordings() {
|
async function loadRecordings() {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
const response = await fetch("/api/recordings");
|
const data = await listRecordings();
|
||||||
if (!response.ok)
|
|
||||||
throw new Error(`Failed to load recordings: ${response.status}`);
|
|
||||||
const data = (await response.json()) as VoiceRecording[];
|
|
||||||
if (!cancelled) setRecordings(data);
|
if (!cancelled) setRecordings(data);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (!cancelled)
|
if (!cancelled)
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ export function useVoiceControl() {
|
|||||||
const [textChannels, setTextChannels] = useState<Channel[]>([]);
|
const [textChannels, setTextChannels] = useState<Channel[]>([]);
|
||||||
const [voiceStatus, setVoiceStatus] = useState<VoiceStatus>({
|
const [voiceStatus, setVoiceStatus] = useState<VoiceStatus>({
|
||||||
connected: false,
|
connected: false,
|
||||||
|
activeGuildId: null,
|
||||||
|
activeChannelId: null,
|
||||||
|
activeChannelName: null,
|
||||||
});
|
});
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// ─── Shared HTTP client — all API endpoints in one file ──────────────────────
|
// ─── Shared HTTP client — all API endpoints in one file ──────────────────────
|
||||||
|
|
||||||
import type { MessageRecord } from "@bete/shared";
|
import type { MessageRecord, PageResult } from "@bete/shared";
|
||||||
|
|
||||||
const BE_API_URL = import.meta.env.VITE_BE_API_URL || "http://localhost:3001";
|
const BE_API_URL = import.meta.env.VITE_BE_API_URL || "http://localhost:3001";
|
||||||
const BE_WS_URL = import.meta.env.VITE_BE_WS_URL || "ws://localhost:3001";
|
const BE_WS_URL = import.meta.env.VITE_BE_WS_URL || "ws://localhost:3001";
|
||||||
@@ -54,12 +54,7 @@ export function getAPIURL(): string {
|
|||||||
|
|
||||||
// ─── Types ───────────────────────────────────────────────────────────────────
|
// ─── Types ───────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export interface PageResult<T> {
|
export type { MessageRecord, PageResult };
|
||||||
data: T[];
|
|
||||||
nextCursor: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type { MessageRecord };
|
|
||||||
|
|
||||||
export interface Guild {
|
export interface Guild {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -76,9 +71,9 @@ export interface Channel {
|
|||||||
|
|
||||||
export interface VoiceStatus {
|
export interface VoiceStatus {
|
||||||
connected: boolean;
|
connected: boolean;
|
||||||
activeGuildId?: string | null;
|
activeGuildId: string | null;
|
||||||
activeChannelId?: string | null;
|
activeChannelId: string | null;
|
||||||
activeChannelName?: string | null;
|
activeChannelName: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ActiveSpeaker {
|
export interface ActiveSpeaker {
|
||||||
@@ -237,6 +232,29 @@ export function setMediaVolume(volume: number): Promise<MediaState> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Recordings ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export interface VoiceRecording {
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
username: string;
|
||||||
|
avatar_url: string | null;
|
||||||
|
guild_id: string | null;
|
||||||
|
channel_id: string | null;
|
||||||
|
channel_name: string | null;
|
||||||
|
filename: string;
|
||||||
|
size_bytes: number;
|
||||||
|
download_url: string | null;
|
||||||
|
upload_status: "pending" | "uploaded" | "failed";
|
||||||
|
upload_error: string | null;
|
||||||
|
created_at: number;
|
||||||
|
uploaded_at: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listRecordings(limit = 50): Promise<VoiceRecording[]> {
|
||||||
|
return request<VoiceRecording[]>(`/api/recordings?limit=${limit}`);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Auth ────────────────────────────────────────────────────────────────────
|
// ─── Auth ────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function login(password: string): Promise<{ ok: boolean }> {
|
export function login(password: string): Promise<{ ok: boolean }> {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export interface WsHandlers {
|
|||||||
onMessageUpdated?: (data: unknown) => void;
|
onMessageUpdated?: (data: unknown) => void;
|
||||||
onMessageDeleted?: (data: unknown) => void;
|
onMessageDeleted?: (data: unknown) => void;
|
||||||
onMessageAnalyzed?: (data: unknown) => void;
|
onMessageAnalyzed?: (data: unknown) => void;
|
||||||
|
onAttachmentCreated?: (data: unknown) => void;
|
||||||
onAttachmentUploaded?: (data: unknown) => void;
|
onAttachmentUploaded?: (data: unknown) => void;
|
||||||
onUserState?: (users: unknown[]) => void;
|
onUserState?: (users: unknown[]) => void;
|
||||||
onUiState?: (state: unknown) => void;
|
onUiState?: (state: unknown) => void;
|
||||||
@@ -99,8 +100,7 @@ function doConnect(): WebSocket {
|
|||||||
h.onVoiceActiveUser?.(msg.data);
|
h.onVoiceActiveUser?.(msg.data);
|
||||||
break;
|
break;
|
||||||
case "attachment_created":
|
case "attachment_created":
|
||||||
// attachment_created is informational — same data shape as message_created
|
h.onAttachmentCreated?.(msg.data);
|
||||||
h.onMessageCreated?.(msg.data);
|
|
||||||
break;
|
break;
|
||||||
case "analysis_queue_status":
|
case "analysis_queue_status":
|
||||||
// analysis_queue_status is monitoring-only — no UI action needed
|
// analysis_queue_status is monitoring-only — no UI action needed
|
||||||
@@ -147,6 +147,7 @@ export function useDashboardSocket(handlers: WsHandlers) {
|
|||||||
onMessageUpdated: (d) => handlersRef.current.onMessageUpdated?.(d),
|
onMessageUpdated: (d) => handlersRef.current.onMessageUpdated?.(d),
|
||||||
onMessageDeleted: (d) => handlersRef.current.onMessageDeleted?.(d),
|
onMessageDeleted: (d) => handlersRef.current.onMessageDeleted?.(d),
|
||||||
onMessageAnalyzed: (d) => handlersRef.current.onMessageAnalyzed?.(d),
|
onMessageAnalyzed: (d) => handlersRef.current.onMessageAnalyzed?.(d),
|
||||||
|
onAttachmentCreated: (d) => handlersRef.current.onAttachmentCreated?.(d),
|
||||||
onAttachmentUploaded: (d) =>
|
onAttachmentUploaded: (d) =>
|
||||||
handlersRef.current.onAttachmentUploaded?.(d),
|
handlersRef.current.onAttachmentUploaded?.(d),
|
||||||
onUserState: (u) => handlersRef.current.onUserState?.(u),
|
onUserState: (u) => handlersRef.current.onUserState?.(u),
|
||||||
|
|||||||
Reference in New Issue
Block a user