fix: chat duplication, lobby scroll, ban self-protection

- Chat: fix race condition where SSE delivers message before POST
  response, causing duplicate — now checks if real msg already exists
- LobbyManager: add max-h-72 + overflow-y-auto for long participant lists
- ModerationPanel: hide kick/ban buttons for yourself (useLocalParticipant),
  add max-h-80 + overflow scroll, show API errors instead of silencing
- Moderate API: reject kick/ban when targetSessionId === host userId
This commit is contained in:
2026-03-24 12:31:02 +03:00
parent f6d3f37a5f
commit 87f0b5a21d
4 changed files with 77 additions and 44 deletions
@@ -45,6 +45,9 @@ export async function POST(
if (!targetSessionId) { if (!targetSessionId) {
return NextResponse.json({ error: "targetSessionId required" }, { status: 400 }); return NextResponse.json({ error: "targetSessionId required" }, { status: 400 });
} }
if (targetSessionId === session.user.id) {
return NextResponse.json({ error: "Cannot kick yourself" }, { status: 400 });
}
await roomService.removeParticipant(lkRoom, targetSessionId); await roomService.removeParticipant(lkRoom, targetSessionId);
await prisma.participantHistory.updateMany({ await prisma.participantHistory.updateMany({
where: { roomId, sessionId: targetSessionId, leftAt: null }, where: { roomId, sessionId: targetSessionId, leftAt: null },
@@ -57,6 +60,9 @@ export async function POST(
if (!targetSessionId) { if (!targetSessionId) {
return NextResponse.json({ error: "targetSessionId required" }, { status: 400 }); return NextResponse.json({ error: "targetSessionId required" }, { status: 400 });
} }
if (targetSessionId === session.user.id) {
return NextResponse.json({ error: "Cannot ban yourself" }, { status: 400 });
}
// Find fingerprint from lobby entry or participant // Find fingerprint from lobby entry or participant
const lobbyEntry = await prisma.lobbyEntry.findFirst({ const lobbyEntry = await prisma.lobbyEntry.findFirst({
+3 -3
View File
@@ -55,8 +55,8 @@ export default function LobbyManager({ roomId }: LobbyManagerProps) {
} }
return ( return (
<div className="p-4"> <div className="p-4 max-h-72 flex flex-col">
<div className="flex items-center gap-2 mb-3"> <div className="flex items-center gap-2 mb-3 shrink-0">
<h3 className="text-sm font-semibold text-white">Зал ожидания</h3> <h3 className="text-sm font-semibold text-white">Зал ожидания</h3>
{entries.length > 0 && ( {entries.length > 0 && (
<span className="text-[11px] font-medium text-accent bg-accent/15 px-1.5 py-0.5 rounded-md"> <span className="text-[11px] font-medium text-accent bg-accent/15 px-1.5 py-0.5 rounded-md">
@@ -68,7 +68,7 @@ export default function LobbyManager({ roomId }: LobbyManagerProps) {
{entries.length === 0 ? ( {entries.length === 0 ? (
<p className="text-sm text-text-muted py-2">Никто не ожидает</p> <p className="text-sm text-text-muted py-2">Никто не ожидает</p>
) : ( ) : (
<div className="space-y-1.5"> <div className="space-y-1.5 overflow-y-auto">
{entries.map((entry) => ( {entries.map((entry) => (
<div <div
key={entry.id} key={entry.id}
+10 -4
View File
@@ -98,11 +98,17 @@ export default function ChatPanel({ roomId, sessionId, senderName }: ChatPanelPr
}); });
if (res.ok) { if (res.ok) {
const msg = await res.json(); const msg = await res.json();
// Replace optimistic message with real one
seenIds.current.add(msg.id); seenIds.current.add(msg.id);
setMessages((prev) => setMessages((prev) => {
prev.map((m) => (m.id === optimisticMsg.id ? { ...msg, createdAt: msg.createdAt } : m)) // Check if SSE already delivered this message (race condition)
); const sseAlreadyDelivered = prev.some((m) => m.id === msg.id);
if (sseAlreadyDelivered) {
// Just remove the optimistic message
return prev.filter((m) => m.id !== optimisticMsg.id);
}
// Replace optimistic with real
return prev.map((m) => (m.id === optimisticMsg.id ? msg : m));
});
} }
} catch { } catch {
// Remove optimistic message on failure // Remove optimistic message on failure
+58 -37
View File
@@ -1,7 +1,7 @@
"use client"; "use client";
import { useState, useCallback } from "react"; import { useState, useCallback } from "react";
import { useParticipants } from "@livekit/components-react"; import { useParticipants, useLocalParticipant } from "@livekit/components-react";
import type { ModerationAction } from "@/types"; import type { ModerationAction } from "@/types";
interface ModerationPanelProps { interface ModerationPanelProps {
@@ -10,19 +10,26 @@ interface ModerationPanelProps {
export default function ModerationPanel({ roomId }: ModerationPanelProps) { export default function ModerationPanel({ roomId }: ModerationPanelProps) {
const participants = useParticipants(); const participants = useParticipants();
const { localParticipant } = useLocalParticipant();
const [acting, setActing] = useState<string | null>(null); const [acting, setActing] = useState<string | null>(null);
const [error, setError] = useState("");
const moderate = useCallback( const moderate = useCallback(
async (action: ModerationAction, targetSessionId?: string) => { async (action: ModerationAction, targetSessionId?: string) => {
setError("");
setActing(targetSessionId ?? action); setActing(targetSessionId ?? action);
try { try {
await fetch(`/api/rooms/${roomId}/moderate`, { const res = await fetch(`/api/rooms/${roomId}/moderate`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action, targetSessionId }), body: JSON.stringify({ action, targetSessionId }),
}); });
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.error ?? `Ошибка: ${res.status}`);
}
} catch { } catch {
// silent setError("Ошибка сети");
} finally { } finally {
setActing(null); setActing(null);
} }
@@ -30,14 +37,22 @@ export default function ModerationPanel({ roomId }: ModerationPanelProps) {
[roomId] [roomId]
); );
const myIdentity = localParticipant?.identity;
return ( return (
<div className="p-4"> <div className="p-4 max-h-80 flex flex-col">
<h3 className="text-sm font-semibold text-white mb-4">Модерация</h3> <h3 className="text-sm font-semibold text-white mb-4 shrink-0">Модерация</h3>
{error && (
<div className="bg-danger/10 border border-danger/20 text-danger px-3 py-2 rounded-lg text-xs mb-3 shrink-0">
{error}
</div>
)}
<button <button
onClick={() => moderate("mute_all")} onClick={() => moderate("mute_all")}
disabled={acting === "mute_all"} disabled={acting === "mute_all"}
className="w-full py-2.5 bg-danger/10 hover:bg-danger/20 text-danger border border-danger/20 disabled:opacity-50 rounded-lg text-sm font-medium transition-colors mb-5 flex items-center justify-center gap-2" className="w-full py-2.5 bg-danger/10 hover:bg-danger/20 text-danger border border-danger/20 disabled:opacity-50 rounded-lg text-sm font-medium transition-colors mb-5 flex items-center justify-center gap-2 shrink-0"
> >
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 19l-7-7m0 0l-7-7m7 7l7-7m-7 7l-7 7" /> <path strokeLinecap="round" strokeLinejoin="round" d="M19 19l-7-7m0 0l-7-7m7 7l7-7m-7 7l-7 7" />
@@ -45,44 +60,50 @@ export default function ModerationPanel({ roomId }: ModerationPanelProps) {
Выключить все микрофоны Выключить все микрофоны
</button> </button>
<div> <div className="flex-1 min-h-0 overflow-y-auto">
<p className="text-xs text-text-muted font-medium uppercase tracking-wider mb-2"> <p className="text-xs text-text-muted font-medium uppercase tracking-wider mb-2">
Участники ({participants.length}) Участники ({participants.length})
</p> </p>
<div className="space-y-1.5"> <div className="space-y-1.5">
{participants.map((p) => ( {participants.map((p) => {
<div const isMe = p.identity === myIdentity;
key={p.identity} return (
className="flex items-center justify-between bg-surface-2 rounded-lg px-3 py-2.5 group hover:bg-surface-3 transition-colors" <div
> key={p.identity}
<div className="flex items-center gap-2 min-w-0 mr-2"> className="flex items-center justify-between bg-surface-2 rounded-lg px-3 py-2.5 group hover:bg-surface-3 transition-colors"
<div className="w-7 h-7 rounded-full bg-surface-3 flex items-center justify-center shrink-0"> >
<span className="text-xs font-medium text-text-secondary"> <div className="flex items-center gap-2 min-w-0 mr-2">
{(p.name || p.identity).charAt(0).toUpperCase()} <div className="w-7 h-7 rounded-full bg-surface-3 flex items-center justify-center shrink-0">
<span className="text-xs font-medium text-text-secondary">
{(p.name || p.identity).charAt(0).toUpperCase()}
</span>
</div>
<span className="text-sm text-text-primary truncate">
{p.name || p.identity}
{isMe && <span className="text-text-muted ml-1">(вы)</span>}
</span> </span>
</div> </div>
<span className="text-sm text-text-primary truncate"> {!isMe && (
{p.name || p.identity} <div className="flex gap-1 shrink-0">
</span> <button
onClick={() => moderate("kick", p.identity)}
disabled={acting === p.identity}
className="px-2.5 py-1 text-xs text-text-secondary bg-surface-1 hover:bg-surface-3 hover:text-white border border-border-default rounded-md transition-colors disabled:opacity-50"
>
Кик
</button>
<button
onClick={() => moderate("ban", p.identity)}
disabled={acting === p.identity}
className="px-2.5 py-1 text-xs text-danger bg-danger/10 hover:bg-danger/20 border border-danger/20 rounded-md transition-colors disabled:opacity-50"
>
Бан
</button>
</div>
)}
</div> </div>
<div className="flex gap-1 shrink-0"> );
<button })}
onClick={() => moderate("kick", p.identity)}
disabled={acting === p.identity}
className="px-2.5 py-1 text-xs text-text-secondary bg-surface-1 hover:bg-surface-3 hover:text-white border border-border-default rounded-md transition-colors disabled:opacity-50"
>
Кик
</button>
<button
onClick={() => moderate("ban", p.identity)}
disabled={acting === p.identity}
className="px-2.5 py-1 text-xs text-danger bg-danger/10 hover:bg-danger/20 border border-danger/20 rounded-md transition-colors disabled:opacity-50"
>
Бан
</button>
</div>
</div>
))}
</div> </div>
</div> </div>
</div> </div>