Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
819 lines
45 KiB
TypeScript
819 lines
45 KiB
TypeScript
"use client";
|
||
// Sessões do Clipador: gravar uma live ou baixar um VOD pelo link, acompanhar cada sessão (chat,
|
||
// transcrição, varredura da IA, cortes), "Cortar agora" na live, parar, apagar e ver o gráfico do chat.
|
||
//
|
||
// O cartão da sessão se lê de cima para baixo: quem/estado/tempo + ações principais → saúde em uma frase →
|
||
// o que está acontecendo (resumo da IA + jogo) → quatro blocos comparáveis do pipeline → ferramentas.
|
||
// A página consulta o serviço a cada 5 s: todo bloco tem altura fixa (linhas truncadas, barra sempre
|
||
// presente, espaço reservado) para nada pular nem mudar de altura quando um número muda.
|
||
import { useEffect, useId, useLayoutEffect, useState, useSyncExternalStore, type FormEvent, type ReactNode } from "react";
|
||
import {
|
||
ACTIVE_SESSION, CLIP_STATUS, CLIP_STATUS_ORDER, PLATFORM_LABEL, SESSION_STATUS, chatStatusInfo, clipperCall, formatClock,
|
||
captureLabel, channelKeyOf, formatDuration, gameIdOf, gbPerHourLabel, useClipperAction,
|
||
type Clip, type ClipStatus, type ClipperPlatform, type ClipperSession, type Game, type JudgeOptions, type Timeline,
|
||
} from "./clipper-client";
|
||
import { ChannelEmotes, SessionGame } from "./clipper-games";
|
||
import {
|
||
AlertIcon, BroadcastIcon, ChartIcon, ChatIcon, CheckIcon, ChevronDownIcon, EyeIcon, KickIcon, MicIcon, ScissorsIcon, SettingsIcon,
|
||
SparkIcon, StopIcon, TrashIcon, TwitchIcon, YouTubeIcon,
|
||
} from "./icons";
|
||
import { Badge, Button, EmptyState, Feedback, Input, ProgressBar, Spinner, cx, formatDate, formatInteger, type Tone } from "./ui";
|
||
import { askConfirm } from "./confirm-dialog";
|
||
|
||
/** Opções do "Cortar agora" (últimos N segundos). */
|
||
const CUT_OPTIONS = [30, 45, 60] as const;
|
||
|
||
/** A varredura da IA assiste janelas de 3 min: padrão de `scanIntervalS` em `OPTION_DEFAULTS` (clipper/app/intel.py).
|
||
* O valor em uso vem de `judge.options.scanIntervalS` em /status; este é o reserva (serviço antigo ou fora do ar). */
|
||
const SCAN_WINDOW_S = 180;
|
||
/** Ao vivo, a IA fica até uma janela atrás por natureza; mais de duas janelas e pouco = atrasada. */
|
||
const SCAN_LATE_S = SCAN_WINDOW_S * 2 + 60;
|
||
/** Trechos de 30 s esperando transcrição acima disso, ao vivo = transcrição atrasada. */
|
||
const TRANSCRIPT_LATE_SEGMENTS = 4;
|
||
|
||
type Run = ReturnType<typeof useClipperAction>["run"];
|
||
|
||
export function PlatformIcon({ platform, size = 16, className }: { platform: ClipperPlatform; size?: number; className?: string }) {
|
||
const Icon = platform === "twitch" ? TwitchIcon : platform === "kick" ? KickIcon : YouTubeIcon;
|
||
return <Icon size={size} className={className} />;
|
||
}
|
||
|
||
/* ---------- Gravar pelo link ---------- */
|
||
|
||
export function RecordForm({ onChanged, disabled }: { onChanged: () => void; disabled: boolean }) {
|
||
const { pending, message, run } = useClipperAction(onChanged);
|
||
const [url, setUrl] = useState("");
|
||
const titleId = useId();
|
||
const hintId = useId();
|
||
|
||
async function submit(e: FormEvent<HTMLFormElement>) {
|
||
e.preventDefault();
|
||
const done = await run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: url.trim() }),
|
||
(s) => s.kind === "vod" ? `VOD na fila: sessão #${s.id}. Baixando e processando.` : `Gravando: sessão #${s.id}.`);
|
||
if (done) setUrl("");
|
||
}
|
||
|
||
return (
|
||
<section aria-labelledby={titleId} className="grid gap-3 rounded-card border border-line bg-surface px-5 py-4 shadow-card">
|
||
<form onSubmit={submit} className="grid items-center gap-x-8 gap-y-3 lg:grid-cols-[minmax(0,24rem)_minmax(0,1fr)]">
|
||
<div className="flex items-start gap-3">
|
||
<span aria-hidden="true" className="grid size-10 shrink-0 place-items-center rounded-control border border-accent/30 bg-accent-soft text-accent">
|
||
<BroadcastIcon size={18} />
|
||
</span>
|
||
<div className="grid min-w-0 gap-0.5">
|
||
<h2 id={titleId} className="text-[0.9375rem] font-semibold text-fg">Gravar pelo link</h2>
|
||
<p id={hintId} className="text-xs leading-relaxed text-fg-subtle">
|
||
Live no ar: começa a gravar agora. Vídeo (VOD) da Twitch, do YouTube ou da Kick: baixa e processa inteiro.
|
||
</p>
|
||
</div>
|
||
</div>
|
||
<div className="flex min-w-0 items-center gap-2.5">
|
||
<Input type="url" required value={url} onChange={(e) => setUrl(e.target.value)} disabled={disabled}
|
||
aria-label="Link da live ou do VOD" aria-describedby={hintId} placeholder="https://www.twitch.tv/nome ou link de um vídeo"
|
||
className="min-w-0 flex-1" />
|
||
<Button disabled={disabled || pending !== null || !url.trim()} className="shrink-0">
|
||
{pending === "record" ? <Spinner /> : <BroadcastIcon size={16} />}Gravar
|
||
</Button>
|
||
</div>
|
||
</form>
|
||
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||
</section>
|
||
);
|
||
}
|
||
|
||
/* ---------- Cortar agora ---------- */
|
||
|
||
/** Botões "Cortar agora" (últimos 30/45/60 s). O corte manual nunca é descartado pela IA. */
|
||
export function CutNow({ sessionId, pending, run }: { sessionId: number; pending: string | null; run: Run }) {
|
||
return (
|
||
<span role="group" aria-label="Cortar agora: últimos segundos"
|
||
className="inline-flex items-center gap-0.5 rounded-control border border-accent/35 bg-accent-soft p-0.5">
|
||
<span className="flex items-center gap-1.5 px-2 text-[0.8125rem] font-semibold text-accent">
|
||
{pending?.startsWith("cut-") ? <Spinner className="size-3.5" /> : <ScissorsIcon size={15} />}Cortar agora
|
||
</span>
|
||
{CUT_OPTIONS.map((s) => (
|
||
<button key={s} type="button" disabled={pending !== null} aria-label={`Cortar os últimos ${s} segundos`}
|
||
onClick={() => void run(`cut-${s}`, () => clipperCall<Clip>(`sessions/${sessionId}/clips`, "POST", { lastS: s }),
|
||
`Corte manual dos últimos ${s} s criado. Ele vai direto para o render.`)}
|
||
className="h-7 rounded-md px-2.5 text-[0.8125rem] font-semibold text-accent tabular-nums transition-colors hover:bg-accent hover:text-accent-fg focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-45">
|
||
{s} s
|
||
</button>
|
||
))}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
/* ---------- Lista de sessões ---------- */
|
||
|
||
export function SessionList({ sessions, clips, games, nameOf, onChanged, onShowClips, onConfigure, onGamesChanged }: {
|
||
sessions: ClipperSession[];
|
||
clips: Clip[];
|
||
games: Game[];
|
||
nameOf: (s: ClipperSession) => string;
|
||
onChanged: () => void;
|
||
onShowClips: (sessionId: number) => void;
|
||
/** Abre a "Configuração do corte" da sessão. */
|
||
onConfigure: (session: ClipperSession) => void;
|
||
onGamesChanged: (games: Game[]) => void;
|
||
}) {
|
||
const scanIntervalS = useScanInterval();
|
||
if (sessions.length === 0) {
|
||
return (
|
||
<EmptyState compact icon={<BroadcastIcon size={18} />} title="Nenhuma sessão ainda">
|
||
Cole o link de uma live acima, ou ligue o monitor de uma fonte na aba Fontes para gravar sozinho quando ela entrar ao vivo.
|
||
</EmptyState>
|
||
);
|
||
}
|
||
return (
|
||
<ul className="grid gap-4">
|
||
{sessions.map((s) => (
|
||
<li key={s.id}>
|
||
<SessionRow session={s} name={nameOf(s)} clips={clips.filter((c) => c.sessionId === s.id)} games={games} onChanged={onChanged}
|
||
onShowClips={onShowClips} onConfigure={onConfigure} onGamesChanged={onGamesChanged} scanIntervalS={scanIntervalS} />
|
||
</li>
|
||
))}
|
||
</ul>
|
||
);
|
||
}
|
||
|
||
/* ---------- Saúde da sessão ---------- */
|
||
|
||
type Level = "danger" | "warning" | "note";
|
||
type Issue = { level: Level; text: string };
|
||
type Health = { tone: Tone; text: string; full: string };
|
||
|
||
/** Uma frase que responde "está tudo bem com esta sessão?": o pior problema primeiro, observações depois. */
|
||
function sessionHealth(s: ClipperSession, mismatch: boolean): Health {
|
||
const live = s.status === "recording" || s.status === "starting";
|
||
const issues: Issue[] = [];
|
||
const seg = s.segments;
|
||
if (s.status === "error") issues.push({ level: "danger", text: "Parou com erro (detalhe abaixo)" });
|
||
if (s.status === "interrupted") {
|
||
issues.push({ level: "warning", text: "Interrompida: o serviço reiniciou no meio da gravação. Retome ou processe o que já foi gravado" });
|
||
}
|
||
if (s.chatStatus.startsWith("error")) issues.push({ level: "danger", text: `Chat com erro: ${s.chatStatus.replace(/^error:\s*/, "")}` });
|
||
else if (live && s.chatStatus === "connecting") issues.push({ level: "note", text: "conectando ao chat" });
|
||
else if (live && (s.chatStatus === "off" || s.chatStatus === "")) {
|
||
issues.push({ level: "warning", text: "Sem chat: os cortes dependem só do áudio e da IA" });
|
||
}
|
||
const waiting = seg.total - seg.analyzed;
|
||
if (live && waiting > TRANSCRIPT_LATE_SEGMENTS) issues.push({ level: "warning", text: `Transcrição atrasada: ${waiting} trechos na fila` });
|
||
if (live && s.scannedUntilS !== undefined && s.durationS - s.scannedUntilS > SCAN_LATE_S) {
|
||
issues.push({ level: "warning", text: `IA ${formatDuration(s.durationS - s.scannedUntilS)} atrás da gravação` });
|
||
}
|
||
if (mismatch) issues.push({ level: "warning", text: "Confirme o jogo: a tela não bate com a categoria" });
|
||
if (seg.transcriptErrors > 0) {
|
||
// Um ou outro trecho sem fala é normal (silêncio, música); muitos indicam o serviço de voz com problema.
|
||
const many = seg.transcriptErrors > Math.max(2, seg.total * 0.05);
|
||
issues.push({ level: many ? "warning" : "note", text: `${seg.transcriptErrors} trecho${seg.transcriptErrors === 1 ? "" : "s"} sem transcrição` });
|
||
}
|
||
if (live && s.camDetect === null) issues.push({ level: "note", text: "câmera ainda não identificada" });
|
||
|
||
const serious = issues.filter((i) => i.level !== "note");
|
||
const notes = issues.filter((i) => i.level === "note").map((i) => i.text);
|
||
if (serious.length > 0) {
|
||
const tone: Tone = serious.some((i) => i.level === "danger") ? "danger" : "warning";
|
||
const parts = [...serious.map((i) => i.text), ...notes];
|
||
return { tone, text: parts.join(" · "), full: parts.join("\n") };
|
||
}
|
||
const base: { tone: Tone; text: string } =
|
||
s.status === "starting" ? { tone: "info", text: "Iniciando a gravação" }
|
||
: s.status === "recording" ? { tone: "success", text: "Tudo certo: gravando, com o chat e a IA em dia" }
|
||
: s.status === "processing"
|
||
? s.kind === "live"
|
||
? { tone: "info", text: "A gravação parou e a IA está processando o que foi gravado. Se a live continua no ar, use “Retomar gravação”" }
|
||
: { tone: "info", text: "Processando: transcrição, varredura da IA e juízes em andamento" }
|
||
: s.status === "done" ? { tone: "success", text: "Concluída: tudo processado" }
|
||
: { tone: "neutral", text: "Gravação parada" };
|
||
const parts = [base.text, ...notes];
|
||
return { tone: base.tone, text: parts.join(" · "), full: parts.join("\n") };
|
||
}
|
||
|
||
const TONE_TEXT: Record<Tone, string> = {
|
||
neutral: "text-fg-muted", accent: "text-accent", info: "text-info", violet: "text-violet", success: "text-success",
|
||
warning: "text-warning", danger: "text-danger", optionB: "text-option-b", optionC: "text-option-c", optionD: "text-option-d",
|
||
};
|
||
const TONE_FILL: Record<Tone, string> = {
|
||
neutral: "bg-fg-subtle", accent: "bg-accent", info: "bg-info", violet: "bg-violet", success: "bg-success",
|
||
warning: "bg-warning", danger: "bg-danger", optionB: "bg-option-b", optionC: "bg-option-c", optionD: "bg-option-d",
|
||
};
|
||
/** Cor do ícone da plataforma e da borda do cartão, por estado da sessão. */
|
||
const STATUS_FRAME: Record<ClipperSession["status"], { icon: string; border: string }> = {
|
||
starting: { icon: "border-info/35 bg-info-soft text-info", border: "border-info/30" },
|
||
recording: { icon: "border-danger/35 bg-danger-soft text-danger", border: "border-danger/30" },
|
||
processing: { icon: "border-info/35 bg-info-soft text-info", border: "border-info/25" },
|
||
done: { icon: "border-line-strong bg-raised text-fg-muted", border: "border-line" },
|
||
stopped: { icon: "border-line-strong bg-raised text-fg-muted", border: "border-line" },
|
||
error: { icon: "border-danger/35 bg-danger-soft text-danger", border: "border-danger/30" },
|
||
interrupted: { icon: "border-warning/35 bg-warning-soft text-warning", border: "border-warning/30" },
|
||
};
|
||
|
||
/* ---------- Cartão da sessão ---------- */
|
||
|
||
function SessionRow({ session: s, name, clips, games, onChanged, onShowClips, onConfigure, onGamesChanged, scanIntervalS }: {
|
||
session: ClipperSession; name: string; clips: Clip[]; games: Game[]; onChanged: () => void; onShowClips: (id: number) => void;
|
||
onConfigure: (session: ClipperSession) => void; onGamesChanged: (games: Game[]) => void; scanIntervalS: number;
|
||
}) {
|
||
const { pending, message, run } = useClipperAction(onChanged);
|
||
const [chartOpen, setChartOpen] = useState(false);
|
||
const chartId = useId();
|
||
const frame = STATUS_FRAME[s.status];
|
||
const live = s.status === "recording" || s.status === "starting";
|
||
const active = ACTIVE_SESSION.includes(s.status);
|
||
const totalClips = CLIP_STATUS_ORDER.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
|
||
const lastMemory = s.memory?.length ? s.memory[s.memory.length - 1] : null;
|
||
const confirmedGame = s.gameSource === "user";
|
||
const mismatch = Boolean(s.game && s.screenGame && !confirmedGame && gameIdOf(s.screenGame) !== gameIdOf(s.game));
|
||
const health = sessionHealth(s, mismatch);
|
||
const showNow = Boolean(lastMemory?.summary) || s.game !== undefined;
|
||
// Relógio da gravação: anda a cada segundo só enquanto grava; os números que dependem dele se inscrevem sozinhos.
|
||
const clock = useRecordingClock(s.durationS, s.status === "recording");
|
||
|
||
return (
|
||
<article aria-label={`Sessão ${s.id}: ${name}`}
|
||
// contain: a largura do cartão vem da página, nunca do texto (linhas truncadas longas não alargam a tela).
|
||
className={cx("overflow-hidden rounded-card border bg-surface shadow-card [contain:inline-size]", frame.border)}>
|
||
{/* 1. Quem, estado, tempo e ações principais */}
|
||
<header className="flex flex-wrap items-start gap-x-5 gap-y-3 px-5 pt-4 pb-3">
|
||
<span className={cx("grid size-11 shrink-0 place-items-center rounded-control border", frame.icon)}>
|
||
<PlatformIcon platform={s.platform} size={20} />
|
||
</span>
|
||
<div className="grid min-w-[min(100%,18rem)] flex-1 gap-1">
|
||
<p className="flex flex-wrap items-center gap-2">
|
||
<span className="font-display text-[1.0625rem] leading-tight font-semibold text-fg">{name}</span>
|
||
<StatusBadge status={s.status} clock={clock} />
|
||
<Badge dot={false}>{s.kind === "vod" ? "VOD" : "live"}</Badge>
|
||
</p>
|
||
<p className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
|
||
<span>#{s.id}</span><Dot /><span>{PLATFORM_LABEL[s.platform]}</span><Dot />
|
||
<span>início {formatDate(s.startedAt)}</span><Dot />
|
||
<CaptureState session={s} live={live} />
|
||
<a href={s.url} target="_blank" rel="noreferrer noopener"
|
||
className="max-w-72 truncate rounded-sm hover:text-fg hover:underline focus-visible:outline-2 focus-visible:outline-accent">
|
||
{s.url.replace(/^https?:\/\/(www\.)?/, "")}
|
||
</a>
|
||
</p>
|
||
{s.title && <p className="truncate text-[0.8125rem] text-fg-muted" title={s.title}>{s.title}</p>}
|
||
</div>
|
||
{/* Largura fixa: o relógio anda a cada segundo e o rótulo troca para o aviso sem empurrar nada. */}
|
||
<div className="grid w-[8.5rem] shrink-0 justify-items-end gap-0.5 text-right">
|
||
<span className="font-display text-2xl leading-none font-semibold text-fg tabular-nums"><ClockText clock={clock} /></span>
|
||
<ClockLabel clock={clock} live={live} />
|
||
</div>
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
{live && s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
|
||
{active && (
|
||
<Button variant="secondary" size="sm" disabled={pending !== null}
|
||
onClick={async () => {
|
||
if (!(await askConfirm({ title: `Parar a sessão #${s.id}?`,
|
||
message: "A gravação para; o que já foi gravado continua sendo analisado.", confirmLabel: "Parar" }))) return;
|
||
void run("stop", () => clipperCall(`sessions/${s.id}/stop`, "POST"), "Sessão parada.");
|
||
}}>
|
||
{pending === "stop" ? <Spinner className="size-3.5" /> : <StopIcon size={15} />}Parar
|
||
</Button>
|
||
)}
|
||
{/* Interrompida = o serviço reiniciou no meio da gravação. Retomar continua NA MESMA sessão (a parte perdida
|
||
durante o reinício não existe na gravação); processar encerra e deixa a IA analisar o que foi gravado.
|
||
Live em "processando" (retomada automática falhou, live ainda no ar) também pode voltar a gravar: o serviço
|
||
confere se o canal está no ar e devolve erro legível se não estiver. */}
|
||
{s.kind === "live" && !live && (
|
||
<Button variant={s.status === "interrupted" ? "primary" : "secondary"} size="sm" disabled={pending !== null}
|
||
title="Se a live ainda está no ar, volta a gravar nesta mesma sessão."
|
||
onClick={() => void run("resume", () => clipperCall(`sessions/${s.id}/resume`, "POST"), "Gravação retomada.")}>
|
||
{pending === "resume" ? <Spinner className="size-3.5" /> : <BroadcastIcon size={15} />}Retomar gravação
|
||
</Button>
|
||
)}
|
||
{["interrupted", "stopped", "error"].includes(s.status) && (
|
||
<Button variant="secondary" size="sm" disabled={pending !== null}
|
||
title="Encerra e manda a IA analisar o que já foi gravado (varredura, juízes e render)."
|
||
onClick={() => void run("finish", () => clipperCall(`sessions/${s.id}/finish`, "POST"), "Processando o que foi gravado.")}>
|
||
{pending === "finish" ? <Spinner className="size-3.5" /> : <SparkIcon size={15} />}Processar o que foi gravado
|
||
</Button>
|
||
)}
|
||
<Button variant="ghost" size="sm" disabled={pending !== null} aria-label={`Apagar a sessão ${s.id}`}
|
||
className="hover:bg-danger-soft hover:text-danger"
|
||
onClick={async () => {
|
||
if (!(await askConfirm({ title: `Apagar a sessão #${s.id}?`,
|
||
message: "A gravação e TODOS os cortes dela (inclusive aprovados) são apagados. Não dá para desfazer.",
|
||
confirmLabel: "Apagar sessão", tone: "danger" }))) return;
|
||
void run("delete", () => clipperCall(`sessions/${s.id}`, "DELETE"), "Sessão apagada.");
|
||
}}>
|
||
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
|
||
</Button>
|
||
</div>
|
||
</header>
|
||
|
||
{/* 2. Saúde em uma frase (uma linha só: o texto muda, a altura não) */}
|
||
<p title={health.full}
|
||
className={cx("mx-5 flex h-9 items-center gap-2 rounded-control border px-3 text-[0.8125rem] font-medium",
|
||
health.tone === "success" ? "border-success/20 bg-success-soft/50"
|
||
: health.tone === "warning" ? "border-warning/25 bg-warning-soft/60"
|
||
: health.tone === "danger" ? "border-danger/30 bg-danger-soft/60"
|
||
: health.tone === "info" ? "border-info/20 bg-info-soft/50" : "border-line bg-raised/50",
|
||
TONE_TEXT[health.tone])}>
|
||
{health.tone === "success" ? <CheckIcon size={15} className="shrink-0" />
|
||
: health.tone === "warning" || health.tone === "danger" ? <AlertIcon size={15} className="shrink-0" />
|
||
: active ? <Spinner className="size-3.5 shrink-0" /> : <BroadcastIcon size={15} className="shrink-0" />}
|
||
<span className="min-w-0 truncate">{health.text}</span>
|
||
</p>
|
||
|
||
<div className="grid gap-4 px-5 pt-4 pb-5">
|
||
{/* 3. O que está acontecendo: resumo da IA + jogo */}
|
||
{showNow && (
|
||
<section aria-label="O que está acontecendo" className="grid rounded-control border border-line bg-raised/40">
|
||
{lastMemory?.summary && (
|
||
<div className="flex items-start gap-2.5 px-4 py-3">
|
||
<SparkIcon size={15} className="mt-0.5 shrink-0 text-violet" />
|
||
{/* Duas linhas reservadas: o resumo novo (a cada 3 min) não muda a altura do cartão. */}
|
||
<p className="line-clamp-2 min-h-[2lh] min-w-0 flex-1 text-[0.8125rem] leading-relaxed text-fg-muted" title={lastMemory.summary}>
|
||
<span className="font-semibold text-violet">{live ? "Agora na live" : "Último resumo da IA"}</span>
|
||
<span className="text-fg-subtle tabular-nums"> · {formatClock(lastMemory.fromS)}–{formatClock(lastMemory.toS)}</span>
|
||
<span className="text-fg-subtle">: </span>{lastMemory.summary}
|
||
</p>
|
||
<SummaryCadence clock={clock} live={live} scannedUntilS={s.scannedUntilS ?? null} intervalS={scanIntervalS} />
|
||
</div>
|
||
)}
|
||
{s.game !== undefined && (
|
||
<div className={cx("px-4 py-2", lastMemory?.summary && "border-t border-line")}>
|
||
<SessionGame session={s} games={games} onChanged={onChanged} onGamesChanged={onGamesChanged} />
|
||
</div>
|
||
)}
|
||
</section>
|
||
)}
|
||
|
||
{/* 4. Saúde do pipeline: quatro blocos com a mesma estrutura (rótulo/estado, número, barra, detalhe) */}
|
||
<dl className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||
<ChatTile session={s} live={live} />
|
||
<TranscriptTile session={s} live={live} active={active} />
|
||
<ScanTile session={s} live={live} active={active} clock={clock} intervalS={scanIntervalS} />
|
||
<ClipsTile session={s} total={totalClips} active={active} />
|
||
</dl>
|
||
|
||
{s.error && <p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 font-mono text-xs break-words text-danger">{s.error}</p>}
|
||
</div>
|
||
|
||
{/* 5. Ferramentas: tudo o que é secundário num lugar só. Os painéis abertos (gráfico, emotes) ocupam a linha toda abaixo. */}
|
||
<div role="group" aria-label="Ferramentas da sessão"
|
||
className="flex flex-wrap items-center gap-2 border-t border-line bg-sunken/40 px-5 py-2.5">
|
||
<Button variant="secondary" size="sm" onClick={() => onConfigure(s)}>
|
||
<SettingsIcon size={15} />Configurar corte
|
||
{s.hasOwnSettings && <><span aria-hidden="true" className="size-1.5 rounded-full bg-accent" /><span className="sr-only">(com ajustes próprios)</span></>}
|
||
</Button>
|
||
<CameraState session={s} live={live} />
|
||
<span aria-hidden="true" className="mx-1 h-5 w-px bg-line-strong" />
|
||
{totalClips > 0 && (
|
||
<Button variant="ghost" size="sm" onClick={() => onShowClips(s.id)}><ScissorsIcon size={15} />Ver cortes desta sessão</Button>
|
||
)}
|
||
<Button variant="ghost" size="sm" aria-expanded={chartOpen} aria-controls={chartId} onClick={() => setChartOpen((o) => !o)}>
|
||
<ChartIcon size={15} />Gráfico do chat
|
||
<ChevronDownIcon size={14} className={cx("transition-transform motion-reduce:transition-none", chartOpen && "rotate-180")} />
|
||
</Button>
|
||
{/* O painel de emotes (clipper-games) traz o próprio botão e a tabela: `contents` põe os dois direto nesta
|
||
linha — o botão ao lado dos outros e a tabela, quando aberta, na linha de baixo inteira. */}
|
||
{s.game !== undefined && (
|
||
<div className="contents [&>div]:contents [&>div>div:nth-child(2)]:order-last [&>div>div:nth-child(2)]:basis-full [&>div>div:nth-child(2)]:pt-1 [&>div>div:nth-child(2)]:pb-2">
|
||
<ChannelEmotes channelKey={channelKeyOf(s)} />
|
||
</div>
|
||
)}
|
||
{chartOpen && <div id={chartId} className="order-last basis-full pt-1 pb-2"><SessionTimeline session={s} clips={clips} /></div>}
|
||
</div>
|
||
|
||
<div aria-live="polite" className="px-5 empty:hidden [&:not(:empty)]:pb-4">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||
</article>
|
||
);
|
||
}
|
||
|
||
function Dot() {
|
||
return <span aria-hidden="true" className="text-line-strong">·</span>;
|
||
}
|
||
|
||
/* ---------- Relógio da gravação ---------- */
|
||
|
||
// O `durationS` do serviço só sobe quando um bloco .ts fecha (a cada 30 s) e a página consulta a cada 5 s. Enquanto
|
||
// grava, o relógio anda sozinho a partir do último valor real e da hora em que ele chegou, com um teto para não
|
||
// inventar tempo: passou do teto sem bloco novo, ele para e o cartão mostra que está esperando.
|
||
|
||
/** Quanto o relógio pode andar além do último `durationS` real (um bloco de 30 s + a consulta de 5 s + folga). */
|
||
const CLOCK_MAX_AHEAD_S = 45;
|
||
/** Passo da conferência: curto para o segundo virar no momento certo; só avisa quem lê quando o número muda. */
|
||
const CLOCK_TICK_MS = 250;
|
||
/** Ao voltar à aba, a página reconsulta o serviço: espera isso antes de acusar "aguardando" pelo tempo escondido. */
|
||
const CLOCK_VISIBLE_GRACE_MS = 6000;
|
||
|
||
class RecordingClock {
|
||
private realS: number;
|
||
private running: boolean;
|
||
private receivedAt = performance.now();
|
||
private visibleSince = performance.now();
|
||
private shown: number;
|
||
private stalled = false;
|
||
private mounted = false;
|
||
private timer: ReturnType<typeof setInterval> | null = null;
|
||
private readonly listeners = new Set<() => void>();
|
||
|
||
constructor(realS: number, running: boolean) {
|
||
this.realS = realS;
|
||
this.running = running;
|
||
this.shown = running ? Math.floor(realS) : realS;
|
||
}
|
||
|
||
readonly subscribe = (listener: () => void) => {
|
||
this.listeners.add(listener);
|
||
return () => { this.listeners.delete(listener); };
|
||
};
|
||
/** Segundos exibidos: nunca voltam enquanto grava. Parado, é o valor real. */
|
||
readonly getShown = () => this.shown;
|
||
/** Chegou ao teto sem bloco novo: o relógio está parado esperando o serviço. */
|
||
readonly getStalled = () => this.stalled;
|
||
|
||
/** Estimativa contínua da gravação agora (já com o teto). */
|
||
estimate(): number {
|
||
return this.running ? this.realS + Math.min(CLOCK_MAX_AHEAD_S, (performance.now() - this.receivedAt) / 1000) : this.realS;
|
||
}
|
||
|
||
/** Valor novo da consulta. Menor que o exibido: o exibido segura até a estimativa alcançar; maior: pula. */
|
||
sync(realS: number, running: boolean) {
|
||
if (realS !== this.realS || running !== this.running) {
|
||
this.realS = realS;
|
||
this.receivedAt = performance.now();
|
||
}
|
||
this.running = running;
|
||
this.schedule();
|
||
this.update();
|
||
}
|
||
|
||
/** Liga o passo do relógio (só com o cartão na tela); devolve a limpeza. */
|
||
mount() {
|
||
this.mounted = true;
|
||
this.visibleSince = performance.now();
|
||
document.addEventListener("visibilitychange", this.onVisibility);
|
||
this.schedule();
|
||
this.update();
|
||
return () => {
|
||
this.mounted = false;
|
||
document.removeEventListener("visibilitychange", this.onVisibility);
|
||
this.schedule();
|
||
};
|
||
}
|
||
|
||
private readonly onVisibility = () => {
|
||
if (document.visibilityState === "visible") this.visibleSince = performance.now();
|
||
this.schedule();
|
||
this.update();
|
||
};
|
||
|
||
/** Um intervalo só, e só enquanto grava com a aba visível. */
|
||
private schedule() {
|
||
const wanted = this.mounted && this.running && document.visibilityState === "visible";
|
||
if (wanted && this.timer === null) this.timer = setInterval(this.update, CLOCK_TICK_MS);
|
||
else if (!wanted && this.timer !== null) {
|
||
clearInterval(this.timer);
|
||
this.timer = null;
|
||
}
|
||
}
|
||
|
||
private readonly update = () => {
|
||
let shown = this.realS;
|
||
let stalled = false;
|
||
if (this.running) {
|
||
const now = performance.now();
|
||
const elapsed = (now - this.receivedAt) / 1000;
|
||
shown = Math.max(Math.floor(this.shown), Math.floor(this.realS + Math.min(CLOCK_MAX_AHEAD_S, elapsed)));
|
||
stalled = elapsed >= CLOCK_MAX_AHEAD_S && now - this.visibleSince >= CLOCK_VISIBLE_GRACE_MS;
|
||
}
|
||
if (shown === this.shown && stalled === this.stalled) return;
|
||
this.shown = shown;
|
||
this.stalled = stalled;
|
||
for (const listener of this.listeners) listener();
|
||
};
|
||
}
|
||
|
||
/** Um relógio por cartão. O cartão não re-renderiza a cada segundo: só os números inscritos nele. */
|
||
function useRecordingClock(durationS: number, running: boolean): RecordingClock {
|
||
const [clock] = useState(() => new RecordingClock(durationS, running));
|
||
// Antes da pintura: o valor novo da consulta não aparece um quadro atrasado.
|
||
useLayoutEffect(() => { clock.sync(durationS, running); }, [clock, durationS, running]);
|
||
useEffect(() => clock.mount(), [clock]);
|
||
return clock;
|
||
}
|
||
|
||
function useClockShown(clock: RecordingClock): number {
|
||
return useSyncExternalStore(clock.subscribe, clock.getShown, clock.getShown);
|
||
}
|
||
|
||
function useClockStalled(clock: RecordingClock): boolean {
|
||
return useSyncExternalStore(clock.subscribe, clock.getStalled, clock.getStalled);
|
||
}
|
||
|
||
function ClockText({ clock }: { clock: RecordingClock }) {
|
||
return <>{formatClock(useClockShown(clock))}</>;
|
||
}
|
||
|
||
function ClockLabel({ clock, live }: { clock: RecordingClock; live: boolean }) {
|
||
const stalled = useClockStalled(clock);
|
||
if (stalled) {
|
||
return (
|
||
<span className="max-w-full truncate text-xs font-medium text-warning"
|
||
title={`Nenhum bloco novo há mais de ${CLOCK_MAX_AHEAD_S} s: o relógio parou no último tempo provável e espera a gravação.`}>
|
||
aguardando o bloco
|
||
</span>
|
||
);
|
||
}
|
||
return <span className="max-w-full truncate text-xs text-fg-subtle">{live ? "gravados" : "de duração"}</span>;
|
||
}
|
||
|
||
/** Selo do estado. Gravando sem bloco novo além do teto: mesmo texto (a largura não muda), em alerta e sem pulsar. */
|
||
function StatusBadge({ status, clock }: { status: ClipperSession["status"]; clock: RecordingClock }) {
|
||
const stalled = useClockStalled(clock) && status === "recording";
|
||
const info = SESSION_STATUS[status];
|
||
return (
|
||
<span className="inline-flex" title={stalled ? "A gravação não entrega um bloco novo há mais do que o esperado." : undefined}>
|
||
<Badge tone={stalled ? "warning" : info.tone} pulse={!stalled && info.pulse}>{info.label}</Badge>
|
||
</span>
|
||
);
|
||
}
|
||
|
||
/* ---------- Cadência do resumo ---------- */
|
||
|
||
/** Intervalo da varredura em uso no serviço (`judge.options.scanIntervalS` em /status), lido uma vez por montagem. */
|
||
function useScanInterval(): number {
|
||
const [intervalS, setIntervalS] = useState(SCAN_WINDOW_S);
|
||
useEffect(() => {
|
||
let cancelled = false;
|
||
void clipperCall<{ judge?: { options?: JudgeOptions } }>("status").then((r) => {
|
||
const value = r.ok ? r.data.judge?.options?.scanIntervalS : undefined;
|
||
if (!cancelled && typeof value === "number" && value > 0) setIntervalS(value);
|
||
});
|
||
return () => { cancelled = true; };
|
||
}, []);
|
||
return intervalS;
|
||
}
|
||
|
||
/**
|
||
* Quando vem o próximo resumo. No serviço (intel.scan_due/scan_session), a janela seguinte é
|
||
* [scannedUntilS, scannedUntilS + intervalo]; ela só é varrida quando a transcrição passa do fim dela, o laço da
|
||
* varredura confere a cada 20 s (worker._scan_loop) e a IA leva o tempo da CLI. Só então o resumo e o
|
||
* `scannedUntilS` são gravados. Por isso a previsão = fim da janela + a demora da IA medida nesta tela (a diferença
|
||
* entre o relógio e o novo `scannedUntilS` quando ele avança); antes da 1ª medida, conta só até o fim da janela.
|
||
*/
|
||
function SummaryCadence({ clock, live, scannedUntilS, intervalS }: {
|
||
clock: RecordingClock; live: boolean; scannedUntilS: number | null; intervalS: number;
|
||
}) {
|
||
const shown = useClockShown(clock);
|
||
const [seen, setSeen] = useState({ scannedUntilS, delayS: 0 });
|
||
if (scannedUntilS !== seen.scannedUntilS) {
|
||
// Estado derivado (padrão do React para "valor anterior"): mede a demora só quando a janela avança uma vez.
|
||
const stepped = seen.scannedUntilS !== null && scannedUntilS !== null && scannedUntilS > seen.scannedUntilS;
|
||
setSeen({
|
||
scannedUntilS,
|
||
delayS: stepped ? Math.min(intervalS, Math.max(0, clock.estimate() - (scannedUntilS ?? 0))) : seen.delayS,
|
||
});
|
||
}
|
||
const cadence = `atualiza a cada ${formatDuration(intervalS)}`;
|
||
let next: string;
|
||
let tone = "text-fg-subtle";
|
||
if (!live || scannedUntilS === null) next = "último resumo";
|
||
else {
|
||
const remaining = scannedUntilS + intervalS + seen.delayS - shown;
|
||
if (remaining >= 1) next = `próximo em ${formatClock(remaining)}`;
|
||
else { next = "gerando o próximo resumo…"; tone = "text-violet"; }
|
||
}
|
||
return (
|
||
// Largura e duas linhas fixas, dentro da altura das duas linhas do resumo: a contagem não empurra o texto.
|
||
<p className="grid w-48 shrink-0 text-right text-xs leading-5 tabular-nums">
|
||
<span className="truncate text-fg-subtle">{live ? cadence : "fora de gravação"}</span>
|
||
<span className={cx("truncate", tone)}>{next}</span>
|
||
</p>
|
||
);
|
||
}
|
||
|
||
/** Resolução gravada de fato (1º bloco). Ao vivo sem bloco ainda: aviso no mesmo lugar, para a linha não mudar de forma. */
|
||
function CaptureState({ session: s, live }: { session: ClipperSession; live: boolean }) {
|
||
if (s.capture === undefined || (s.capture === null && !live)) return null; // serviço antigo ou sessão antiga
|
||
if (s.capture === null) return <><span>resolução: aguardando o 1º bloco</span><Dot /></>;
|
||
const c = s.capture;
|
||
const detail = [`pedido: ${CAPTURE_ASKED[c.quality] ?? c.quality}`, c.codec.toUpperCase(),
|
||
c.gbPerHour ? `≈ ${gbPerHourLabel(c.gbPerHour)}` : "", c.mixed ? "há trechos gravados em outra resolução" : ""].filter(Boolean).join(" · ");
|
||
return (
|
||
<>
|
||
<span title={`Gravação: ${captureLabel(c)} · ${detail}`} className={cx("tabular-nums", c.mixed && "text-warning")}>
|
||
{live ? "gravando em" : "gravado em"} <span className="font-mono text-fg-muted">{captureLabel(c)}</span>
|
||
</span>
|
||
<Dot />
|
||
</>
|
||
);
|
||
}
|
||
|
||
const CAPTURE_ASKED: Record<string, string> = {
|
||
best: "melhor disponível", "1440p": "até 1440p", "1080p": "até 1080p", "720p": "até 720p", "480p": "até 480p",
|
||
};
|
||
|
||
/** Câmera do streamer: achada pela IA, pelo rosto, marcada à mão, ausente ou ainda não procurada. */
|
||
function CameraState({ session: s, live }: { session: ClipperSession; live: boolean }) {
|
||
if (s.camDetect === undefined) return null; // serviço antigo: não há detecção
|
||
if (s.camDetect === null) {
|
||
return <Badge tone={live ? "warning" : "neutral"}>{live ? "câmera ainda não identificada" : "câmera não marcada"}</Badge>;
|
||
}
|
||
const c = s.camDetect;
|
||
return (
|
||
<Badge tone={c.hasWebcam || c.source === "manual" ? "success" : "neutral"}>
|
||
{c.source === "manual" ? "câmera marcada por você"
|
||
: !c.hasWebcam ? "sem webcam na tela"
|
||
: c.source === "yunet" ? "câmera achada (rosto, sem IA)" : "câmera achada pela IA"}
|
||
</Badge>
|
||
);
|
||
}
|
||
|
||
/* ---------- Blocos do pipeline ---------- */
|
||
|
||
/** Bloco de altura fixa: cabeçalho (rótulo + estado), número grande, barra (ou espaço reservado) e uma linha de detalhe. */
|
||
function Tile({ icon, label, state, value, unit, meter, detail, detailTone }: {
|
||
icon: ReactNode; label: string; state: { tone: Tone; text: string; pulse?: boolean };
|
||
value: ReactNode; unit?: ReactNode; meter?: ReactNode; detail: ReactNode; detailTone?: Tone;
|
||
}) {
|
||
return (
|
||
<div className="grid min-w-0 content-start gap-2.5 rounded-control border border-line bg-raised/40 px-4 py-3">
|
||
<dt className="flex items-center justify-between gap-2">
|
||
<span className="flex items-center gap-1.5 text-eyebrow font-semibold text-fg-subtle uppercase">{icon}{label}</span>
|
||
<Badge tone={state.tone} pulse={state.pulse}>{state.text}</Badge>
|
||
</dt>
|
||
<dd className="grid gap-2.5">
|
||
<p className="flex min-w-0 items-baseline gap-1.5">
|
||
<span className="font-display text-[1.625rem] leading-none font-semibold text-fg tabular-nums">{value}</span>
|
||
{unit && <span className="truncate text-xs text-fg-subtle tabular-nums">{unit}</span>}
|
||
</p>
|
||
<div className="h-1.5">{meter}</div>
|
||
<p className={cx("truncate text-xs tabular-nums", detailTone ? TONE_TEXT[detailTone] : "text-fg-subtle")}
|
||
title={typeof detail === "string" ? detail : undefined}>
|
||
{detail}
|
||
</p>
|
||
</dd>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function ChatTile({ session: s, live }: { session: ClipperSession; live: boolean }) {
|
||
const chat = chatStatusInfo(s.chatStatus);
|
||
const error = s.chatStatus.startsWith("error") ? s.chatStatus.replace(/^error:\s*/, "") : null;
|
||
// Rótulo curto no selo; o texto completo do estado vai para a linha de detalhe.
|
||
const short = s.chatStatus === "connected" ? "conectado" : s.chatStatus === "connecting" ? "conectando"
|
||
: s.chatStatus === "unsupported" ? "sem chat" : error ? "erro" : "desligado";
|
||
return (
|
||
<Tile icon={<ChatIcon size={13} />} label="Chat" state={{ tone: chat.tone, text: short, pulse: live && s.chatStatus === "connected" }}
|
||
value={formatInteger(s.chatMessages)} unit={`mensage${s.chatMessages === 1 ? "m" : "ns"}`}
|
||
detail={error ?? (s.chatStatus === "unsupported" ? "a plataforma não tem chat para ler"
|
||
: live && s.chatStatus === "connected" ? "lendo em tempo real" : chat.label)}
|
||
detailTone={error ? "danger" : undefined} />
|
||
);
|
||
}
|
||
|
||
function TranscriptTile({ session: s, live, active }: { session: ClipperSession; live: boolean; active: boolean }) {
|
||
const seg = s.segments;
|
||
const waiting = seg.total - seg.analyzed;
|
||
const state: { tone: Tone; text: string; pulse?: boolean } =
|
||
seg.total === 0 ? (active ? { tone: "info", text: "esperando", pulse: true } : { tone: "neutral", text: "vazia" })
|
||
: waiting <= 0 ? { tone: "success", text: "em dia" }
|
||
: live && waiting > TRANSCRIPT_LATE_SEGMENTS ? { tone: "warning", text: "atrasada" }
|
||
: active ? { tone: "info", text: `${waiting} na fila`, pulse: true } : { tone: "neutral", text: `${waiting} pendentes` };
|
||
return (
|
||
<Tile icon={<MicIcon size={13} />} label="Transcrição" state={state}
|
||
value={formatInteger(seg.analyzed)} unit={`de ${formatInteger(seg.total)} trecho${seg.total === 1 ? "" : "s"} de 30 s`}
|
||
meter={<ProgressBar value={seg.total ? seg.analyzed / seg.total : active ? undefined : 0} label={`Trechos analisados da sessão ${s.id}`} />}
|
||
detail={seg.transcriptErrors > 0
|
||
? `${seg.transcriptErrors} trecho${seg.transcriptErrors === 1 ? "" : "s"} sem fala reconhecida`
|
||
: "fala e volume de cada trecho"}
|
||
detailTone={seg.transcriptErrors > 0 ? "warning" : undefined} />
|
||
);
|
||
}
|
||
|
||
function ScanTile({ session: s, live, active, clock, intervalS }: {
|
||
session: ClipperSession; live: boolean; active: boolean; clock: RecordingClock; intervalS: number;
|
||
}) {
|
||
const scanned = s.scannedUntilS ?? null;
|
||
if (scanned === null) {
|
||
return (
|
||
<Tile icon={<EyeIcon size={13} />} label="IA assistiu" state={{ tone: "neutral", text: "desligada" }}
|
||
value="—" detail="varredura da IA desligada nesta sessão" />
|
||
);
|
||
}
|
||
const lag = Math.max(0, s.durationS - scanned);
|
||
const state: { tone: Tone; text: string; pulse?: boolean } =
|
||
live ? (lag > SCAN_LATE_S ? { tone: "warning", text: "atrasada" } : { tone: "success", text: "em dia" })
|
||
: lag < SCAN_WINDOW_S ? { tone: "success", text: "completa" }
|
||
: active ? { tone: "info", text: "assistindo", pulse: true } : { tone: "neutral", text: "parcial" };
|
||
return (
|
||
<Tile icon={<EyeIcon size={13} />} label="IA assistiu" state={state}
|
||
// O quanto a IA assistiu é sempre o real; só o total ("de H:MM:SS") acompanha o relógio da gravação.
|
||
value={formatClock(scanned)} unit={<>de <ClockText clock={clock} /></>}
|
||
meter={<ProgressBar value={s.durationS > 0 ? scanned / s.durationS : 0} label={`Quanto da sessão ${s.id} a IA já assistiu`} />}
|
||
detail={live ? `olha janelas de ${formatDuration(intervalS)} · ${lag < 1 ? "em dia" : `${formatDuration(lag)} atrás`}`
|
||
: lag < SCAN_WINDOW_S ? "assistiu a sessão inteira" : `faltam ${formatDuration(lag)}`}
|
||
detailTone={live && lag > SCAN_LATE_S ? "warning" : undefined} />
|
||
);
|
||
}
|
||
|
||
/** Estados que entram no detalhe do bloco de cortes (o "pronto para aprovar" é o número grande). */
|
||
const CLIP_DETAIL_ORDER: ClipStatus[] = CLIP_STATUS_ORDER.filter((k) => k !== "ready");
|
||
const CLIP_IN_PROGRESS: ClipStatus[] = ["candidate", "pending", "rendering"];
|
||
|
||
function ClipsTile({ session: s, total, active }: { session: ClipperSession; total: number; active: boolean }) {
|
||
const ready = s.clips.ready ?? 0;
|
||
const working = CLIP_IN_PROGRESS.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
|
||
const parts = CLIP_DETAIL_ORDER.filter((k) => (s.clips[k] ?? 0) > 0).map((k) => `${s.clips[k]} ${CLIP_STATUS[k].label}`);
|
||
const state: { tone: Tone; text: string; pulse?: boolean } =
|
||
working > 0 ? { tone: "violet", text: `IA avaliando ${working}`, pulse: true }
|
||
: total > 0 ? { tone: "neutral", text: `${total} no total` }
|
||
: { tone: "neutral", text: active ? "nenhum ainda" : "nenhum" };
|
||
return (
|
||
<Tile icon={<ScissorsIcon size={13} />} label="Cortes" state={state}
|
||
value={<span className={ready > 0 ? "text-accent" : undefined}>{formatInteger(ready)}</span>} unit="para aprovar"
|
||
meter={total > 0 ? (
|
||
<div role="img" aria-label={`Cortes da sessão ${s.id} por estado: ${[`${ready} pronto para aprovar`, ...parts].join(", ")}`}
|
||
className="flex h-1.5 w-full gap-px overflow-hidden rounded-full bg-overlay">
|
||
{CLIP_STATUS_ORDER.filter((k) => (s.clips[k] ?? 0) > 0).map((k) => (
|
||
<span key={k} className={cx("h-full", TONE_FILL[CLIP_STATUS[k].tone])} style={{ width: `${((s.clips[k] ?? 0) / total) * 100}%` }} />
|
||
))}
|
||
</div>
|
||
) : <div className="h-1.5 w-full rounded-full bg-overlay" />}
|
||
detail={parts.length ? parts.join(" · ") : total > 0 ? "todos prontos para aprovar" : active ? "a IA ainda não achou um momento" : "nenhum corte nesta sessão"} />
|
||
);
|
||
}
|
||
|
||
/* ---------- Gráfico de mensagens/s ---------- */
|
||
|
||
/** Pontos no máximo: sessões de horas são agrupadas (máximo de cada grupo) para o SVG ficar leve. */
|
||
const MAX_POINTS = 480;
|
||
const CHART_H = 100;
|
||
|
||
function SessionTimeline({ session, clips }: { session: ClipperSession; clips: Clip[] }) {
|
||
const [data, setData] = useState<Timeline | null>(null);
|
||
const [error, setError] = useState<string | null>(null);
|
||
const live = ACTIVE_SESSION.includes(session.status);
|
||
// Ao vivo, o gráfico acompanha a duração (que muda a cada consulta da página).
|
||
const refreshKey = live ? Math.floor(session.durationS / 30) : 0;
|
||
|
||
useEffect(() => {
|
||
let cancelled = false;
|
||
void clipperCall<Timeline>(`sessions/${session.id}/timeline`).then((r) => {
|
||
if (cancelled) return;
|
||
if (r.ok) { setData(r.data); setError(null); } else setError(r.error);
|
||
});
|
||
return () => { cancelled = true; };
|
||
}, [session.id, refreshKey]);
|
||
|
||
if (error) return <Feedback ok={false}>Não deu para ler o gráfico: {error}</Feedback>;
|
||
if (!data) return <p role="status" className="flex items-center gap-2 text-xs text-fg-muted"><Spinner className="size-3.5" />Carregando o gráfico…</p>;
|
||
if (data.messagesPerS.length === 0 || data.durationS <= 0) {
|
||
return <p className="text-xs text-fg-subtle">Sem mensagens de chat registradas nesta sessão.</p>;
|
||
}
|
||
|
||
const series = data.messagesPerS;
|
||
const bucket = Math.max(1, Math.ceil(series.length / MAX_POINTS));
|
||
const points: number[] = [];
|
||
for (let i = 0; i < series.length; i += bucket) points.push(Math.max(...series.slice(i, i + bucket)));
|
||
const peak = Math.max(1, ...points);
|
||
const width = points.length;
|
||
const secondsPerPoint = data.durationS / width;
|
||
const y = (v: number) => CHART_H - (v / peak) * (CHART_H - 6);
|
||
const area = `M0 ${CHART_H} ${points.map((v, i) => `L${i} ${y(v).toFixed(1)} L${i + 1} ${y(v).toFixed(1)}`).join(" ")} L${width} ${CHART_H} Z`;
|
||
const x = (s: number) => Math.min(width, Math.max(0, s / secondsPerPoint));
|
||
const ticks = [0, 0.25, 0.5, 0.75, 1];
|
||
|
||
return (
|
||
<figure className="grid gap-2">
|
||
<div className="relative rounded-control border border-line bg-sunken/50 p-2">
|
||
<svg viewBox={`0 0 ${width} ${CHART_H}`} preserveAspectRatio="none" className="block h-28 w-full" role="img"
|
||
aria-label={`Mensagens por segundo ao longo de ${formatClock(data.durationS)}; pico de ${peak} por segundo; ${clips.length} corte${clips.length === 1 ? "" : "s"} marcado${clips.length === 1 ? "" : "s"}.`}>
|
||
{clips.map((c) => (
|
||
<rect key={c.id} x={x(c.startS)} y={0} width={Math.max(0.6, x(c.endS) - x(c.startS))} height={CHART_H}
|
||
fill={c.status === "discarded" || c.status === "rejected" ? "var(--color-fg-subtle)" : "var(--color-accent)"}
|
||
opacity={c.status === "discarded" || c.status === "rejected" ? 0.12 : 0.2}>
|
||
<title>{`Corte ${c.id} · ${CLIP_STATUS[c.status].label} · ${formatClock(c.startS)}–${formatClock(c.endS)}`}</title>
|
||
</rect>
|
||
))}
|
||
<path d={area} fill="var(--color-option-b)" fillOpacity={0.35} stroke="var(--color-option-b)" strokeWidth={1}
|
||
vectorEffect="non-scaling-stroke" />
|
||
{clips.map((c) => (
|
||
<line key={`p${c.id}`} x1={x(c.peakS)} x2={x(c.peakS)} y1={0} y2={CHART_H} stroke="var(--color-accent)" strokeWidth={1.5}
|
||
vectorEffect="non-scaling-stroke" />
|
||
))}
|
||
</svg>
|
||
</div>
|
||
<div className="relative h-4 text-[0.6875rem] text-fg-subtle tabular-nums" aria-hidden="true">
|
||
{ticks.map((t) => (
|
||
<span key={t} className={cx("absolute top-0", t === 0 ? "left-2" : t === 1 ? "right-2" : "-translate-x-1/2")}
|
||
style={t > 0 && t < 1 ? { left: `${t * 100}%` } : undefined}>
|
||
{formatClock(data.durationS * t)}
|
||
</span>
|
||
))}
|
||
</div>
|
||
<figcaption className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-fg-subtle">
|
||
<span className="inline-flex items-center gap-1.5"><span className="size-2.5 rounded-sm bg-option-b/60" />mensagens/s (pico {peak})</span>
|
||
<span className="inline-flex items-center gap-1.5"><span className="size-2.5 rounded-sm bg-accent/40" />trecho do corte</span>
|
||
<span className="inline-flex items-center gap-1.5"><span className="h-2.5 w-0.5 bg-accent" />pico usado no corte</span>
|
||
<span>{formatDuration(data.durationS)} no total</span>
|
||
</figcaption>
|
||
</figure>
|
||
);
|
||
}
|