Clipador: subpáginas, jogos, idioma por canal e juiz com Gemini e IA reserva

- Clipador em subpáginas (Cortes, Sessões, Fontes, Jogos, Ajustes) com moldura comum, lista + diálogo
  dos cortes e submenu na barra lateral.
- Perfis de jogo (o que a IA sabe de cada jogo), parar pausa o monitor e idioma por fonte e por canal
  de publicação (migração v9: accounts.language).
- Juiz: Gemini CLI como terceiro provedor e IA reserva por chamada — se a IA escolhida cair por cota,
  login, chave ou rede, a próxima da ordem de Configurações → IA responde (com pausa da que caiu).
  Lê data/ai/settings.json e o cofre data/ai/vault.bin (DPAPI) escritos pelo painel; contrato em doc/ia.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 01:51:12 -03:00
co-authored by Claude Opus 5.5
parent 2d8b1a582d
commit 0567c7454a
55 changed files with 6514 additions and 2506 deletions
+9
View File
@@ -4,6 +4,7 @@ import { AccountCreateForm, AccountDetail } from "@/components/account-manager";
import { PlusIcon, PublishIcon, SettingsIcon, UsersIcon } from "@/components/icons";
import { EmptyState, LinkButton, Meta, PageHeader, cx } from "@/components/ui";
import { listAccounts, type AccountView } from "@/lib/accounts";
import { languageLabel, languageShort } from "@/lib/languages";
import { listStories } from "@/lib/stories";
export const metadata = { title: "Canais de publicação" };
@@ -57,6 +58,8 @@ export default async function AccountsPage({ searchParams }: { searchParams: Pro
/** Um chip por canal (com ponto de alerta se alguma rede pede atenção) e o botão "Novo canal". */
function AccountPicker({ accounts, selectedId, creating }: { accounts: AccountView[]; selectedId?: string; creating: boolean }) {
// Sigla do idioma só quando há canais em idiomas diferentes (todos em português: não polui).
const mixedLanguages = new Set(accounts.map((a) => a.language)).size > 1;
return (
<nav aria-label="Canais de publicação" className="flex flex-wrap items-center gap-x-3 gap-y-3 border-b border-line pb-5">
<ul className="flex min-w-0 flex-wrap gap-2">
@@ -70,6 +73,12 @@ function AccountPicker({ accounts, selectedId, creating }: { accounts: AccountVi
className={cx("inline-flex h-10 max-w-[20rem] items-center gap-2 rounded-full border px-4 text-sm font-medium transition-colors",
current ? "border-accent/60 bg-accent-soft text-fg" : "border-line-strong bg-surface text-fg-muted hover:bg-raised hover:text-fg")}>
<span className="truncate">{a.name}</span>
{mixedLanguages && (
<span className="rounded-full border border-line-strong px-1.5 text-[0.625rem] font-semibold tracking-wide text-fg-subtle"
title={languageLabel(a.language)}>
{languageShort(a.language)}<span className="sr-only"> ({languageLabel(a.language)})</span>
</span>
)}
{attention > 0 && <>
<span aria-hidden="true" className="size-2 shrink-0 rounded-full bg-warning" />
<span className="sr-only">({attention === 1 ? "uma rede precisa" : `${attention} redes precisam`} de atenção)</span>
+2 -2
View File
@@ -6,10 +6,10 @@ export async function GET(_request: Request, ctx: { params: Promise<{ id: string
return account ? Response.json(account) : Response.json({ error: "Canal de publicação não encontrado." }, { status: 404 });
}
/** Edita nome, nicho, notas e regras: {name?, niche?, notes?, approvalMode?: "manual"|"auto", timing?: "now"|"best_slot", aiLabel?: "auto"|"always"|"never"}. */
/** Edita nome, nicho, notas, idioma e regras: {name?, niche?, notes?, language?: "pt-BR"|"en-US"|"es-419", approvalMode?: "manual"|"auto", timing?: "now"|"best_slot", aiLabel?: "auto"|"always"|"never"}. */
export async function PATCH(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const body = await readJson<{ name: string; niche: string; notes: string; approvalMode: string; timing: string; aiLabel: string }>(request);
const body = await readJson<{ name: string; niche: string; notes: string; language: string; approvalMode: string; timing: string; aiLabel: string }>(request);
return Response.json(updateAccount((await ctx.params).id, body));
} catch (error) {
return errorResponse(error);
+3 -3
View File
@@ -7,11 +7,11 @@ export async function GET() {
return Response.json(listAccounts(), { headers: { "Cache-Control": "no-store" } });
}
/** Cria uma conta: {name, niche?, notes?}. */
/** Cria uma conta: {name, niche?, notes?, language?: "pt-BR"|"en-US"|"es-419"}. */
export async function POST(request: Request) {
try {
const body = (await request.json()) as { name?: string; niche?: string; notes?: string };
return Response.json(createAccount({ name: String(body.name ?? ""), niche: body.niche, notes: body.notes }));
const body = (await request.json()) as { name?: string; niche?: string; notes?: string; language?: string };
return Response.json(createAccount({ name: String(body.name ?? ""), niche: body.niche, notes: body.notes, language: body.language }));
} catch (error) {
return errorResponse(error);
}
@@ -0,0 +1,9 @@
import { GamesPage } from "@/components/clipper-games-page";
import { ClipperGate } from "@/components/clipper-provider";
export const metadata = { title: "Jogos · Clipador" };
/** O que a IA sabe dos jogos das lives. Cabeçalho, barra da live e sub-navegação vêm do layout. */
export default function ClipperGamesPage() {
return <ClipperGate><GamesPage /></ClipperGate>;
}
+27
View File
@@ -0,0 +1,27 @@
import { connection } from "next/server";
import type { ReactNode } from "react";
import type { ChannelAccounts } from "@/components/clipper-channels";
import { ClipperProvider } from "@/components/clipper-provider";
import { ClipperShell } from "@/components/clipper-shell";
import { listAccounts } from "@/lib/accounts";
/**
* Moldura comum das subpáginas do Clipador (Cortes, Sessões, Fontes, Jogos, Ajustes): os dados do serviço são
* lidos no navegador (mudam a cada segundo) e compartilhados pelo ClipperProvider; do servidor vem só em quais
* canais de publicação cada fonte está ligada. O editor em tela cheia (/clipper/edit) fica fora deste grupo.
*/
export default async function ClipperStudioLayout({ children }: { children: ReactNode }) {
await connection();
const channelAccounts: ChannelAccounts = {};
for (const account of listAccounts()) {
for (const link of account.channels) {
if (link.status !== "active") continue;
(channelAccounts[link.channel_id] ??= []).push({ id: account.id, name: account.name });
}
}
return (
<ClipperProvider channelAccounts={channelAccounts}>
<ClipperShell>{children}</ClipperShell>
</ClipperProvider>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { ClipsPage } from "@/components/clipper-clips-page";
import { ClipperGate } from "@/components/clipper-provider";
export const metadata = { title: "Cortes · Clipador" };
/** Cortes do Clipador: lista com filtros e o modal do corte. Cabeçalho, barra da live e sub-navegação vêm do layout. */
export default function ClipperClipsPage() {
return (
<ClipperGate>
<ClipsPage />
</ClipperGate>
);
}
@@ -0,0 +1,14 @@
import { ClipperGate } from "@/components/clipper-provider";
import { SessionDetailPage } from "@/components/clipper-session-detail";
export const metadata = { title: "Sessão · Clipador" };
/** Detalhe de uma sessão do Clipador. A sessão vem dos dados já carregados pelo provider (id fora da lista = não encontrada). */
export default async function ClipperSessionPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return (
<ClipperGate>
<SessionDetailPage id={Number(id)} />
</ClipperGate>
);
}
@@ -0,0 +1,13 @@
import { ClipperGate } from "@/components/clipper-provider";
import { SessionsPage } from "@/components/clipper-sessions-page";
export const metadata = { title: "Sessões · Clipador" };
/** Sessões do Clipador: lista compacta; o cabeçalho, a barra da live e a sub-navegação vêm do layout do grupo. */
export default function ClipperSessionsPage() {
return (
<ClipperGate>
<SessionsPage />
</ClipperGate>
);
}
@@ -0,0 +1,9 @@
import { ClipperGate } from "@/components/clipper-provider";
import { SettingsPage } from "@/components/clipper-settings-page";
export const metadata = { title: "Ajustes · Clipador" };
/** Ajustes do Clipador: juiz (IA), serviço e idiomas. Cabeçalho, barra da live e sub-navegação vêm do layout. */
export default function ClipperSettingsPage() {
return <ClipperGate><SettingsPage /></ClipperGate>;
}
@@ -0,0 +1,9 @@
import { SourcesPage } from "@/components/clipper-channels";
import { ClipperGate } from "@/components/clipper-provider";
export const metadata = { title: "Fontes · Clipador" };
/** Fontes do Clipador: os streamers de onde saem os cortes. Cabeçalho, barra da live e sub-navegação vêm do layout. */
export default function ClipperSourcesPage() {
return <ClipperGate><SourcesPage /></ClipperGate>;
}
-39
View File
@@ -1,39 +0,0 @@
import { connection } from "next/server";
import type { ChannelAccounts } from "@/components/clipper-channels";
import { ClipperStudio } from "@/components/clipper-studio";
import Link from "next/link";
import { BroadcastIcon, PublishIcon, ScissorsIcon, SparkIcon } from "@/components/icons";
import { Meta, PageHeader } from "@/components/ui";
import { listAccounts } from "@/lib/accounts";
export const metadata = { title: "Clipador" };
/**
* Clipador: cortes automáticos de lives (Twitch, YouTube, Kick). O estado muda a cada segundo
* (gravação, IA, render), então a página busca /api/clipper/* no navegador e consulta de novo
* enquanto houver trabalho. Do servidor vem só em quais canais de publicação cada fonte está ligada.
*/
export default async function ClipperPage() {
await connection();
const channelAccounts: ChannelAccounts = {};
for (const account of listAccounts()) {
for (const link of account.channels) {
if (link.status !== "active") continue;
(channelAccounts[link.channel_id] ??= []).push({ id: account.id, name: account.name });
}
}
return (
<>
<PageHeader eyebrow="Cortes de live" title="Clipador"
description="Grava lives de terceiros, acha os picos de reação do chat, pede o veredito da IA e entrega cortes verticais com legenda, prontos para você aprovar."
meta={<>
<Meta icon={<BroadcastIcon size={15} />}>Twitch, YouTube e Kick</Meta>
<Meta icon={<SparkIcon size={15} />}>Juiz: Codex ou Claude pela CLI</Meta>
<Meta icon={<ScissorsIcon size={15} />}>MP4 1080×1920 com legenda</Meta>
<Meta icon={<PublishIcon size={15} />}>Cortes aprovados saem nas redes dos <Link href="/accounts" className="text-fg-muted underline underline-offset-2 hover:text-fg">canais de publicação</Link></Meta>
</>} />
<ClipperStudio channelAccounts={channelAccounts} />
</>
);
}
+12
View File
@@ -219,6 +219,18 @@
transition-delay: 110ms;
}
/* Subpáginas na barra: fechadas (0fr) com a barra recolhida, abertas (1fr) quando ela expande. */
.rail-sub {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 200ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.rail:hover .rail-sub,
.rail:has(:focus-visible) .rail-sub {
grid-template-rows: 1fr;
}
/* Texto com o degradê da chama, para o que é feito pela IA */
.text-flame {
background: linear-gradient(95deg, var(--color-glow), var(--color-accent) 45%, var(--color-flame));
+27 -4
View File
@@ -9,12 +9,14 @@ import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useId, useState, useTransition, type FormEvent, type ReactNode } from "react";
import type { AccountView } from "@/lib/accounts";
import { ACCOUNT_LANGUAGES, DEFAULT_LANGUAGE, languageLabel, languageShort } from "@/lib/languages";
import { PLATFORMS, type StoryKind } from "@/lib/types";
import { apiCall } from "./api-client";
import { PLATFORM_LABEL, clipperCall, isOfflineError, type ClipperChannel } from "./clipper-client";
import { PlatformIcon } from "./clipper-sessions";
import { PublishingNetworksCard, PublishingRulesCard, networkAnchor } from "./account-networks";
import { Dialog } from "./dialog";
import { DescribedSelect } from "./forms";
import { AlertIcon, ChartIcon, FilmIcon, LinkIcon, PenIcon, PlusIcon, PublishIcon, ScissorsIcon, TrashIcon, XIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { readNetwork } from "./publishing-client";
@@ -23,6 +25,9 @@ import { storyFormatLabel } from "./story-formats";
import { Badge, Button, Card, Eyebrow, Feedback, Field, Input, LinkButton, Select, Spinner, Textarea, cx, formatDate, type Tone } from "./ui";
import { askConfirm } from "./confirm-dialog";
/** Opções do seletor "Idioma e público" (criar e editar canal). */
const LANGUAGE_OPTIONS = ACCOUNT_LANGUAGES.map((l) => ({ value: l.id, label: l.label, description: l.audience }));
type StoryOption = { id: string; title: string; kind: StoryKind };
/** `key` diz qual ação gerou o retorno, para mostrá-lo perto de onde o clique aconteceu. */
type Message = { ok: boolean; text: string; key: string } | null;
@@ -69,6 +74,7 @@ export function AccountCreateForm() {
await run<AccountView>("create",
() => apiCall<AccountView>("/api/accounts", "POST", {
name: String(form.get("name") ?? ""), niche: String(form.get("niche") ?? ""), notes: String(form.get("notes") ?? ""),
language: String(form.get("language") ?? DEFAULT_LANGUAGE),
}),
(a) => `Canal “${a.name}” criado.`,
(a) => router.push(`/accounts?account=${encodeURIComponent(a.id)}`));
@@ -84,6 +90,8 @@ export function AccountCreateForm() {
<Field label="Nicho (opcional)">
<Input name="niche" maxLength={60} placeholder="Ex.: suspense leve, humor" />
</Field>
{/* Idioma e público: para quem o canal fala (os cortes e textos precisam estar nesse idioma). */}
<DescribedSelect name="language" label="Idioma e público" defaultValue={DEFAULT_LANGUAGE} options={LANGUAGE_OPTIONS} />
<Field label="Notas (opcional)">
<Textarea name="notes" rows={3} maxLength={500} placeholder="Público, horários de postagem, combinados…" />
</Field>
@@ -112,6 +120,7 @@ export function AccountDetail({ account, stories }: { account: AccountView; stor
const form = new FormData(e.currentTarget);
const ok = await run("save", () => apiCall<AccountView>(base, "PATCH", {
name: String(form.get("name") ?? ""), niche: String(form.get("niche") ?? ""), notes: String(form.get("notes") ?? ""),
language: String(form.get("language") ?? account.language),
}), "Dados do canal salvos.");
if (ok) setEditing(false);
}
@@ -171,7 +180,7 @@ export function AccountDetail({ account, stories }: { account: AccountView; stor
</div>
<Dialog open={editing} onClose={() => setEditing(false)} size="sm" eyebrow="Canal de publicação" title="Editar dados do canal"
description="Nome, nicho e notas. Não mexe nas redes nem no que o canal publica."
description="Nome, nicho, idioma e notas. Não mexe nas redes nem no que o canal publica."
footer={<>
<Button type="button" variant="ghost" onClick={() => setEditing(false)}>Cancelar</Button>
<Button type="submit" form={formId} disabled={pending !== null}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar dados"}</Button>
@@ -179,6 +188,7 @@ export function AccountDetail({ account, stories }: { account: AccountView; stor
<form id={formId} key={account.updated_at} onSubmit={save} className="grid gap-4">
<Field label="Nome"><Input name="name" required minLength={2} maxLength={60} defaultValue={account.name} autoFocus /></Field>
<Field label="Nicho"><Input name="niche" maxLength={60} defaultValue={account.niche} placeholder="Ex.: suspense leve" /></Field>
<DescribedSelect name="language" label="Idioma e público" defaultValue={account.language || DEFAULT_LANGUAGE} options={LANGUAGE_OPTIONS} />
<Field label="Notas"><Textarea name="notes" rows={4} maxLength={500} defaultValue={account.notes} /></Field>
<div aria-live="polite" className="empty:hidden">{saveMessage && !saveMessage.ok && <Feedback ok={false}>{saveMessage.text}</Feedback>}</div>
</form>
@@ -211,9 +221,15 @@ function AccountHeader({ account, activeStories, activeChannels, onEdit }: {
<div className="min-w-0">
<Eyebrow className="mb-2">Canal de publicação</Eyebrow>
<h2 id={titleId} className="font-display text-[1.75rem] leading-tight font-semibold tracking-[-0.02em] break-words text-fg">{account.name}</h2>
<p className="mt-1.5 text-sm text-fg-muted">
{account.niche || <span className="text-fg-subtle">Sem nicho definido</span>}
<span aria-hidden="true" className="px-2 text-fg-subtle">·</span>{publishes}
<p className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-fg-muted">
<span title={`Idioma e público: ${languageLabel(account.language)}`}>
<Badge tone="info" dot={false}>
<span className="font-semibold">{languageShort(account.language)}</span>
<span aria-hidden="true">·</span>{languageLabel(account.language)}
</Badge>
</span>
<span>{account.niche || <span className="text-fg-subtle">Sem nicho definido</span>}</span>
<span aria-hidden="true" className="text-fg-subtle">·</span><span>{publishes}</span>
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
@@ -259,6 +275,13 @@ function AccountDataCard({ account, onEdit }: { account: AccountView; onEdit: ()
<dt className="text-[0.8125rem] text-fg-subtle">Nicho</dt>
<dd className="text-fg">{account.niche || <span className="text-fg-subtle">—</span>}</dd>
</div>
<div className="grid gap-1">
<dt className="text-[0.8125rem] text-fg-subtle">Idioma e público</dt>
<dd className="text-fg">
{languageLabel(account.language)}
<span className="block text-xs text-fg-subtle">{ACCOUNT_LANGUAGES.find((l) => l.id === account.language)?.audience ?? "—"}</span>
</dd>
</div>
<div className="grid gap-1">
<dt className="text-[0.8125rem] text-fg-subtle">Criado em</dt>
<dd className="text-fg">{formatDate(account.created_at)}</dd>
+19 -3
View File
@@ -6,11 +6,12 @@
// Título e legenda são os do cartão (salvos). Cada rede mostra por que não pode ser escolhida, quando for o caso.
import { useEffect, useState } from "react";
import type { AccountView } from "@/lib/accounts";
import { DEFAULT_LANGUAGE, languageLabel, languageShort } from "@/lib/languages";
import type { Platform } from "@/lib/types";
import { apiCall } from "./api-client";
import type { Clip } from "./clipper-client";
import { Dialog } from "./dialog";
import { AlertIcon, CheckIcon, ClockIcon, PublishIcon } from "./icons";
import { AlertIcon, CheckIcon, ClockIcon, InfoIcon, PublishIcon } from "./icons";
import { PLATFORM_META } from "./platforms";
import { formatTime, publishClip, toLocalInput, type ClipTiming, type PublishJob } from "./publishing-client";
import { TextLink } from "./publishing-ui";
@@ -98,6 +99,9 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
const [error, setError] = useState<string | null>(null);
const account = accounts?.find((a) => a.id === accountId) ?? null;
// Idioma do corte: o da sessão de origem (o serviço antigo não manda `language`; sem ele, português).
const clipLanguage = clip.language || DEFAULT_LANGUAGE;
const languageMismatch = account !== null && (account.language || DEFAULT_LANGUAGE) !== clipLanguage;
/** Redes do canal: escolhível? por quê não? (a ordem é sempre YouTube, TikTok, Instagram) */
// `pending`: o corte já tem horário nesta rede. No "próximo horário bom" ela fica travada (o servidor não
@@ -223,11 +227,23 @@ function PublishDialog({ clip, jobs, onClose, onDone }: {
{accounts.length > 1 ? (
<Field label="Canal de publicação">
<Select value={accountId} onChange={(e) => pickAccount(accounts.find((a) => a.id === e.target.value) ?? null)}>
{accounts.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
{accounts.map((a) => <option key={a.id} value={a.id}>{a.name} · {languageShort(a.language || DEFAULT_LANGUAGE)}</option>)}
</Select>
</Field>
) : (
<p className="text-[0.8125rem] text-fg-muted">Canal de publicação: <span className="font-medium text-fg">{account?.name}</span></p>
<p className="text-[0.8125rem] text-fg-muted">
Canal de publicação: <span className="font-medium text-fg">{account?.name}</span>
{account && <span className="text-fg-subtle"> · {languageLabel(account.language || DEFAULT_LANGUAGE)}</span>}
</p>
)}
{languageMismatch && account && (
<p role="note" className="flex gap-2 rounded-control border border-info/30 bg-info-soft px-3 py-2 text-[0.8125rem] leading-relaxed text-info">
<InfoIcon size={15} className="mt-0.5 shrink-0" />
<span>
Este canal publica em <span className="font-medium">{languageLabel(account.language)}</span>. O corte está em{" "}
{languageLabel(clipLanguage).toLowerCase()}: a versão traduzida vem na próxima etapa; publique só se for intencional.
</span>
</p>
)}
<fieldset className="grid gap-2">
+271 -129
View File
@@ -1,22 +1,90 @@
"use client";
// Canais do Clipador: cadastrar pelo link do canal, ligar o monitor (grava sozinho quando entra ao
// vivo), marcar se o streamer autorizou os cortes, checar agora, renomear e remover.
// Fontes do Clipador (/clipper/sources): os streamers de onde saem os cortes, em tabela — ao vivo/offline, monitor
// (ligado · pausado · desligado), autorização, idioma da live, canais de publicação ligados e as ações da fonte.
// "Adicionar fonte" abre um diálogo. Os dados vêm do ClipperProvider; cada ação recarrega tudo.
//
// Monitor pausado: parar uma gravação à mão pausa o monitor da fonte (`monitorPausedAt`, com a sessão que motivou)
// até você religar — PATCH {monitor: true} limpa a pausa. O serviço antigo não manda esses campos (nem `language`).
import Link from "next/link";
import { useState, type FormEvent } from "react";
import { PLATFORM_LABEL, clipperCall, useClipperAction, type ClipperChannel, type ClipperSession } from "./clipper-client";
import { useId, useState, type FormEvent, type ReactNode } from "react";
import {
LANGUAGES, PLATFORM_LABEL, clipperCall, languageLabel, useClipperAction,
type ClipperChannel, type ClipperSession,
} from "./clipper-client";
import { CutSettingsDialog, type CutScope } from "./clipper-cut-settings";
import { ChannelEmotes } from "./clipper-games";
import { useClipper, useClipperData } from "./clipper-provider";
import { PlatformIcon } from "./clipper-sessions";
import { AlertIcon, BroadcastIcon, CheckIcon, PenIcon, PlusIcon, RefreshIcon, SettingsIcon, TrashIcon, UsersIcon } from "./icons";
import { Badge, Button, Card, EmptyState, Feedback, Field, Input, Spinner, Switch, formatRelative } from "./ui";
import { askConfirm } from "./confirm-dialog";
import { Dialog } from "./dialog";
import { AlertIcon, BroadcastIcon, ChatIcon, ChevronDownIcon, PenIcon, PlusIcon, RefreshIcon, SettingsIcon, TrashIcon, UsersIcon } from "./icons";
import {
Badge, Button, EmptyState, Feedback, Field, Input, Select, Spinner, Switch, Table, THead, Td, Th, cx, formatRelative,
} from "./ui";
/** Canais de publicação ligados a cada fonte (id da fonte → canais), calculado no servidor do painel. */
export type ChannelAccounts = Record<string, { id: string; name: string }[]>;
export function ChannelAddForm({ onChanged, disabled }: { onChanged: () => void; disabled: boolean }) {
/* ---------- Página ---------- */
export function SourcesPage() {
const { channelAccounts, reload, games } = useClipper();
const { status, channels, sessions } = useClipperData();
const [adding, setAdding] = useState(false);
const [cutScope, setCutScope] = useState<CutScope | null>(null);
const titleId = useId();
return (
<section aria-labelledby={titleId} className="grid gap-4">
<div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
<div className="grid gap-1">
<h2 id={titleId} className="text-title text-fg">Fontes</h2>
<p className="max-w-[90ch] text-xs leading-relaxed text-fg-subtle">
Monitorar grava sozinho quando a fonte entra ao vivo. Parar uma gravação à mão pausa o monitor dessa fonte até você religar;
se a live cair sozinha, a gravação é retomada na mesma sessão.
</p>
</div>
<Button onClick={() => setAdding(true)}><PlusIcon size={16} />Adicionar fonte</Button>
</div>
{channels.length === 0 ? (
<EmptyState compact icon={<BroadcastIcon size={18} />} title="Nenhuma fonte cadastrada"
action={<Button variant="secondary" onClick={() => setAdding(true)}><PlusIcon size={16} />Adicionar fonte</Button>}>
Cadastre o link do canal de um streamer. Com o monitor ligado, o Clipador grava sozinho sempre que ele entrar ao vivo.
</EmptyState>
) : (
<Table>
<THead>
<Th>Fonte</Th><Th>Ao vivo</Th><Th>Monitor</Th><Th>Autorização</Th><Th>Idioma</Th><Th>Publica em</Th><Th className="text-right">Ações</Th>
</THead>
<tbody>
{channels.map((c) => (
<SourceRow key={c.id} channel={c} accounts={channelAccounts[c.id] ?? []} showEmotes={games !== null} onChanged={reload}
onConfigure={() => setCutScope({
kind: "channel", channel: c,
// Sessões vêm da mais nova para a mais antiga: a primeira da fonte dá o quadro de referência.
session: sessions.find((s) => s.channelId === c.id) ?? null,
})} />
))}
</tbody>
</Table>
)}
<AddSourceDialog open={adding} defaultLanguage={status.settings.language} onClose={() => setAdding(false)} onChanged={reload} />
<CutSettingsDialog scope={cutScope} onClose={() => setCutScope(null)} onSaved={reload} />
</section>
);
}
/* ---------- Adicionar fonte ---------- */
function AddSourceDialog({ open, defaultLanguage, onClose, onChanged }: {
open: boolean; defaultLanguage: string; onClose: () => void; onChanged: () => void;
}) {
const { pending, message, run } = useClipperAction(onChanged);
const [monitor, setMonitor] = useState(true);
const [authorized, setAuthorized] = useState(false);
const [formKey, setFormKey] = useState(0);
const formId = useId();
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
@@ -24,70 +92,60 @@ export function ChannelAddForm({ onChanged, disabled }: { onChanged: () => void;
const displayName = String(form.get("displayName") ?? "").trim();
const done = await run("add", () => clipperCall<ClipperChannel>("channels", "POST", {
url: String(form.get("url") ?? "").trim(), ...(displayName ? { displayName } : {}), monitor, authorized,
language: String(form.get("language") ?? defaultLanguage),
}), (c) => `Fonte “${c.displayName || c.channel}” adicionada${c.monitor ? " e monitorada" : ""}.`);
if (done) { setFormKey((k) => k + 1); setAuthorized(false); }
if (done) onClose();
}
return (
<Card eyebrow={<><PlusIcon size={13} />Nova fonte</>} title="Adicionar fonte"
description="Link do perfil do streamer (não de um vídeo): twitch.tv/nome, kick.com/nome ou youtube.com/@nome.">
<form key={formKey} onSubmit={submit} className="grid gap-4">
<div className="grid gap-4 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Field label="Link da fonte">
<Input name="url" type="url" required disabled={disabled} placeholder="https://www.twitch.tv/nome" />
</Field>
<Field label="Nome para mostrar (opcional)">
<Input name="displayName" maxLength={60} disabled={disabled} placeholder="Ex.: Alanzoka" />
<Dialog open={open} onClose={onClose} eyebrow={<><PlusIcon size={13} />Nova fonte</>} title="Adicionar fonte"
description="Link do perfil do streamer (não de um vídeo): twitch.tv/nome, kick.com/nome ou youtube.com/@nome."
footer={<>
<Button type="button" variant="ghost" onClick={onClose}>Cancelar</Button>
<Button type="submit" form={formId} disabled={pending !== null}>{pending === "add" ? <><Spinner />Adicionando…</> : <><PlusIcon size={16} />Adicionar fonte</>}</Button>
</>}>
<form id={formId} onSubmit={submit} className="grid gap-4">
<Field label="Link da fonte"><Input name="url" type="url" required autoFocus placeholder="https://www.twitch.tv/nome" /></Field>
<div className="grid gap-4 sm:grid-cols-2">
<Field label="Nome para mostrar (opcional)"><Input name="displayName" maxLength={60} placeholder="Ex.: Alanzoka" /></Field>
<Field label="Idioma da live" hint="Usado na transcrição e nos textos da IA. Canais em outro idioma são configurados em Canais de publicação.">
<Select name="language" defaultValue={defaultLanguage}>
{languageOptions(defaultLanguage).map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}
</Select>
</Field>
</div>
<div className="grid gap-4 md:grid-cols-2">
<Switch label="Monitorar" checked={monitor} onChange={setMonitor} disabled={disabled}
hint="Checa de minuto em minuto e grava sozinho quando a fonte entra ao vivo." />
<Switch label="O streamer autorizou cortes" checked={authorized} onChange={setAuthorized} disabled={disabled}
hint="Cortar live de terceiros sem autorização pode render strike de direitos autorais." />
</div>
<div className="flex flex-wrap items-center gap-3">
<Button disabled={disabled || pending !== null}>{pending === "add" ? <Spinner /> : <PlusIcon size={16} />}Adicionar fonte</Button>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
<Switch label="Monitorar" checked={monitor} onChange={setMonitor} hint="Checa de minuto em minuto e grava sozinho quando a fonte entra ao vivo." />
<Switch label="O streamer autorizou cortes" checked={authorized} onChange={setAuthorized}
hint="Cortar live de terceiros sem autorização pode render strike de direitos autorais." />
<div aria-live="polite" className="empty:hidden">{message && !message.ok && <Feedback ok={false}>{message.text}</Feedback>}</div>
</form>
</Card>
</Dialog>
);
}
export function ChannelList({ channels, accounts, onChanged, onConfigure, showEmotes }: {
channels: ClipperChannel[]; accounts: ChannelAccounts; onChanged: () => void;
/** Abre a "Configuração do corte" com o padrão do canal. */
onConfigure: (channel: ClipperChannel) => void;
/** O serviço novo (fase 2) tem a tabela de emotes. */
showEmotes: boolean;
}) {
if (channels.length === 0) {
return (
<EmptyState compact icon={<BroadcastIcon size={18} />} title="Nenhuma fonte cadastrada">
Adicione uma fonte acima. Com o monitor ligado, o Clipador grava sozinho sempre que ela entrar ao vivo.
</EmptyState>
);
}
return (
<ul className="grid divide-y divide-line overflow-hidden rounded-card border border-line bg-surface shadow-card">
{channels.map((c) => <li key={c.id}><ChannelRow channel={c} accounts={accounts[c.id] ?? []} onChanged={onChanged} onConfigure={onConfigure} showEmotes={showEmotes} /></li>)}
</ul>
);
/** Idiomas conhecidos; um código fora da lista (do .env) entra para não sumir do seletor. */
function languageOptions(current: string | undefined) {
if (!current || LANGUAGES.some((l) => l.id === current)) return LANGUAGES;
return [...LANGUAGES, { id: current, label: languageLabel(current), short: current }];
}
function ChannelRow({ channel: c, accounts, onChanged, onConfigure, showEmotes }: {
channel: ClipperChannel; accounts: { id: string; name: string }[]; onChanged: () => void;
onConfigure: (channel: ClipperChannel) => void; showEmotes: boolean;
/* ---------- Linha da fonte ---------- */
function SourceRow({ channel: c, accounts, showEmotes, onChanged, onConfigure }: {
channel: ClipperChannel; accounts: { id: string; name: string }[]; showEmotes: boolean; onChanged: () => void; onConfigure: () => void;
}) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const [renaming, setRenaming] = useState(false);
const [emotesOpen, setEmotesOpen] = useState(false);
const [checked, setChecked] = useState<{ live: boolean; title: string } | null>(null);
const base = `channels/${encodeURIComponent(c.id)}`;
const name = c.displayName || c.channel;
const isLive = checked ? checked.live : c.lastStatus === "ao vivo";
const paused = c.monitor && Boolean(c.monitorPausedAt);
const busy = pending !== null;
const emotesId = useId();
const patch = (key: string, body: Partial<Pick<ClipperChannel, "displayName" | "monitor" | "authorized">>, text: string) =>
const patch = (key: string, body: Partial<Pick<ClipperChannel, "displayName" | "monitor" | "authorized" | "language">>, text: string) =>
run(key, () => clipperCall<ClipperChannel>(base, "PATCH", body), text);
async function check() {
@@ -97,86 +155,170 @@ function ChannelRow({ channel: c, accounts, onChanged, onConfigure, showEmotes }
if (r) setChecked(r);
}
const extra = (message || emotesOpen) && (
<tr className="border-t border-line/60 bg-sunken/30">
<td colSpan={7} className="px-4 py-3">
<div className="grid gap-3 sm:pl-[3.25rem]">
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
{emotesOpen && <div id={emotesId}><ChannelEmotes channelKey={c.id} title="Emotes da fonte" /></div>}
</div>
</td>
</tr>
);
return (
<div className="grid gap-3 px-5 py-4">
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
<span className="grid size-10 shrink-0 place-items-center rounded-control border border-line-strong bg-raised text-fg-muted">
<PlatformIcon platform={c.platform} size={19} />
</span>
<div className="grid min-w-44 flex-1 gap-1">
{renaming ? (
<form className="flex flex-wrap items-center gap-2" onSubmit={async (e) => {
e.preventDefault();
const displayName = String(new FormData(e.currentTarget).get("displayName") ?? "").trim();
if (await patch("rename", { displayName }, "Nome atualizado.")) setRenaming(false);
}}>
<Input name="displayName" defaultValue={c.displayName} maxLength={60} autoFocus aria-label={`Nome da fonte ${c.channel}`} className="h-8 max-w-60" />
<Button size="sm" variant="secondary" disabled={pending !== null}>{pending === "rename" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar</Button>
<Button type="button" size="sm" variant="ghost" onClick={() => setRenaming(false)}>Cancelar</Button>
</form>
) : (
<p className="flex flex-wrap items-center gap-2">
<span className="font-semibold text-fg">{name}</span>
<button type="button" onClick={() => { setRenaming(true); setMessage(null); }} aria-label={`Renomear ${name}`}
className="grid size-6 place-items-center rounded text-fg-subtle hover:bg-raised hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
<PenIcon size={13} />
</button>
{isLive ? <Badge tone="danger" pulse>ao vivo</Badge> : c.lastStatus === "offline" || checked ? <Badge>offline</Badge> : null}
{c.authorized
? <Badge tone="success">autorizado</Badge>
: <Badge tone="warning" dot={false}><AlertIcon size={12} />sem autorização · risco de strike</Badge>}
</p>
)}
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-subtle">
<span>{PLATFORM_LABEL[c.platform]}</span>
<a href={c.url} target="_blank" rel="noreferrer noopener" className="hover:text-fg hover:underline">{c.url.replace(/^https?:\/\/(www\.)?/, "")}</a>
<span>{c.lastCheckAt ? `checado ${formatRelative(c.lastCheckAt)}` : "nunca checado"}</span>
{accounts.length > 0 && (
<span className="inline-flex flex-wrap items-center gap-1.5">
<UsersIcon size={13} />
<span className="sr-only">Publicada pelos canais:</span>
{accounts.map((a, i) => (
<span key={a.id}>
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`} className="text-fg-muted hover:text-fg hover:underline">{a.name}</Link>
{i < accounts.length - 1 ? "," : ""}
</span>
))}
<>
<tr className="border-t border-line transition-colors first:border-t-0 hover:bg-raised/40">
<Td>
<div className="flex items-center gap-3">
<span className="grid size-10 shrink-0 place-items-center rounded-control border border-line-strong bg-raised text-fg-muted">
<PlatformIcon platform={c.platform} size={19} />
</span>
<div className="grid min-w-0 gap-0.5">
{renaming ? (
<form className="flex flex-wrap items-center gap-2" onSubmit={async (e) => {
e.preventDefault();
const displayName = String(new FormData(e.currentTarget).get("displayName") ?? "").trim();
if (await patch("rename", { displayName }, "Nome atualizado.")) setRenaming(false);
}}>
<Input name="displayName" defaultValue={c.displayName} maxLength={60} autoFocus aria-label={`Nome da fonte ${c.channel}`} className="h-8 w-48" />
<Button size="sm" variant="secondary" disabled={busy}>{pending === "rename" ? <Spinner className="size-3.5" /> : "Salvar"}</Button>
<Button type="button" size="sm" variant="ghost" onClick={() => setRenaming(false)}>Cancelar</Button>
</form>
) : (
<span className="flex items-center gap-1.5">
<span className="truncate font-medium text-fg">{name}</span>
<button type="button" onClick={() => { setRenaming(true); setMessage(null); }} aria-label={`Renomear ${name}`} title="Renomear"
className="grid size-6 shrink-0 place-items-center rounded text-fg-subtle hover:bg-raised hover:text-fg focus-visible:outline-2 focus-visible:outline-accent">
<PenIcon size={13} />
</button>
</span>
)}
<span className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span>{PLATFORM_LABEL[c.platform]}</span>
<Dot />
<a href={c.url} target="_blank" rel="noreferrer noopener" className="truncate hover:text-fg hover:underline">{c.url.replace(/^https?:\/\/(www\.)?/, "")}</a>
<Dot />
<span>{c.lastCheckAt ? `checado ${formatRelative(c.lastCheckAt)}` : "nunca checado"}</span>
</span>
</div>
</div>
</Td>
<Td>
{isLive ? <Badge tone="danger" pulse>ao vivo</Badge> : c.lastStatus === "offline" || checked ? <Badge>offline</Badge> : <span className="text-fg-subtle">—</span>}
</Td>
<Td>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
<Switch label={<span className="sr-only">Monitorar {name}</span>} checked={c.monitor} busy={pending === "monitor"} disabled={busy}
onChange={(v) => void patch("monitor", { monitor: v }, v ? "Monitor ligado: grava sozinho quando entrar ao vivo." : "Monitor desligado.")} />
{paused ? (
<span className="grid gap-1">
<span className="flex items-center gap-2">
<Badge tone="warning">pausado</Badge>
<Button size="sm" variant="secondary" disabled={busy} className="h-7"
onClick={() => void patch("resume", { monitor: true }, "Monitor religado: volta a gravar sozinho quando a fonte estiver ao vivo.")}>
{pending === "resume" ? <Spinner className="size-3.5" /> : <BroadcastIcon size={14} />}Religar
</Button>
</span>
<span className="text-xs text-fg-subtle">
você parou {c.monitorPausedBySession ? `a sessão #${c.monitorPausedBySession}` : "uma gravação"}
{c.monitorPausedAt ? ` ${formatRelative(c.monitorPausedAt)}` : ""}
</span>
</span>
) : (
<span className={cx("text-xs", c.monitor ? "text-fg-muted" : "text-fg-subtle")}>{c.monitor ? "grava sozinho" : "desligado"}</span>
)}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Button variant="ghost" size="sm" onClick={() => onConfigure(c)}><SettingsIcon size={15} />Padrão da fonte</Button>
<Button variant="secondary" size="sm" disabled={pending !== null} onClick={() => void check()}>
{pending === "check" ? <><Spinner className="size-3.5" />Checando…</> : <><RefreshIcon size={15} />Checar agora</>}
</Button>
{isLive && checked?.live && (
<Button size="sm" disabled={pending !== null}
onClick={() => void run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: c.url }), (s) => `Gravando: sessão #${s.id}.`)}>
{pending === "record" ? <Spinner className="size-3.5" /> : <BroadcastIcon size={15} />}Gravar agora
</Button>
</div>
</Td>
<Td>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
<Switch label={<span className="sr-only">O streamer autorizou cortes de {name}</span>} checked={c.authorized} busy={pending === "authorized"} disabled={busy}
onChange={(v) => void patch("authorized", { authorized: v }, v ? "Marcado como autorizado." : "Autorização desmarcada.")} />
{c.authorized
? <span className="text-xs text-fg-muted">autorizou cortes</span>
: <Badge tone="warning" dot={false}><AlertIcon size={12} />risco de strike</Badge>}
</div>
</Td>
<Td>
<Select aria-label={`Idioma da live de ${name}`} value={c.language ?? ""} disabled={busy || c.language === undefined}
title={c.language === undefined ? "O Clipador no ar ainda é a versão antiga: reinicie o serviço para escolher o idioma por fonte." : languageLabel(c.language)}
onChange={(e) => void patch("language", { language: e.target.value }, `Idioma da live: ${languageLabel(e.target.value)}.`)}
className="h-8 w-auto min-w-20 py-0 text-xs">
{c.language === undefined && <option value="">padrão</option>}
{languageOptions(c.language).map((l) => <option key={l.id} value={l.id}>{l.short} · {l.label}</option>)}
</Select>
</Td>
<Td>
{accounts.length > 0 ? (
<span className="inline-flex flex-wrap items-center gap-1.5 text-xs">
<UsersIcon size={13} className="text-fg-subtle" />
<span className="sr-only">Publicada pelos canais:</span>
{accounts.map((a, i) => (
<span key={a.id}>
<Link href={`/accounts?account=${encodeURIComponent(a.id)}`} className="text-fg-muted hover:text-fg hover:underline">{a.name}</Link>
{i < accounts.length - 1 ? "," : ""}
</span>
))}
</span>
) : (
<Link href="/accounts" className="text-xs text-fg-subtle underline-offset-2 hover:text-fg hover:underline">ligar a um canal</Link>
)}
<Button variant="ghost" size="sm" disabled={pending !== null} aria-label={`Remover a fonte ${name}`}
onClick={async () => {
if (!(await askConfirm({ title: `Remover a fonte “${name}”?`,
message: "Ela deixa de ser monitorada. Sessões e cortes já gravados continuam.",
confirmLabel: "Remover fonte", tone: "danger" }))) return;
void run("delete", () => clipperCall(base, "DELETE"), "Fonte removida.");
}}>
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Remover
</Button>
</div>
</div>
<div className="flex flex-wrap gap-x-8 gap-y-3 sm:pl-14">
<Switch label="Monitorar" checked={c.monitor} busy={pending === "monitor"} disabled={pending !== null}
onChange={(v) => void patch("monitor", { monitor: v }, v ? "Monitor ligado: grava sozinho quando entrar ao vivo." : "Monitor desligado.")}
hint="Grava sozinho quando entra ao vivo" />
<Switch label="Autorizou cortes" checked={c.authorized} busy={pending === "authorized"} disabled={pending !== null}
onChange={(v) => void patch("authorized", { authorized: v }, v ? "Marcado como autorizado." : "Autorização desmarcada.")}
hint="O streamer permitiu publicar cortes" />
</div>
{showEmotes && <div className="sm:pl-12"><ChannelEmotes channelKey={c.id} /></div>}
<div aria-live="polite" className="empty:hidden sm:pl-14">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</Td>
<Td className="text-right">
<div className="flex flex-wrap items-center justify-end gap-1">
{isLive && checked?.live && (
<Button size="sm" disabled={busy}
onClick={() => void run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: c.url }), (s) => `Gravando: sessão #${s.id}.`)}>
{pending === "record" ? <Spinner className="size-3.5" /> : <BroadcastIcon size={15} />}Gravar agora
</Button>
)}
<Button variant="secondary" size="sm" disabled={busy} onClick={() => void check()}>
{pending === "check" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Checar agora
</Button>
<IconAction label="Padrão da fonte (layout, legenda, duração)" onClick={onConfigure}><SettingsIcon size={16} /></IconAction>
{showEmotes && (
<IconAction label="Emotes da fonte" pressed={emotesOpen} controls={emotesId} onClick={() => setEmotesOpen((o) => !o)}>
<ChatIcon size={16} /><ChevronDownIcon size={12} className={cx("transition-transform", emotesOpen && "rotate-180")} />
</IconAction>
)}
<IconAction label={`Remover a fonte ${name}`} danger disabled={busy}
onClick={async () => {
if (!(await askConfirm({ title: `Remover a fonte “${name}”?`,
message: "Ela deixa de ser monitorada. Sessões e cortes já gravados continuam.",
confirmLabel: "Remover fonte", tone: "danger" }))) return;
void run("delete", () => clipperCall(base, "DELETE"), "Fonte removida.");
}}>
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={16} />}
</IconAction>
</div>
</Td>
</tr>
{extra}
</>
);
}
function Dot() {
return <span aria-hidden="true" className="text-line-strong">·</span>;
}
/** Botão só de ícone (o rótulo vai para title e leitores de tela). */
function IconAction({ label, onClick, children, danger = false, disabled = false, pressed, controls }: {
label: string; onClick: () => void; children: ReactNode; danger?: boolean; disabled?: boolean; pressed?: boolean; controls?: string;
}) {
return (
<button type="button" onClick={onClick} aria-label={label} title={label} disabled={disabled}
aria-pressed={pressed} aria-controls={pressed !== undefined ? controls : undefined}
className={cx("inline-flex h-8 min-w-8 items-center justify-center gap-0.5 rounded-control px-1.5 text-fg-muted transition-colors",
"focus-visible:outline-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-45",
danger ? "hover:bg-danger-soft hover:text-danger" : "hover:bg-raised hover:text-fg", pressed && "bg-raised text-fg")}>
{children}
</button>
);
}
+63 -4
View File
@@ -6,7 +6,7 @@ import { apiCall, type ApiResult } from "./api-client";
import type { Tone } from "./ui";
export type ClipperPlatform = "twitch" | "youtube" | "kick";
export type JudgeProvider = "codex" | "claude" | "off";
export type JudgeProvider = "codex" | "claude" | "gemini" | "off";
export type ClipperStatus = {
version: string;
@@ -31,9 +31,20 @@ export type JudgeConfig = {
minScore: number;
options?: JudgeOptions;
lastScanError?: string | null;
models: { codex: JudgeModel[]; claude: JudgeModel[]; defaults: { codex: string; claude: string } };
/** `gemini` é opcional: o serviço antigo (antes do Gemini) não manda. */
models: { codex: JudgeModel[]; claude: JudgeModel[]; gemini?: JudgeModel[]; defaults: { codex: string; claude: string; gemini?: string } };
/** Por que a IA escolhida não roda (desligada em Configurações → IA, sem CLI, sem chave); null = pronta. */
unavailableReason?: string | null;
/** Modo de login da IA escolhida (Configurações → IA). */
authMode?: "oauth" | "apiKey" | null;
/** IA reserva: ordem efetiva em que o juiz tenta (a escolhida primeiro). Serviço antigo não manda. */
fallback?: { enabled: boolean; cooldownMin: number; chain: Exclude<JudgeProvider, "off">[] };
/** IAs em pausa depois de falha de indisponibilidade (`until` em ISO, UTC). */
pauses?: JudgePause[];
};
export type JudgePause = { provider: Exclude<JudgeProvider, "off">; until: string; reason: string };
export type ClipperChannel = {
id: string;
platform: ClipperPlatform;
@@ -45,6 +56,12 @@ export type ClipperChannel = {
lastCheckAt: string | null;
lastStatus: "ao vivo" | "offline" | "";
createdAt: string;
/** Idioma falado na live (transcrição e textos da IA). Opcional: o serviço antigo não manda (= padrão do serviço). */
language?: string;
/** Monitor pausado por você ter parado uma sessão à mão: não grava de novo até religar. Opcional (serviço antigo). */
monitorPausedAt?: string | null;
/** Sessão que você parou e motivou a pausa. */
monitorPausedBySession?: number | null;
};
export type SessionStatus = "starting" | "recording" | "processing" | "done" | "stopped" | "error" | "interrupted";
@@ -82,6 +99,8 @@ export type ClipperSession = {
hasOwnSettings?: boolean;
/** O que a captura gravou de fato (1º bloco de cada execução). null = sessão antiga ou ainda sem bloco; ausente = serviço antigo. */
capture?: CaptureInfo | null;
/** Idioma falado na live (copiado da fonte ao criar a sessão). Opcional: o serviço antigo não manda. */
language?: string;
};
export type GameSource = "platform" | "screen" | "user" | "";
@@ -159,6 +178,8 @@ export type Clip = {
edit?: { updatedAt: string; exportedAt: string | null; cover: string | null; origin?: "ai" | "user" | null } | null;
/** Formato do vídeo renderizado. Opcional: o serviço antigo não manda (ausente = vertical). */
aspect?: Aspect;
/** Idioma da sessão de origem (resolvido pelo serviço). Opcional: o serviço antigo não manda (= padrão, pt-BR). */
language?: string;
};
/* ---------- Configuração do corte ---------- */
@@ -254,15 +275,34 @@ export function layerFrom(draft: CutSettings, base: CutSettings, own: CutLayer |
/* ---------- Jogos e emotes ---------- */
/** Missão do jogo (só quando a lista já é pública): nome oficial, capítulo/ato, resumo e o que marca o fim dela. */
export type GameMission = { name: string; chapter: string; summary: string; completion_triggers: string[] };
export type GameProfile = {
name: string; summary: string; genre: string;
mechanics: string[]; clip_worthy: string[]; avoid: string[]; jargon: string[]; news: string[]; sources: string[];
/** Hashtags do jogo (a 1ª é a principal): entram em toda legenda de corte deste jogo, depois da do canal. */
hashtags?: string[];
// Opcionais: perfis antigos e o serviço antigo não mandam.
/** Outros nomes do jogo ("GTA 6", "GTA VI"): categoria e tela caem no mesmo perfil. */
aliases?: string[];
/** [] = a lista de missões ainda não é pública. */
missions?: GameMission[];
/** Sinais gerais de fim de missão/objetivo (banner, tela de resultado, fala): a IA termina o corte logo depois. */
end_triggers?: string[];
};
export type Game = {
id: string; name: string; status: "pending" | "ready" | "error"; error: string | null;
model: string | null; researchedAt: string | null; profile: GameProfile | null;
model: string | null; researchedAt: string | null;
/** Perfil em português: o que o painel mostra. */
profile: GameProfile | null;
/** Perfil em inglês: o que vai para a IA. null/ausente = ainda não traduzido (a IA usa o `profile`). */
profileAi?: GameProfile | null;
/** Idioma do `profileAi` ("en-US"). */
aiLanguage?: string;
/** Quando uma versão foi gerada a partir da outra. */
translatedAt?: string | null;
/** União dos aliases das duas versões. */
aliases?: string[];
/** Última edição à mão ou por pedido seu à IA (serviço antigo não manda). */
editedAt?: string | null;
/** Pedidos que você fez à IA; voltam em toda pesquisa nova. */
@@ -321,6 +361,25 @@ export function useClipperAction(onDone?: () => void) {
return { pending, message, setMessage, run };
}
/* ---------- Idiomas ---------- */
/** Idiomas que o Clipador conhece (transcrição, textos da IA e público dos canais). O 1º é o padrão. */
export const LANGUAGES: { id: string; label: string; short: string }[] = [
{ id: "pt-BR", label: "Português (Brasil)", short: "PT" },
{ id: "en-US", label: "English (US)", short: "EN" },
{ id: "es-419", label: "Español (Latinoamérica)", short: "ES" },
];
/** Nome legível do idioma ("Português (Brasil)"); código desconhecido volta como está. */
export function languageLabel(code: string | null | undefined): string {
return LANGUAGES.find((l) => l.id === code)?.label ?? (code || "—");
}
/** Sigla curta do idioma ("PT", "EN"); código desconhecido vira a parte antes do hífen em maiúsculas. */
export function languageShort(code: string | null | undefined): string {
return LANGUAGES.find((l) => l.id === code)?.short ?? (code ? code.split("-")[0].toUpperCase() : "—");
}
/* ---------- Rótulos ---------- */
export const PLATFORM_LABEL: Record<ClipperPlatform, string> = { twitch: "Twitch", youtube: "YouTube", kick: "Kick" };
@@ -376,7 +435,7 @@ export const MODE_LABEL: Record<LayoutMode, { label: string; hint: string }> = {
export const TAG_LABEL: Record<keyof ClipTags, string> = { risada: "risada", susto: "susto", hype: "hype", clip: "“clip” no chat" };
export const PROVIDER_LABEL: Record<JudgeProvider, string> = { codex: "Codex (GPT)", claude: "Claude", off: "Desligado" };
export const PROVIDER_LABEL: Record<JudgeProvider, string> = { codex: "Codex (GPT)", claude: "Claude", gemini: "Gemini", off: "Desligado" };
/** Sessões que ainda mudam sozinhas (vale consultar de novo). */
export const ACTIVE_SESSION: SessionStatus[] = ["starting", "recording", "processing"];
@@ -0,0 +1,192 @@
"use client";
// Modal de um corte: vídeo e sinais à esquerda; estado, publicação, veredito da IA, título/legenda, ajuste do trecho e
// transcrição à direita. No rodapé, anterior/próximo (percorre a lista filtrada, na ordem exibida; ← → no teclado
// fora de campos de texto), as ações da etapa e "Apagar". Aprovar ou rejeitar pula sozinho para o próximo corte
// (fluxo de decidir em sequência); sem próximo, fecha.
import { useEffect, useState } from "react";
import { CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, languageLabel, useClipperAction, type Clip, type ClipperSession } from "./clipper-client";
import {
ChatSignals, ClipActions, ClipMedia, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip,
} from "./clipper-clip-parts";
import { Dialog } from "./dialog";
import { ArrowLeftIcon, ArrowRightIcon, CheckIcon, ClockIcon } from "./icons";
import type { PublishJob } from "./publishing-client";
import { PublishChips, TextLink } from "./publishing-ui";
import { Badge, Button, Feedback, Input, Spinner, Textarea, cx } from "./ui";
export function ClipDialog({ clip, name, session, position, onPrev, onNext, onClose, onChanged, publishJobs, onPublished, deleting, onDelete }: {
clip: Clip;
name: string;
session: ClipperSession | undefined;
/** Posição na lista filtrada (1-based) e total; null = o corte não está mais na lista exibida. */
position: { index: number; total: number } | null;
/** null = não há anterior/próximo. */
onPrev: (() => void) | null;
onNext: (() => void) | null;
onClose: () => void;
onChanged: () => void;
/** Jobs de publicação deste corte (etapa Aprovados); null = não lidos. */
publishJobs: PublishJob[] | null;
onPublished: () => void;
deleting: boolean;
onDelete: DeleteClip;
}) {
// ← → trocam de corte quando o foco não está num campo de texto (o vídeo tem as próprias teclas).
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey) return;
const t = e.target as HTMLElement | null;
if (t && (t.closest("input, textarea, select, video, [contenteditable=true]"))) return;
if (e.key === "ArrowLeft" && onPrev) { e.preventDefault(); onPrev(); }
if (e.key === "ArrowRight" && onNext) { e.preventDefault(); onNext(); }
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [onPrev, onNext]);
const status = CLIP_STATUS[clip.status];
const situation = situationLabel(clip);
return (
<Dialog open onClose={onClose} size="lg" dismissOnBackdrop
eyebrow={<>Corte #{clip.id} · {name} · sessão #{clip.sessionId}</>}
title={clip.title || `Corte ${clip.id}`}
description={<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
<Badge tone={status.tone} pulse={status.pulse}>{status.label}</Badge>
<span>{situation ?? SOURCE_LABEL[clip.source]}</span>
<span className="inline-flex items-center gap-1 tabular-nums"><ClockIcon size={13} />{formatDuration(clip.durationS)} · {formatClock(clip.startS)}–{formatClock(clip.endS)}</span>
{clip.aspect === "horizontal" && <span>horizontal 16:9</span>}
{session?.language && <span title="Idioma da live">{languageLabel(session.language)}</span>}
</span>}
footer={<ClipFooter key={clip.id} clip={clip} position={position} onPrev={onPrev} onNext={onNext} onClose={onClose}
onChanged={onChanged} publishJobs={publishJobs} onPublished={onPublished} deleting={deleting} onDelete={onDelete} />}>
<ClipBody key={clip.id} clip={clip} onChanged={onChanged} publishJobs={publishJobs} />
</Dialog>
);
}
/** Corpo do modal. `key` por corte: rascunho de título/legenda e versão do vídeo começam do zero a cada corte. */
function ClipBody({ clip, onChanged, publishJobs }: { clip: Clip; onChanged: () => void; publishJobs: PublishJob[] | null }) {
const { pending, message, run } = useClipperAction(onChanged);
const base = `clips/${clip.id}`;
const busy = clip.status === "candidate" || clip.status === "pending" || clip.status === "rendering";
const editable = !busy && clip.status !== "published";
// Rascunho de título e legenda: a consulta periódica não apaga o que está sendo digitado.
const [saved, setSaved] = useState({ title: clip.title, caption: clip.caption });
const [title, setTitle] = useState(clip.title);
const [caption, setCaption] = useState(clip.caption);
if (saved.title !== clip.title || saved.caption !== clip.caption) {
setSaved({ title: clip.title, caption: clip.caption });
if (title === saved.title) setTitle(clip.title);
if (caption === saved.caption) setCaption(clip.caption);
}
const textDirty = title !== clip.title || caption !== clip.caption;
// Versão do vídeo: muda quando um render termina (mesmo caminho de arquivo, conteúdo novo).
const [videoVersion, setVideoVersion] = useState(clip.updatedAt);
const [lastStatus, setLastStatus] = useState(clip.status);
if (lastStatus !== clip.status) {
setLastStatus(clip.status);
if (lastStatus === "candidate" || lastStatus === "pending" || lastStatus === "rendering") setVideoVersion(clip.updatedAt);
}
const showPublication = clip.status === "approved" || clip.status === "published";
return (
<div className="grid gap-6 md:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">
<div className="grid content-start gap-4">
<ClipMedia clip={clip} version={videoVersion} />
<ChatSignals clip={clip} />
<FaceSignal clip={clip} />
</div>
<div className="grid min-w-0 content-start gap-5">
{showPublication && (
<section aria-label="Publicação nas redes" className="grid gap-1.5">
<h3 className="text-eyebrow font-semibold text-fg-subtle uppercase">Publicação</h3>
{publishJobs
? <PublishChips jobs={publishJobs} showAccount={new Set(publishJobs.map((j) => j.accountId)).size > 1}
emptyText={<>Ainda não foi para nenhuma rede. Use “Publicar” abaixo para escolher o canal e as redes. <TextLink href="/publishing">Abrir Publicações</TextLink></>} />
: <p className="flex items-center gap-2 text-xs text-fg-subtle"><Spinner className="size-3.5" />Lendo o estado da publicação…</p>}
</section>
)}
<section aria-label="Veredito da IA" className="grid gap-3">
<JudgeVerdict clip={clip} />
</section>
{clip.status === "error" && clip.error && (
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 font-mono text-xs break-words text-danger">{clip.error}</p>
)}
<form className="grid gap-3" onSubmit={(e) => {
e.preventDefault();
void run("text", () => clipperCall<Clip>(base, "PATCH", { title, caption }), "Título e legenda salvos.");
}}>
<label className="grid gap-1.5">
<span className="text-[0.8125rem] font-medium text-fg-muted">Título</span>
<Input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={100} disabled={!editable} className="h-9" />
</label>
<label className="grid gap-1.5">
<span className="text-[0.8125rem] font-medium text-fg-muted">Legenda do post</span>
<Textarea value={caption} onChange={(e) => setCaption(e.target.value)} rows={3} maxLength={2200} disabled={!editable} className="text-[0.8125rem]" />
</label>
{textDirty && (
<div className="flex flex-wrap items-center gap-2">
<Button type="submit" variant="secondary" size="sm" disabled={pending !== null}>
{pending === "text" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar texto
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => { setTitle(clip.title); setCaption(clip.caption); }}>Desfazer</Button>
</div>
)}
</form>
{editable && <TrimControl clip={clip} pending={pending} run={run} />}
{clip.transcript && (
<details className="group rounded-control border border-line bg-sunken/30 px-3 py-2 text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">Transcrição</summary>
<p className="mt-2 leading-relaxed text-fg-muted">{clip.transcript}</p>
</details>
)}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</div>
);
}
/** Rodapé: anterior/próximo à esquerda, ações da etapa no meio, apagar à direita. */
function ClipFooter({ clip, position, onPrev, onNext, onClose, onChanged, publishJobs, onPublished, deleting, onDelete }: {
clip: Clip; position: { index: number; total: number } | null; onPrev: (() => void) | null; onNext: (() => void) | null; onClose: () => void;
onChanged: () => void; publishJobs: PublishJob[] | null; onPublished: () => void; deleting: boolean; onDelete: DeleteClip;
}) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const publish = publishJobs ? { jobs: publishJobs, onDone: (m: { ok: boolean; text: string }) => { setMessage(m); onPublished(); } } : null;
return (
<div className="grid w-full gap-2">
<div className="flex w-full flex-wrap items-center gap-x-3 gap-y-2">
<div className="flex items-center gap-1" role="group" aria-label="Navegar entre os cortes da lista">
<Button variant="ghost" size="sm" disabled={!onPrev} onClick={() => onPrev?.()} aria-label="Corte anterior (seta para a esquerda)" title="Anterior (←)">
<ArrowLeftIcon size={15} />
</Button>
<span className="min-w-14 text-center text-xs text-fg-subtle tabular-nums">{position ? `${position.index} de ${position.total}` : "fora da lista"}</span>
<Button variant="ghost" size="sm" disabled={!onNext} onClick={() => onNext?.()} aria-label="Próximo corte (seta para a direita)" title="Próximo (→)">
<ArrowRightIcon size={15} />
</Button>
</div>
<ClipActions clip={clip} pending={pending} run={run} publish={publish} className="mx-auto"
onDecided={() => { if (onNext) onNext(); else onClose(); }} />
<div className={cx("ml-auto", !onNext && "")}>
<DeleteControl clip={clip} deleting={deleting} disabled={pending !== null}
onDelete={async (c, confirmPublished) => {
const ok = await onDelete(c, confirmPublished);
if (ok) { if (onNext) onNext(); else if (onPrev) onPrev(); else onClose(); }
return ok;
}} />
</div>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
+429
View File
@@ -0,0 +1,429 @@
"use client";
// Peças de UM corte do Clipador, usadas pela lista (/clipper) e pelo modal do corte: vídeo/miniatura, veredito da IA
// (proposta da varredura, análise do analista, nota do editor), sinais do chat e do rosto, ajuste fino de início/fim,
// ações por etapa (aprovar, rejeitar, publicar, re-renderizar, mandar de novo para a IA, editar) e "Apagar" com
// confirmação curta no lugar. Nada aqui busca dados: tudo vem por props; cada ação chama `run` (useClipperAction).
import { useEffect, useRef, useState, type ReactNode } from "react";
import {
ACTIVE_CLIP, CLIP_STATUS, FACE_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf, clipperCall, formatClock, formatDuration, formatScore,
type Clip, type ClipAnalysis, type ClipTags, type Situation, type useClipperAction,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
import { AlertIcon, CheckIcon, EyeIcon, RefreshIcon, ScissorsIcon, SparkIcon, TrashIcon, UndoIcon, XIcon } from "./icons";
import type { PublishJob } from "./publishing-client";
import { Badge, Button, LinkButton, Spinner, cx, fileUrl } from "./ui";
export type Run = ReturnType<typeof useClipperAction>["run"];
/** Apaga um corte; `confirmPublished` = o usuário já aceitou apagar só a cópia local de um corte publicado. */
export type DeleteClip = (clip: Clip, confirmPublished: boolean) => Promise<boolean>;
/** Duração mínima e máxima de um corte (limites do serviço; Shorts aceita até 180 s). */
export const MIN_CLIP_S = 5;
export const MAX_CLIP_S = 180;
/** Passos do ajuste: o início volta bastante (a ação costuma vir antes da reação); o fim estica um pouco. */
const START_STEPS = [-30, -10, -5, -2, 2] as const;
const END_STEPS = [-2, 2, 5, 10] as const;
/** O serviço recusa apagar enquanto a IA avalia (`candidate`) ou o FFmpeg renderiza (`rendering`). */
export function canDelete(clip: Clip): boolean {
return !UNDELETABLE_CLIP.includes(clip.status);
}
/** Nota da IA (0–10) do corte; `null` quando a IA ainda não julgou ou deu erro. */
export function judgeScore(clip: Clip): number | null {
return clip.judge && "score" in clip.judge ? clip.judge.score : null;
}
/** Situação que o analista viu ("falha engraçada", "lag ou bug"…), ou null sem análise. */
export function situationLabel(clip: Clip): string | null {
const a = clip.judge && "analysis" in clip.judge ? clip.judge.analysis : null;
if (!a?.situation) return null;
return SITUATION_LABEL[a.situation as Situation] ?? a.situation;
}
/* ---------- Apagar com confirmação no lugar ---------- */
export function DeleteControl({ clip, deleting, disabled, onDelete }: { clip: Clip; deleting: boolean; disabled: boolean; onDelete: DeleteClip }) {
const [asking, setAsking] = useState(false);
const openRef = useRef<HTMLButtonElement>(null);
const cancelRef = useRef<HTMLButtonElement>(null);
const wasAsking = useRef(false);
useEffect(() => {
// Foco: ao perguntar vai para Cancelar (Enter de novo não apaga por engano); ao desistir volta para Apagar.
if (asking) cancelRef.current?.focus();
else if (wasAsking.current) openRef.current?.focus();
wasAsking.current = asking;
}, [asking]);
const published = clip.status === "published";
if (!asking) {
return (
<Button ref={openRef} variant="ghost" size="sm" disabled={disabled || deleting} onClick={() => setAsking(true)}
className="text-fg-muted hover:bg-danger-soft hover:text-danger" aria-label={`Apagar o corte ${clip.id}`}>
{deleting ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
);
}
return (
<div role="group" aria-label={`Confirmar: apagar o corte ${clip.id}`}
onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); setAsking(false); } }}
// Mesma altura do botão "Apagar" (h-8): perguntar não muda a altura do cartão.
className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-danger">{published ? "Publicado: apagar só a cópia local?" : "Apagar vídeo e edição?"}</span>
<Button variant="danger" size="sm" disabled={deleting}
onClick={async () => {
// Deu certo: o foco já foi para o aviso (o cartão vai sumir); não volta para cá.
if (await onDelete(clip, published)) wasAsking.current = false;
setAsking(false);
}}>
{deleting ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
<Button ref={cancelRef} variant="ghost" size="sm" disabled={deleting} onClick={() => setAsking(false)}>Cancelar</Button>
</div>
);
}
/* ---------- Cartão do corte ---------- */
export function ClipMedia({ clip, version }: { clip: Clip; version: string }) {
const busy = ACTIVE_CLIP.includes(clip.status);
const poster = clip.thumb ? fileUrl(clip.thumb) : undefined;
const frame = aspectOf(clip) === "horizontal" ? "aspect-video" : "aspect-9/16 max-sm:max-w-60";
if (clip.file && !busy) {
return (
<video key={version} controls preload="metadata" poster={poster} aria-label={`Vídeo do corte: ${clip.title || clip.id}`}
src={`${fileUrl(clip.file)}&v=${encodeURIComponent(version)}`}
className={cx(frame, "w-full self-start rounded-control border border-line bg-sunken object-contain")} />
);
}
return (
<div className={cx(frame, "relative grid w-full self-start overflow-hidden rounded-control border border-line bg-sunken")}>
{/* eslint-disable-next-line @next/next/no-img-element -- miniatura local servida por /api/files */}
{poster && <img src={poster} alt="" className="absolute inset-0 size-full object-cover opacity-35" />}
<div className="relative grid place-content-center justify-items-center gap-2 p-4 text-center text-xs text-fg-muted">
{busy ? <Spinner className="size-5 text-accent" /> : <ScissorsIcon size={22} className="text-fg-subtle" />}
<span>{busy ? CLIP_STATUS[clip.status].label : clip.status === "discarded" ? "Não renderizado: a IA descartou" : "Sem vídeo"}</span>
</div>
</div>
);
}
export function JudgeVerdict({ clip }: { clip: Clip }) {
const judge = clip.judge;
if (!judge) {
return (
<>
<Proposal clip={clip} />
<p className="flex items-center gap-2 text-xs text-fg-subtle">
<SparkIcon size={14} className={clip.status === "candidate" ? "text-violet" : undefined} />
{clip.status === "candidate" ? "A IA está avaliando este momento…"
: clip.source === "manual" ? "Corte manual: não passa pela IA."
: "Sem veredito da IA (juiz desligado ou avaliado só pela heurística)."}
</p>
</>
);
}
if ("error" in judge) {
return (
<>
<Proposal clip={clip} />
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertIcon size={14} className="mt-px" />
<span>A IA não conseguiu avaliar: <span className="break-words">{judge.error}</span></span>
</p>
</>
);
}
const tone = judge.keep ? (judge.score >= 7 ? "text-success" : "text-fg") : "text-warning";
const a = judge.analysis;
return (
<>
<Proposal clip={clip} />
{a && <AnalysisView analysis={a} model={judge.analystModel} />}
<div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3.5 gap-y-1 rounded-control border border-violet/20 bg-violet-soft/40 px-3.5 py-2.5">
<div className="row-span-2 grid justify-items-center leading-none" aria-label={`Nota da IA: ${formatScore(judge.score)} de 10`}>
<span className={cx("font-display text-2xl font-semibold tabular-nums", tone)}>{formatScore(judge.score)}</span>
<span className="mt-1 text-[0.6875rem] text-fg-subtle">de 10</span>
</div>
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5 font-semibold text-violet"><SparkIcon size={13} />{a ? "Editor" : "Juiz"}</span>
<Badge tone={judge.keep ? "success" : "warning"} dot={false}>{judge.keep ? "manteve" : "descartou"}</Badge>
<span className="font-mono text-[0.6875rem] text-fg-subtle">{judge.model}</span>
</p>
{judge.reason && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{judge.reason}</p>}
</div>
</>
);
}
/** Corte da varredura (source "ai"): a proposta que a IA fez ao assistir a janela, antes dos juízes. */
export function Proposal({ clip }: { clip: Clip }) {
const r = clip.reasons ?? {};
if (clip.source !== "ai" || !(r.proposalTitle || r.proposalReason)) return null;
return (
<div className="grid gap-1 rounded-control border border-info/20 bg-info-soft/40 px-3.5 py-2.5 text-xs">
<p className="flex flex-wrap items-center gap-2">
<span className="inline-flex items-center gap-1.5 font-semibold text-info"><EyeIcon size={13} />Varredura viu na tela</span>
{r.proposalScore !== undefined && <Badge tone="info" dot={false}>proposta {formatScore(r.proposalScore)}/10</Badge>}
{r.scanFromS !== undefined && r.scanToS !== undefined && <span className="text-fg-subtle">janela {formatClock(r.scanFromS)}–{formatClock(r.scanToS)}</span>}
</p>
{r.proposalTitle && <p className="font-medium text-fg">{r.proposalTitle}</p>}
{r.proposalReason && <p className="leading-relaxed text-fg-muted">{r.proposalReason}</p>}
</div>
);
}
/** O que o ANALISTA (1º juiz) entendeu: situação, o que aconteceu, confiança; tela/fala/chat expansíveis. */
export function AnalysisView({ analysis: a, model }: { analysis: ClipAnalysis; model?: string }) {
const confidence = Math.round(Math.min(1, Math.max(0, a.confidence ?? 0)) * 100);
const details = [
{ label: "Tela", text: a.screen }, { label: "Fala", text: a.speech }, { label: "Chat", text: a.chat_meaning }, { label: "Gancho", text: a.hook },
].filter((d) => d.text);
return (
<div className="grid gap-2 rounded-control border border-line bg-sunken/40 px-3.5 py-2.5">
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="font-semibold text-fg">O que aconteceu</span>
<Badge tone="accent" dot={false}>{SITUATION_LABEL[a.situation as Situation] ?? a.situation}</Badge>
<span className={cx("tabular-nums", confidence >= 70 ? "text-success" : confidence >= 40 ? "text-fg-muted" : "text-warning")}>
confiança {confidence}%
</span>
{model && <span className="font-mono text-[0.6875rem] text-fg-subtle">analista {model}</span>}
</p>
{a.what_happened && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{a.what_happened}</p>}
{details.length > 0 && (
<details className="text-xs">
<summary className="cursor-pointer text-fg-subtle select-none hover:text-fg">Tela, fala e chat</summary>
<dl className="mt-2 grid gap-1.5">
{details.map((d) => (
<div key={d.label} className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-2">
<dt className="font-semibold text-fg-subtle">{d.label}</dt>
<dd className="leading-relaxed text-fg-muted">{d.text}</dd>
</div>
))}
</dl>
</details>
)}
</div>
);
}
export function ChatSignals({ clip }: { clip: Clip }) {
const { peakRatio, messages, tags, topMessages, emotes } = clip.reasons ?? {};
const tagEntries = Object.entries(tags ?? {}).filter(([, n]) => (n ?? 0) > 0) as [keyof ClipTags, number][];
const emoteEntries = Object.entries(emotes ?? {}).filter(([, n]) => n > 0).sort((x, y) => y[1] - x[1]);
if (peakRatio === undefined && messages === undefined && tagEntries.length === 0 && emoteEntries.length === 0 && !topMessages?.length) return null;
return (
<div className="grid gap-2">
<div className="flex flex-wrap items-center gap-1.5 text-xs">
{peakRatio !== undefined && <Chip strong>pico {formatScore(peakRatio)}× o normal</Chip>}
{messages !== undefined && <Chip>{messages} mensage{messages === 1 ? "m" : "ns"}</Chip>}
{tagEntries.map(([tag, n]) => <Chip key={tag} accent>{TAG_LABEL[tag] ?? tag} ×{n}</Chip>)}
</div>
{emoteEntries.length > 0 && (
<ul aria-label="Emotes do chat no pico" className="flex flex-wrap gap-1.5 text-xs">
{emoteEntries.slice(0, 8).map(([name, n]) => (
<li key={name} className="inline-flex h-6 items-center gap-1 rounded-full border border-option-b/25 bg-option-b-soft px-2.5 font-mono text-option-b">
{name}<span className="text-option-b/70">×{n}</span>
</li>
))}
</ul>
)}
{topMessages && topMessages.length > 0 && (
<ul aria-label="Mensagens do chat no pico" className="flex flex-wrap gap-1.5">
{topMessages.slice(0, 6).map((m, i) => (
<li key={i} title={m}
className="max-w-56 truncate rounded-lg border border-line bg-sunken/50 px-2 py-1 text-[0.75rem] text-fg-muted">
{m}
</li>
))}
</ul>
)}
</div>
);
}
/** Reação no rosto do streamer (rastreio local): rótulo, intensidade relativa ao normal dele e quando aconteceu. */
export function FaceSignal({ clip }: { clip: Clip }) {
const face = clip.reasons?.face;
if (!face || face.label === "neutro") return null;
const support = clip.reasons?.support;
return (
<p className="flex flex-wrap items-center gap-1.5 text-xs" aria-label="Reação no rosto do streamer">
<Chip accent>rosto: {FACE_LABEL[face.label] ?? face.label}{face.strong ? " forte" : ""}</Chip>
<span title="Quantos desvios acima do rosto normal deste streamer (3 = começa a contar; 6 ou mais = forte)">
<Chip>intensidade {formatScore(face.intensity)}</Chip>
</span>
<span className="text-fg-subtle" title={`começou em ${formatClock(face.onsetS)}`}>pico em {formatClock(face.peakS)}</span>
{clip.source === "face" && support && (
<span className="text-fg-subtle">com apoio {support.chatReactions >= 2 ? `do chat (${support.chatReactions} reações)` : "do áudio"}</span>
)}
</p>
);
}
function Chip({ children, strong = false, accent = false }: { children: ReactNode; strong?: boolean; accent?: boolean }) {
return (
<span className={cx("inline-flex h-6 items-center rounded-full border px-2.5 font-medium whitespace-nowrap",
accent ? "border-accent/25 bg-accent-soft text-accent" : strong ? "border-line-strong bg-raised text-fg" : "border-line bg-raised/60 text-fg-muted")}>
{children}
</span>
);
}
export function TrimControl({ clip, pending, run }: { clip: Clip; pending: string | null; run: Run }) {
const [trim, setTrim] = useState<{ start: number; end: number } | null>(null);
const start = trim?.start ?? clip.startS;
const end = trim?.end ?? clip.endS;
const dirty = trim !== null && (trim.start !== clip.startS || trim.end !== clip.endS);
const length = end - start;
const valid = length >= MIN_CLIP_S && length <= MAX_CLIP_S;
const nudge = (step: number, edge: "start" | "end") => {
const next = edge === "start" ? { start: Math.max(0, start + step), end } : { start, end: end + step };
const span = next.end - next.start;
const ok = span >= MIN_CLIP_S && span <= MAX_CLIP_S && !(edge === "start" && step < 0 && start <= 0);
const word = step < 0 ? "antes" : "depois";
return (
<button key={`${edge}${step}`} type="button" disabled={!ok || pending !== null} onClick={() => setTrim(next)}
aria-label={`${edge === "start" ? "Começar" : "Terminar"} ${Math.abs(step)} segundos ${word}`}
className={cx("h-7 rounded-md px-1.5 font-mono text-xs transition-colors hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-40",
Math.abs(step) >= 10 ? "text-accent" : "text-fg-muted")}>
{step > 0 ? "+" : "−"}{Math.abs(step)} s
</button>
);
};
const delta = (now: number, was: number) => {
const d = Math.round(now - was);
return d === 0 ? null : <span className="text-accent"> ({d > 0 ? "+" : "−"}{Math.abs(d)} s)</span>;
};
return (
<fieldset className="grid gap-2">
<legend className="mb-1.5 text-[0.8125rem] font-medium text-fg-muted">Ajuste do trecho</legend>
<div className="flex flex-wrap items-center gap-2">
<span className="inline-flex flex-wrap items-center gap-0.5 rounded-control border border-line-strong bg-sunken/60 p-0.5">
{START_STEPS.filter((st) => st < 0).map((st) => nudge(st, "start"))}
<span className="px-1.5 text-xs text-fg-subtle">início <span className="font-mono text-fg tabular-nums">{formatClock(start)}</span>{delta(start, clip.startS)}</span>
{START_STEPS.filter((st) => st > 0).map((st) => nudge(st, "start"))}
</span>
<span className="inline-flex flex-wrap items-center gap-0.5 rounded-control border border-line-strong bg-sunken/60 p-0.5">
{END_STEPS.filter((st) => st < 0).map((st) => nudge(st, "end"))}
<span className="px-1.5 text-xs text-fg-subtle">fim <span className="font-mono text-fg tabular-nums">{formatClock(end)}</span>{delta(end, clip.endS)}</span>
{END_STEPS.filter((st) => st > 0).map((st) => nudge(st, "end"))}
</span>
<span className={cx("text-xs tabular-nums", !valid ? "text-danger" : dirty ? "text-accent" : "text-fg-subtle")}>{formatDuration(length)}</span>
</div>
{dirty && (
<div className="flex flex-wrap items-center gap-2">
<Button type="button" size="sm" variant="secondary" disabled={pending !== null || !valid}
onClick={async () => {
const done = await run("trim", () => clipperCall<Clip>(`clips/${clip.id}`, "PATCH", { startS: start, endS: end }),
"Novo trecho salvo. O corte voltou para a fila de render.");
if (done) setTrim(null);
}}>
{pending === "trim" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Aplicar e re-renderizar
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setTrim(null)}>Desfazer</Button>
<span className="text-xs text-fg-subtle">Entre {MIN_CLIP_S} e {MAX_CLIP_S} s. A gravação inteira fica guardada por cerca de 6 h.</span>
</div>
)}
</fieldset>
);
}
export function ClipActions({ clip, pending, run, publish, onDecided, className }: {
clip: Clip; pending: string | null; run: Run;
/** Aprovados/publicados: botão "Publicar" (null enquanto o estado da publicação não foi lido). */
publish: { jobs: PublishJob[]; onDone: (m: { ok: boolean; text: string }) => void } | null;
/** Depois de aprovar ou rejeitar com sucesso (o modal usa para pular ao próximo corte). */
onDecided?: () => void;
className?: string;
}) {
const base = `clips/${clip.id}`;
const icon = (key: string, fallback: ReactNode) => (pending === key ? <Spinner className="size-3.5" /> : fallback);
const setStatus = async (key: string, status: "approved" | "rejected" | "ready", text: string) => {
const done = await run(key, () => clipperCall<Clip>(base, "PATCH", { status }), text);
if (done && status !== "ready") onDecided?.();
return done;
};
const render = (text: string) => run("render", () => clipperCall<Clip>(`${base}/render`, "POST"), text);
const rejudge = () => run("rejudge", () => clipperCall<Clip>(`${base}/rejudge`, "POST"), "Mandado de novo para a IA.");
const disabled = pending !== null;
const rejudgeButton = clip.source !== "manual" && (
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void rejudge()}>
{icon("rejudge", <SparkIcon size={15} />)}Mandar de novo para a IA
</Button>
);
let buttons: ReactNode = null;
switch (clip.status) {
case "ready":
buttons = <>
<Button size="sm" disabled={disabled} onClick={() => void setStatus("approve", "approved", "Corte aprovado.")}>
{icon("approve", <CheckIcon size={15} />)}Aprovar
</Button>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("reject", "rejected", "Corte rejeitado.")}>
{icon("reject", <XIcon size={15} />)}Rejeitar
</Button>
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void render("Re-render pedido. O corte voltou para a fila.")}>
{icon("render", <RefreshIcon size={15} />)}Re-renderizar
</Button>
{rejudgeButton}
</>;
break;
case "approved":
buttons = <>
{publish && <ClipPublishButton clip={clip} jobs={publish.jobs} onDone={publish.onDone} />}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Aprovação desfeita.")}>
{icon("undo", <UndoIcon size={15} />)}Desfazer aprovação
</Button>
</>;
break;
case "published":
// Publicado: dá para mandar para outra rede ou outro canal; editar não (o vídeo já está no ar).
return publish ? (
<div className={cx("flex flex-wrap items-center gap-2", className)}>
<ClipPublishButton clip={clip} jobs={publish.jobs} onDone={publish.onDone} variant="secondary" />
</div>
) : null;
case "rejected":
buttons = <>
{clip.file && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Corte de volta para aprovar.")}>
{icon("undo", <UndoIcon size={15} />)}Voltar para aprovar
</Button>}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void render("Re-render pedido.")}>
{icon("render", <RefreshIcon size={15} />)}Re-renderizar
</Button>
</>;
break;
case "discarded":
buttons = <>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Render forçado: o corte entrou na fila.")}>
{icon("render", <ScissorsIcon size={15} />)}Forçar render
</Button>
{rejudgeButton}
</>;
break;
case "error":
buttons = <>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Tentando de novo: o corte entrou na fila.")}>
{icon("render", <RefreshIcon size={15} />)}Tentar render de novo
</Button>
{rejudgeButton}
</>;
break;
default:
// Na fila (esperando a IA ou o render): nada a decidir ainda; apagar fica com quem chama (DeleteControl).
return null;
}
return (
<div className={cx("flex flex-wrap items-center gap-2", className)}>
{buttons}
{/* Editor em tela cheia: abre o projeto que a IA montou (ou o seu) para ajustar e exportar de novo. */}
<LinkButton href={`/clipper/edit/${clip.id}`} variant="secondary" size="sm">
<ScissorsIcon size={15} />{clip.edit?.origin === "user" ? "Continuar edição" : "Editar"}
</LinkButton>
</div>
);
}
+233
View File
@@ -0,0 +1,233 @@
"use client";
// Lista de cortes: uma linha por corte com o que decide (miniatura, título, fonte/sessão/trecho, situação, nota da IA,
// duração, estado ou publicação, ações rápidas da etapa). Clique na linha (fora de botões) ou Enter abre o modal do
// corte; a linha aberta fica destacada. A caixa de seleção só aparece no hover/foco ou no modo de seleção.
import { type KeyboardEvent, type MouseEvent, type ReactNode } from "react";
import {
CLIP_STATUS, SOURCE_LABEL, clipperCall, formatClock, formatDuration, formatScore, languageShort, useClipperAction,
type Clip, type ClipperSession,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
import { canDelete, judgeScore, situationLabel, type DeleteClip } from "./clipper-clip-parts";
import type { QueueFilter } from "./clipper-queue";
import { ArrowRightIcon, CheckIcon, RefreshIcon, ScissorsIcon, SparkIcon, UndoIcon, XIcon } from "./icons";
import type { PublishJob } from "./publishing-client";
import { PublishChips } from "./publishing-ui";
import { Badge, Button, Feedback, Spinner, Table, THead, Td, Th, cx, fileUrl, formatRelative } from "./ui";
export type ClipTableProps = {
clips: Clip[];
sessions: ClipperSession[];
stage: QueueFilter;
nameOf: (clip: Clip) => string;
/** Idioma padrão do serviço: só mostra o chip de idioma quando a sessão do corte difere dele. */
defaultLanguage: string;
/** Etapa Aprovados: jobs de publicação por id do corte (null = ainda não lidos / etapa não é Aprovados). */
publishing: Map<string, PublishJob[]> | null;
onPublished: () => void;
onChanged: () => void;
onOpen: (clip: Clip) => void;
/** Corte aberto no modal (linha destacada). */
openId: number | null;
/** Modo de seleção ligado: a caixa aparece em todas as linhas. */
revealed: boolean;
selected: ReadonlySet<number>;
onSelect: (id: number, on: boolean) => void;
deleting: ReadonlySet<number>;
onDelete: DeleteClip;
};
export function ClipTable(props: ClipTableProps) {
const { clips, stage } = props;
const approved = stage === "approved";
return (
<Table className="bg-surface shadow-card">
<THead>
<Th className="w-8"><span className="sr-only">Selecionar</span></Th>
<Th className="w-14"><span className="sr-only">Miniatura</span></Th>
<Th>Corte</Th>
<Th className="max-lg:hidden">Situação</Th>
<Th className="w-20 text-right">Nota IA</Th>
<Th className="w-20 text-right max-md:hidden">Duração</Th>
<Th className={approved ? "min-w-48" : "w-40"}>{approved ? "Publicação" : "Estado"}</Th>
<Th className="text-right"><span className="sr-only">Ações</span></Th>
</THead>
<tbody>
{clips.map((clip) => <ClipRow key={clip.id} clip={clip} {...props} />)}
</tbody>
</Table>
);
}
/** Clique num botão, link, input ou texto selecionado não conta como "abrir a linha". */
function isInteractive(target: EventTarget | null): boolean {
return target instanceof Element && Boolean(target.closest("button, a, input, select, textarea, label, [role=dialog], video"));
}
function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, onPublished, onChanged, onOpen, openId, revealed, selected, onSelect, deleting, onDelete }:
ClipTableProps & { clip: Clip }) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const status = CLIP_STATUS[clip.status];
const isDeleting = deleting.has(clip.id);
const isSelected = selected.has(clip.id);
const open = openId === clip.id;
const name = nameOf(clip);
const title = clip.title || `Corte ${clip.id}`;
const session = sessions.find((s) => s.id === clip.sessionId);
const language = session?.language;
const score = judgeScore(clip);
const kept = clip.judge && "keep" in clip.judge ? clip.judge.keep : null;
const situation = situationLabel(clip);
const jobs = publishing?.get(String(clip.id)) ?? null;
const horizontal = clip.aspect === "horizontal";
const poster = clip.thumb ? fileUrl(clip.thumb) : null;
const onRowClick = (e: MouseEvent<HTMLTableRowElement>) => {
if (isInteractive(e.target) || window.getSelection()?.toString()) return;
onOpen(clip);
};
const onRowKey = (e: KeyboardEvent<HTMLTableRowElement>) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpen(clip); }
};
return (
<>
<tr tabIndex={0} aria-label={`Abrir o corte: ${title}`} onClick={onRowClick} onKeyDown={onRowKey} aria-current={open ? "true" : undefined}
className={cx("group/row cursor-pointer border-t border-line transition-colors first:border-t-0 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent",
open ? "bg-accent-soft/40" : isSelected ? "bg-raised/70" : "hover:bg-raised/40",
isDeleting && "opacity-50")}>
<Td className="pr-0 pl-3">
<input type="checkbox" checked={isSelected} disabled={!canDelete(clip) || isDeleting}
onChange={(e) => onSelect(clip.id, e.target.checked)}
aria-label={`Selecionar o corte ${clip.id}: ${title}`}
title={canDelete(clip) ? "Selecionar para apagar" : "A IA ou o render está trabalhando neste corte"}
className={cx("size-4 cursor-pointer accent-accent transition-opacity duration-150 motion-reduce:transition-none disabled:cursor-not-allowed",
!canDelete(clip)
? (revealed ? "opacity-40" : "opacity-0 group-hover/row:opacity-40 group-focus-within/row:opacity-40")
: revealed || isSelected ? "opacity-100" : "opacity-0 group-hover/row:opacity-100 group-focus-within/row:opacity-100")} />
</Td>
<Td className="px-2">
<span className={cx("relative grid shrink-0 place-items-center overflow-hidden rounded-md border border-line bg-sunken text-fg-subtle",
horizontal ? "h-9 w-16" : "h-16 w-9")}>
{/* eslint-disable-next-line @next/next/no-img-element -- miniatura local servida por /api/files */}
{poster ? <img src={poster} alt="" className="absolute inset-0 size-full object-cover" /> : <ScissorsIcon size={14} />}
</span>
</Td>
<Td>
<div className="grid min-w-0 max-w-[36rem] gap-0.5">
<p className="truncate font-medium text-fg" title={clip.title || undefined}>{title}</p>
<p className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span className="text-fg-muted">{name}</span>
<span aria-hidden="true">·</span>
<span>sessão #{clip.sessionId}</span>
<span aria-hidden="true">·</span>
<span className="tabular-nums">{formatClock(clip.startS)}–{formatClock(clip.endS)}</span>
<span aria-hidden="true">·</span>
<span title={new Date(clip.createdAt).toLocaleString("pt-BR")}>{formatRelative(clip.createdAt)}</span>
{language && language !== defaultLanguage && (
<span className="rounded-sm border border-line-strong px-1 font-mono text-[0.625rem] text-fg-muted" title={`Idioma da live: ${language}`}>{languageShort(language)}</span>
)}
{horizontal && <span className="rounded-sm border border-line-strong px-1 text-[0.625rem] text-fg-muted">16:9</span>}
</p>
</div>
</Td>
<Td className="max-lg:hidden">
<span className="flex flex-wrap items-center gap-1.5">
{situation
? <Badge tone="accent" dot={false}>{situation}</Badge>
: <Badge tone={clip.source === "manual" ? "info" : clip.source === "ai" ? "violet" : "neutral"} dot={false}>{SOURCE_LABEL[clip.source]}</Badge>}
</span>
</Td>
<Td className="text-right">
{score === null
? <span className="text-fg-subtle" title={clip.source === "manual" ? "Corte manual: não passa pela IA" : "Sem nota da IA"}>—</span>
: <span className={cx("font-display text-lg font-semibold tabular-nums", kept === false ? "text-warning" : score >= 7 ? "text-success" : "text-fg")}
title={kept === false ? "A IA descartou" : "Nota da IA (0–10)"}>{formatScore(score)}</span>}
</Td>
<Td className="text-right text-fg-muted tabular-nums max-md:hidden">{formatDuration(clip.durationS)}</Td>
<Td>
{stage === "approved" && jobs
? <PublishChips jobs={jobs} emptyText={<span className="inline-flex items-center gap-1.5"><Badge tone={status.tone}>{status.label}</Badge><span>ainda não foi para nenhuma rede</span></span>} />
: <Badge tone={status.tone} pulse={status.pulse}>{status.label}</Badge>}
</Td>
<Td className="text-right">
<div className="flex items-center justify-end gap-1.5">
<QuickActions clip={clip} pending={pending} run={run} jobs={jobs}
onPublished={(m) => { setMessage(m); onPublished(); }} />
<Button variant="ghost" size="sm" onClick={() => onOpen(clip)} aria-label={`Abrir o corte: ${title}`} title="Abrir" className="text-fg-muted">
<ArrowRightIcon size={15} /><span className="max-xl:sr-only">Abrir</span>
</Button>
</div>
</Td>
</tr>
{(message || (clip.status === "error" && clip.error)) && (
<tr className="border-t-0">
<td colSpan={8} className="px-4 pt-0 pb-3">
<div aria-live="polite" className="grid gap-2">
{clip.status === "error" && clip.error && !message && (
<p className="truncate font-mono text-xs text-danger" title={clip.error}>{clip.error}</p>
)}
{message && <Feedback ok={message.ok}>{message.text}</Feedback>}
</div>
</td>
</tr>
)}
</>
);
}
type Run = ReturnType<typeof useClipperAction>["run"];
/** Ações rápidas da etapa, na própria linha (o resto fica no modal). */
function QuickActions({ clip, pending, run, jobs, onPublished }: {
clip: Clip; pending: string | null; run: Run; jobs: PublishJob[] | null; onPublished: (m: { ok: boolean; text: string }) => void;
}) {
const base = `clips/${clip.id}`;
const disabled = pending !== null;
const icon = (key: string, fallback: ReactNode) => (pending === key ? <Spinner className="size-3.5" /> : fallback);
const setStatus = (key: string, status: "approved" | "rejected" | "ready", text: string) =>
run(key, () => clipperCall<Clip>(base, "PATCH", { status }), text);
const render = (text: string) => run("render", () => clipperCall<Clip>(`${base}/render`, "POST"), text);
const label = clip.title || `corte ${clip.id}`;
switch (clip.status) {
case "ready":
return <>
<Button size="sm" disabled={disabled} onClick={() => void setStatus("approve", "approved", "Corte aprovado.")} aria-label={`Aprovar: ${label}`}>
{icon("approve", <CheckIcon size={15} />)}Aprovar
</Button>
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("reject", "rejected", "Corte rejeitado.")} aria-label={`Rejeitar: ${label}`}>
{icon("reject", <XIcon size={15} />)}Rejeitar
</Button>
</>;
case "approved":
return <>
{jobs && <ClipPublishButton clip={clip} jobs={jobs} onDone={onPublished} />}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Aprovação desfeita.")} aria-label={`Desfazer aprovação: ${label}`}>
{icon("undo", <UndoIcon size={15} />)}<span className="max-xl:sr-only">Desfazer</span>
</Button>
</>;
case "published":
return jobs ? <ClipPublishButton clip={clip} jobs={jobs} onDone={onPublished} variant="secondary" /> : null;
case "rejected":
return clip.file ? (
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Corte de volta para aprovar.")} aria-label={`Voltar para aprovar: ${label}`}>
{icon("undo", <UndoIcon size={15} />)}Voltar para aprovar
</Button>
) : null;
case "discarded":
return (
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Render forçado: o corte entrou na fila.")} aria-label={`Forçar render: ${label}`}>
{icon("render", <ScissorsIcon size={15} />)}Forçar render
</Button>
);
case "error":
return (
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Tentando de novo: o corte entrou na fila.")} aria-label={`Tentar render de novo: ${label}`}>
{icon("render", <RefreshIcon size={15} />)}Tentar de novo
</Button>
);
default:
return clip.status === "candidate" ? <span className="inline-flex items-center gap-1.5 text-xs text-violet"><SparkIcon size={13} />IA avaliando</span> : null;
}
}
+239
View File
@@ -0,0 +1,239 @@
"use client";
// Subpágina Cortes (/clipper): barra de filtros (etapa, fonte, sessão, idioma, ordenação, seleção), a lista e o modal
// do corte. O estado fica na URL — ?stage= ?source= ?session= ?lang= (replaceState) e ?clip= (pushState: o "voltar"
// do navegador fecha o modal). Ao abrir a página sem ?session, a lista já vem filtrada pela 1ª sessão gravando agora
// (pedido do dono, 17/11/2026); depois vale o que você escolher. Os dados vêm do ClipperProvider (layout).
import { useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LANGUAGES, channelFromUrl, languageLabel, type Clip } from "./clipper-client";
import { ClipDialog } from "./clipper-clip-dialog";
import { ClipTable } from "./clipper-clip-table";
import { canDelete } from "./clipper-clip-parts";
import { useClipper, useClipperData } from "./clipper-provider";
import {
DeleteToast, FilterLabel, QUEUE_FILTERS, QUEUE_SORTS, SelectionPill, StageFilter, TabMenu, useClipDeletion, useClipPublishing, useQueueSort,
type QueueFilter, type QueueSort,
} from "./clipper-queue";
import { CheckIcon, PublishIcon, ScissorsIcon } from "./icons";
import { TextLink } from "./publishing-ui";
import { Button, EmptyState, Select, Spinner, cx } from "./ui";
/** Valor de ?source= para cortes sem fonte cadastrada (link solto). */
const NO_SOURCE = "none";
export function ClipsPage() {
return (
<Suspense fallback={<div role="status" className="flex items-center gap-3 py-6 text-sm text-fg-muted"><Spinner />Carregando os cortes…</div>}>
<ClipsPageInner />
</Suspense>
);
}
/** Lê e grava os filtros na URL (replace) e o corte aberto (push). */
function useQueryState() {
const params = useSearchParams();
const set = useCallback((changes: Record<string, string | null>, mode: "replace" | "push" = "replace") => {
const next = new URLSearchParams(window.location.search);
for (const [k, v] of Object.entries(changes)) {
if (v === null || v === "") next.delete(k); else next.set(k, v);
}
const query = next.toString();
const url = `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`;
if (mode === "push") window.history.pushState(null, "", url);
else window.history.replaceState(null, "", url);
}, []);
return { params, set };
}
function ClipsPageInner() {
const { clips, sessions, channels, status } = useClipperData();
const { nameOfClip, reload } = useClipper();
const { params, set } = useQueryState();
const defaultLanguage = status.settings.language;
const stageParam = params.get("stage");
const stage: QueueFilter = QUEUE_FILTERS.some((f) => f.id === stageParam) ? (stageParam as QueueFilter) : "ready";
const source = params.get("source") ?? "";
const sessionParam = params.get("session");
const sessionFilter = sessionParam && /^\d+$/.test(sessionParam) ? Number(sessionParam) : null;
const lang = params.get("lang") ?? "";
const clipParam = params.get("clip");
const openId = clipParam && /^\d+$/.test(clipParam) ? Number(clipParam) : null;
const [sort, setSort] = useQueueSort();
// 1ª carga sem ?session na URL: filtra pela sessão gravando agora (pedido do dono, 17/11/2026) — mas só se ela
// já tiver algum corte; senão a lista abriria vazia com "98 para aprovar" no contador, e o filtro escondido confunde.
const autoPicked = useRef(false);
useEffect(() => {
if (autoPicked.current) return;
autoPicked.current = true;
if (sessionParam !== null || source) return;
const open = sessions.find((s) => s.status === "recording" || s.status === "starting");
if (open && clips.some((c) => c.sessionId === open.id)) set({ session: String(open.id) });
}, [sessions, clips, sessionParam, source, set]);
// Opções de fonte: fontes cadastradas que têm corte + "sem fonte" para cortes de link solto.
const sourceOptions = useMemo(() => {
const used = new Set(clips.map((c) => c.channelId ?? NO_SOURCE));
const list = channels.filter((c) => used.has(c.id)).map((c) => ({ id: c.id, label: c.displayName || c.channel }));
if (used.has(NO_SOURCE)) {
const urls = [...new Set(clips.filter((c) => !c.channelId).map((c) => channelFromUrl(c.sessionUrl)))];
list.push({ id: NO_SOURCE, label: urls.length === 1 ? `${urls[0]} (sem fonte cadastrada)` : "Sem fonte cadastrada" });
}
return list;
}, [clips, channels]);
const sessionById = useMemo(() => new Map(sessions.map((s) => [s.id, s])), [sessions]);
const languageOf = useCallback((c: Clip) => sessionById.get(c.sessionId)?.language ?? defaultLanguage, [sessionById, defaultLanguage]);
const languages = useMemo(() => [...new Set(clips.map(languageOf))], [clips, languageOf]);
// Escopo = filtros fora a etapa (as contagens das etapas valem para esse escopo).
const scoped = clips.filter((c) =>
(!source || (c.channelId ?? NO_SOURCE) === source)
&& (sessionFilter === null || c.sessionId === sessionFilter)
&& (!lang || languageOf(c) === lang));
const current = QUEUE_FILTERS.find((f) => f.id === stage)!;
const counts = Object.fromEntries(QUEUE_FILTERS.map((f) => [f.id, scoped.filter((c) => f.statuses.includes(c.status)).length])) as Record<QueueFilter, number>;
const compare = (QUEUE_SORTS.find((s) => s.id === sort) ?? QUEUE_SORTS[0]).compare;
const shown = scoped.filter((c) => current.statuses.includes(c.status)).sort(compare);
const sessionOptions = sessions.filter((s) => clips.some((c) => c.sessionId === s.id && (!source || (c.channelId ?? NO_SOURCE) === source)) || s.id === sessionFilter);
const publishing = useClipPublishing(stage === "approved");
// Seleção para apagar: vale só para o que está na lista (trocar de etapa ou de filtro limpa).
const [selected, setSelected] = useState<ReadonlySet<number>>(() => new Set());
const [selecting, setSelecting] = useState(false);
const { deleting, notice, setNotice, remove, confirmMany } = useClipDeletion(reload);
const selectable = shown.filter(canDelete);
const chosen = selectable.filter((c) => selected.has(c.id));
const working = deleting.size > 0;
const choosing = selecting || chosen.length > 0;
const exitSelecting = useCallback(() => { setSelecting(false); setSelected(new Set()); }, []);
const changeFilters = (changes: Record<string, string | null>) => { set(changes); exitSelecting(); };
useEffect(() => {
if (!choosing) return;
const onKey = (e: KeyboardEvent) => {
// Esc de um modal, menu ou confirmação da linha é deles (o modal nativo também dispara keydown aqui).
if (e.key !== "Escape" || e.defaultPrevented || document.querySelector("dialog[open]")) return;
exitSelecting();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [choosing, exitSelecting]);
const toggle = useCallback((id: number, on: boolean) => setSelected((prev) => {
const next = new Set(prev);
if (on) next.add(id); else next.delete(id);
return next;
}), []);
const forget = (gone: Set<number>) => setSelected((prev) => new Set([...prev].filter((id) => !gone.has(id))));
const scopeNote = sessionFilter !== null ? `Vale só para a sessão #${sessionFilter} (o filtro da lista). Os cortes das outras sessões ficam.`
: source ? `Vale só para a fonte filtrada (${sourceOptions.find((o) => o.id === source)?.label ?? source}). As outras ficam.`
: lang ? `Vale só para o idioma filtrado (${languageLabel(lang)}).` : null;
const deleteOne = useCallback(async (clip: Clip, confirmPublished: boolean) => {
const r = await remove([clip], confirmPublished);
forget(r.gone);
return r.ok;
}, [remove]);
// Modal: o corte aberto vem de TODOS os cortes (continua aberto mesmo se sair da etapa); anterior/próximo seguem a lista.
const openClip = openId !== null ? clips.find((c) => c.id === openId) ?? null : null;
const openIndex = openId !== null ? shown.findIndex((c) => c.id === openId) : -1;
const openAt = (clip: Clip | null, mode: "push" | "replace") => set({ clip: clip ? String(clip.id) : null }, mode);
const prev = openIndex > 0 ? shown[openIndex - 1] : null;
const next = openIndex >= 0 && openIndex < shown.length - 1 ? shown[openIndex + 1] : null;
const onPrev = prev ? () => openAt(prev, "replace") : null;
const onNext = next ? () => openAt(next, "replace") : null;
const close = useCallback(() => set({ clip: null }, "replace"), [set]);
// O corte aberto sumiu (apagado, ou a lista mudou e ele não existe mais): fecha.
useEffect(() => { if (openId !== null && clips.length > 0 && !clips.some((c) => c.id === openId)) close(); }, [openId, clips, close]);
return (
<section aria-labelledby="cortes-titulo" className="grid gap-4">
<h2 id="cortes-titulo" className="sr-only">Cortes</h2>
<div className="flex flex-wrap items-center gap-x-4 gap-y-3">
<StageFilter value={stage} counts={counts} onChange={(id) => changeFilters({ stage: id === "ready" ? null : id })} />
<div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-2">
{(sourceOptions.length > 1 || source) && (
<FilterLabel control={
<Select value={source} onChange={(e) => changeFilters({ source: e.target.value || null, session: null })} className="h-9 w-auto min-w-40" aria-label="Filtrar por fonte">
<option value="">Todas as fontes</option>
{sourceOptions.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)}
</Select>}>Fonte</FilterLabel>
)}
{(sessionOptions.length > 1 || sessionFilter !== null) && (
<FilterLabel control={
<Select value={sessionFilter ?? ""} onChange={(e) => changeFilters({ session: e.target.value || null })} className="h-9 w-auto max-w-72 min-w-44" aria-label="Filtrar por sessão">
<option value="">Todas as sessões</option>
{sessionOptions.map((s) => (
<option key={s.id} value={s.id}>#{s.id} · {s.title || s.url.replace(/^https?:\/\/(www\.)?/, "")}</option>
))}
</Select>}>Sessão</FilterLabel>
)}
{(languages.length > 1 || lang) && (
<FilterLabel control={
<Select value={lang} onChange={(e) => changeFilters({ lang: e.target.value || null })} className="h-9 w-auto min-w-36" aria-label="Filtrar por idioma">
<option value="">Todos os idiomas</option>
{[...new Set([...languages, ...(lang ? [lang] : [])])].map((code) => (
<option key={code} value={code}>{LANGUAGES.find((l) => l.id === code)?.label ?? code}</option>
))}
</Select>}>Idioma</FilterLabel>
)}
<FilterLabel control={
<Select value={sort} onChange={(e) => setSort(e.target.value as QueueSort)} className="h-9 w-auto min-w-44" aria-label="Ordenar">
{QUEUE_SORTS.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
</Select>}>Ordenar</FilterLabel>
{/* Sempre no lugar (mesmo vazio, desabilitado): ligar/desligar a seleção não mexe no layout. */}
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" aria-pressed={selecting} disabled={selectable.length === 0 || working}
onClick={() => (selecting ? exitSelecting() : setSelecting(true))} title="Escolher cortes para apagar (Esc sai)"
className={cx("text-fg-muted", selecting && "bg-raised text-fg")}>
<CheckIcon size={15} />{selecting ? "Selecionando" : "Selecionar"}
</Button>
<TabMenu count={selectable.length} disabled={selectable.length === 0 || working}
onDeleteAll={() => void confirmMany(selectable, "tab", { stageLabel: current.label, shownCount: shown.length, scopeNote }).then(forget)} />
</div>
</div>
</div>
{stage === "approved" && (
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs leading-relaxed text-fg-muted">
<PublishIcon size={14} className="text-fg-subtle" />
{publishing.error
? <span className="text-warning">Não deu para ler o estado da publicação agora ({publishing.error}).</span>
: <span>“Publicar” escolhe o canal, as redes e quando sai. Fonte ligada a um canal publica os aprovados sozinha. A coluna Publicação mostra o estado em cada rede.</span>}
<TextLink href="/publishing">Abrir Publicações</TextLink>
</p>
)}
{shown.length === 0 ? (
<EmptyState compact icon={<ScissorsIcon size={18} />} title={`Nenhum corte em “${current.label}”`}>
{current.empty}
{sessionFilter !== null && <> Filtrando pela sessão #{sessionFilter}.</>}
{source && <> Filtrando por fonte.</>}
</EmptyState>
) : (
<ClipTable clips={shown} sessions={sessions} stage={stage} nameOf={nameOfClip} defaultLanguage={defaultLanguage}
publishing={stage === "approved" ? publishing.byClip : null} onPublished={publishing.reload} onChanged={reload}
onOpen={(clip) => openAt(clip, "push")} openId={openId}
revealed={choosing} selected={selected} onSelect={toggle} deleting={deleting} onDelete={deleteOne} />
)}
{openClip && (
<ClipDialog clip={openClip} name={nameOfClip(openClip)} session={sessionById.get(openClip.sessionId)}
position={openIndex >= 0 ? { index: openIndex + 1, total: shown.length } : null}
onPrev={onPrev} onNext={onNext} onClose={close} onChanged={reload}
publishJobs={stage === "approved" && publishing.byClip ? publishing.byClip.get(String(openClip.id)) ?? [] : null}
onPublished={publishing.reload} deleting={deleting.has(openClip.id)} onDelete={deleteOne} />
)}
{choosing && (
<SelectionPill chosen={chosen.length} total={selectable.length} working={working}
onSelectAll={(on) => setSelected(on ? new Set(selectable.map((c) => c.id)) : new Set())}
onDelete={() => void confirmMany(chosen, "selected", { stageLabel: current.label, shownCount: shown.length, scopeNote }).then(forget)}
onExit={exitSelecting} />
)}
{notice && <DeleteToast key={notice.key} notice={notice} raised={choosing} onClose={() => setNotice(null)} />}
</section>
);
}
@@ -0,0 +1,470 @@
"use client";
// Modal do jogo do Clipador: tudo o que a IA sabe de um jogo, em abas (Visão geral, Rende corte, Missões, Gatilhos
// de fim, Termos e hashtags, Fontes, Pedidos à IA), com a alternância Português (você lê) / English (vai para a IA).
// Rodapé: Pedir à IA (chat na seção da aba aberta), Editar (no idioma escolhido; o serviço traduz para o outro),
// Pesquisar de novo e Apagar. Usado pela página Jogos e pelo "O que a IA sabe do jogo" da sessão.
import { useId, useMemo, useState, type KeyboardEvent, type ReactNode } from "react";
import { askConfirm } from "./confirm-dialog";
import { clipperCall, type Game, type GameMission, type GameProfile } from "./clipper-client";
import {
AiChat, Chevron, CountPill, ListBlock, MISSION_SUGGESTIONS, ProfileEditor, SECTIONS, SavedNotes, aliasesOf, diffList, gamePath, missionNames,
monogram, useGameActions, type ChatTurn, type GamesReply, type ListKey, type RefineReply, type SectionKey,
} from "./clipper-game-parts";
import { Dialog } from "./dialog";
import { AlertIcon, BookIcon, GlobeIcon, LinkIcon, PenIcon, RefreshIcon, SearchIcon, SparkIcon, TrashIcon } from "./icons";
import { Badge, Button, EmptyState, Feedback, Input, Spinner, cx, formatRelative, hueOf } from "./ui";
type Language = "pt" | "en";
type TabId = "overview" | "clip" | "missions" | "triggers" | "terms" | "sources" | "notes";
/** Seção do chat para cada aba ("" = o perfil inteiro) e os atalhos de pedido. */
const TAB_SECTION: Record<TabId, { section: SectionKey; title: string; suggestions: string[] }> = {
overview: { section: "", title: "o perfil inteiro", suggestions: ["Deixe o resumo mais curto", "Acrescente as mecânicas da última atualização", "Pesquise as novidades deste mês"] },
clip: { section: "clip_worthy", title: SECTIONS.clip_worthy.title, suggestions: SECTIONS.clip_worthy.suggestions },
missions: { section: "missions", title: "Missões", suggestions: MISSION_SUGGESTIONS },
triggers: { section: "end_triggers", title: SECTIONS.end_triggers.title, suggestions: SECTIONS.end_triggers.suggestions },
terms: { section: "jargon", title: SECTIONS.jargon.title, suggestions: [...SECTIONS.jargon.suggestions, ...SECTIONS.hashtags.suggestions.slice(0, 1)] },
sources: { section: "sources", title: SECTIONS.sources.title, suggestions: ["Acrescente a wiki oficial do jogo como fonte"] },
notes: { section: "", title: "o perfil inteiro", suggestions: [] },
};
/** A lista de missões ganha busca a partir disto. */
const MISSION_SEARCH_FROM = 16;
export function GameDialog({ game, name, open, onClose, onGamesChanged }: {
/** undefined = o jogo ainda não está cadastrado no Clipador. */
game: Game | undefined; name: string; open: boolean; onClose: () => void; onGamesChanged: (games: Game[]) => void;
}) {
const { pending, message, setMessage, run } = useGameActions(onGamesChanged);
const [lang, setLang] = useState<Language>("pt");
const [tab, setTab] = useState<TabId>("overview");
const [editing, setEditing] = useState(false);
const [chatOpen, setChatOpen] = useState(false);
const [chatBusy, setChatBusy] = useState(false);
const [fresh, setFresh] = useState<Set<string>>(new Set()); // itens que a IA acabou de acrescentar (destaque)
const title = game?.profile?.name || game?.name || name;
const hue = hueOf(title);
const path = game ? gamePath(game.id) : "";
const busy = pending !== null || chatBusy || game?.status === "pending";
const shown: GameProfile | null | undefined = lang === "en" ? game?.profileAi : game?.profile;
const aliases = game ? aliasesOf(game) : [];
function close() {
setEditing(false);
setChatOpen(false);
setMessage(null);
onClose();
}
async function research() {
// Pesquisar refaz o perfil do zero: a edição à mão some; os pedidos guardados entram de novo na pesquisa.
if (game?.editedAt && !(await askConfirm({ title: "Pesquisar de novo?",
message: "Refaz o perfil do zero (em inglês, com missões e gatilhos) e apaga o que você editou à mão. Os pedidos que você fez à IA são aplicados de novo.",
confirmLabel: "Pesquisar de novo", tone: "danger" }))) return;
void run("research", () => clipperCall<GamesReply>(`${path}/research`, "POST"), "Pesquisa concluída e traduzida.", true);
}
async function remove() {
if (!game) return;
if (!(await askConfirm({ title: `Apagar o jogo “${title}”?`,
message: "O perfil, as missões e os pedidos guardados somem. As sessões não mudam; se o jogo voltar numa live, a IA pesquisa de novo.",
confirmLabel: "Apagar jogo", tone: "danger" }))) return;
const ok = await run("delete", () => clipperCall<GamesReply | null>(path, "DELETE"), "Jogo apagado.");
if (ok) close();
}
/** Manda um pedido do chat; aplica o perfil novo e devolve a resposta da IA + o que mudou (contado na versão em português). */
async function ask(section: SectionKey, instruction: string, search: boolean, history: ChatTurn[]): Promise<ChatTurn> {
if (!game) return { role: "ai", text: "Cadastre o jogo antes.", error: true };
setChatBusy(true);
const before = game.profile;
const r = await clipperCall<RefineReply>(`${path}/refine`, "POST", {
instruction, search, section, history: history.map(({ role, text }) => ({ role, text })),
});
setChatBusy(false);
if (!r.ok) {
if (search) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return { role: "ai", text: r.error, error: true };
}
onGamesChanged(r.data.games);
const after = r.data.games.find((g) => g.id === game.id)?.profile;
let added = 0, removed = 0;
const nextFresh = new Set<string>();
for (const key of Object.keys(SECTIONS) as ListKey[]) {
const d = diffList(before?.[key], after?.[key]);
added += d.added.length;
removed += d.removed.length;
for (const item of d.added) nextFresh.add(`${key}:${item.toLowerCase()}`);
}
const m = diffList(missionNames(before), missionNames(after));
added += m.added.length;
removed += m.removed.length;
for (const item of m.added) nextFresh.add(`missions:${item.toLowerCase()}`);
setFresh(nextFresh);
return { role: "ai", text: r.data.reply || "Pronto, atualizei o perfil.", added, removed };
}
const status = !game ? <Badge>não cadastrado</Badge>
: game.status === "pending" ? <Badge tone="info" pulse>pesquisando na web</Badge>
: game.status === "error" ? <Badge tone="danger">erro na pesquisa</Badge>
: <Badge tone="success">pronto</Badge>;
const footer = game ? (
<>
<Button variant="ghost" size="sm" disabled={busy} onClick={() => void remove()}
className="mr-auto text-fg-muted hover:bg-danger-soft hover:text-danger">
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
<Button variant="ghost" size="sm" disabled={busy || editing} onClick={() => void research()}>
{pending === "research" ? <><Spinner className="size-3.5" />Pesquisando…</> : <><RefreshIcon size={15} />{game.profile ? "Pesquisar de novo" : "Pesquisar"}</>}
</Button>
{shown && (
<Button variant="secondary" size="sm" disabled={busy || editing} onClick={() => { setEditing(true); setChatOpen(false); }}>
<PenIcon size={15} />Editar {lang === "en" ? "(inglês)" : "(português)"}
</Button>
)}
{game.profile && (
<Button size="sm" disabled={(busy && !chatBusy) || editing} aria-expanded={chatOpen} onClick={() => setChatOpen((o) => !o)}>
<SparkIcon size={15} />{chatOpen ? "Fechar IA" : "Pedir à IA"}
</Button>
)}
</>
) : (
<Button size="sm" disabled={pending !== null}
onClick={() => void run("create", () => clipperCall<GamesReply>("games", "POST", { name }), "Jogo cadastrado. Pesquisando na web… leva de 1 a 5 min.")}>
{pending === "create" ? <Spinner className="size-3.5" /> : <SparkIcon size={15} />}Cadastrar e pesquisar
</Button>
);
return (
<Dialog open={open} onClose={close} size="lg" dismissOnBackdrop={!editing}
eyebrow={<>{[shown?.genre || game?.profile?.genre, aliases.length ? aliases.slice(0, 3).join(" · ") : null].filter(Boolean).join(" · ") || "Jogo"}</>}
title={
<span className="flex items-center gap-3">
<span aria-hidden="true" className="grid size-9 shrink-0 place-items-center rounded-lg text-sm font-bold text-white"
style={{ background: `linear-gradient(135deg, hsl(${hue} 65% 52%), hsl(${(hue + 40) % 360} 70% 40%))` }}>
{monogram(title)}
</span>
{title}
</span>
}
description={
<span className="flex flex-wrap items-center gap-x-2 gap-y-1">
{status}
{game?.researchedAt && <span>pesquisado {formatRelative(game.researchedAt)}</span>}
{game?.editedAt && <span>· editado {formatRelative(game.editedAt)}</span>}
{game?.model && <span className="font-mono text-xs">· {game.model}</span>}
</span>
}
footer={footer}>
<div className="grid gap-4">
{!game ? (
<EmptyState compact icon={<BookIcon size={18} />} title="Jogo ainda não cadastrado">
A IA pesquisa o jogo na web (mecânicas, missões, gatilhos de fim, gírias, o que costuma render corte) e usa isso para entender a live.
</EmptyState>
) : (
<>
{game.status === "error" && game.error && <Feedback ok={false}>{game.error}</Feedback>}
{game.status === "pending" && (
<p role="status" className="flex items-center gap-2 rounded-control border border-info/25 bg-info-soft/50 px-3 py-2 text-xs text-info">
<Spinner className="size-3.5" />Pesquisando na web… leva de 1 a 5 min. Esta janela atualiza sozinha.
</p>
)}
{!editing && <LanguageSwitch value={lang} onChange={setLang} hasAi={Boolean(game.profileAi)} translatedAt={game.translatedAt ?? null} />}
{editing ? (
<ProfileEditor key={lang} profile={shown} fallbackName={game.name} language={lang} saving={pending === "save"}
onCancel={() => setEditing(false)}
onSave={async (profile) => {
const ok = await run("save", () => clipperCall<GamesReply>(`${path}?lang=${lang}`, "PUT", profile),
lang === "pt" ? "Perfil salvo. A versão da IA foi atualizada." : "Profile saved. A versão em português foi atualizada.");
if (ok) setEditing(false);
}} />
) : lang === "en" && !game.profileAi ? (
<div className="grid justify-items-start gap-3 rounded-control border border-warning/25 bg-warning-soft/60 px-4 py-3">
<p className="flex items-start gap-2 text-sm text-warning">
<AlertIcon size={15} className="mt-0.5 shrink-0" />
Este jogo ainda não tem a versão em inglês. Enquanto isso, a IA lê a versão em português.
</p>
<Button size="sm" variant="secondary" disabled={busy}
onClick={() => void run("translate", () => clipperCall<GamesReply>(`${path}/translate`, "POST"), "Versão da IA gerada.", true)}>
{pending === "translate" ? <Spinner className="size-3.5" /> : <GlobeIcon size={15} />}Gerar versão da IA
</Button>
</div>
) : shown ? (
<>
<ProfileTabs profile={shown} game={game} tab={tab} onTab={(t) => setTab(t)} />
{chatOpen && (
<AiChat key={tab} sectionTitle={TAB_SECTION[tab].title} suggestions={TAB_SECTION[tab].suggestions}
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask(TAB_SECTION[tab].section, text, search, history)}
onClose={() => setChatOpen(false)} />
)}
<div role="tabpanel" id={`game-panel-${tab}`} aria-labelledby={`game-tab-${tab}`} className="grid gap-3">
<TabContent tab={tab} profile={shown} game={game} fresh={fresh} busy={busy}
onResearch={() => void research()}
onForget={(i) => void run("note", () => clipperCall<GamesReply>(`${path}/notes/${i}`, "DELETE"), "Pedido esquecido.")} />
</div>
</>
) : (
<EmptyState compact icon={<BookIcon size={18} />} title="Ainda sem perfil">
{game.status === "pending" ? "A pesquisa está em andamento." : "Use “Pesquisar” para a IA montar o perfil do jogo."}
</EmptyState>
)}
</>
)}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</Dialog>
);
}
/* ---------- Idioma ---------- */
function LanguageSwitch({ value, onChange, hasAi, translatedAt }: { value: Language; onChange: (v: Language) => void; hasAi: boolean; translatedAt: string | null }) {
const options: { id: Language; label: string; hint: string }[] = [
{ id: "pt", label: "Português", hint: "você lê" },
{ id: "en", label: "English", hint: "vai para a IA" },
];
return (
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div role="radiogroup" aria-label="Idioma do perfil" className="inline-flex rounded-control border border-line-strong bg-sunken/60 p-1">
{options.map((o) => {
const on = o.id === value;
return (
<button key={o.id} type="button" role="radio" aria-checked={on} onClick={() => onChange(o.id)}
className={cx("flex items-center gap-1.5 rounded-[0.45rem] px-3 py-1.5 text-[0.8125rem] font-medium transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
on ? "bg-overlay text-fg shadow-[0_1px_3px_rgb(0_0_0/0.5)]" : "text-fg-muted hover:text-fg")}>
{o.label}<span className={cx("text-xs font-normal", on ? "text-fg-muted" : "text-fg-subtle")}>({o.hint})</span>
{o.id === "en" && !hasAi && <span aria-label="ainda não gerada" className="size-1.5 rounded-full bg-warning" />}
</button>
);
})}
</div>
{translatedAt && <span className="text-xs text-fg-subtle">versões sincronizadas {formatRelative(translatedAt)}</span>}
</div>
);
}
/* ---------- Abas ---------- */
function ProfileTabs({ profile: p, game, tab, onTab }: { profile: GameProfile; game: Game; tab: TabId; onTab: (t: TabId) => void }) {
const items: { id: TabId; label: string; count?: number }[] = [
{ id: "overview", label: "Visão geral" },
{ id: "clip", label: "Rende corte", count: (p.clip_worthy?.length ?? 0) + (p.avoid?.length ?? 0) },
{ id: "missions", label: "Missões", count: p.missions?.length ?? 0 },
{ id: "triggers", label: "Gatilhos de fim", count: p.end_triggers?.length ?? 0 },
{ id: "terms", label: "Termos e hashtags", count: (p.jargon?.length ?? 0) + (p.hashtags?.length ?? 0) },
{ id: "sources", label: "Fontes", count: p.sources?.length ?? 0 },
{ id: "notes", label: "Pedidos à IA", count: game.notes?.length ?? 0 },
];
function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {
const i = items.findIndex((t) => t.id === tab);
const next = e.key === "ArrowRight" ? (i + 1) % items.length : e.key === "ArrowLeft" ? (i - 1 + items.length) % items.length
: e.key === "Home" ? 0 : e.key === "End" ? items.length - 1 : -1;
if (next < 0) return;
e.preventDefault();
onTab(items[next].id);
document.getElementById(`game-tab-${items[next].id}`)?.focus();
}
return (
<div role="tablist" aria-label="Partes do perfil do jogo" onKeyDown={onKeyDown}
className="-mx-1 flex gap-1 overflow-x-auto border-b border-line px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{items.map((t) => {
const on = t.id === tab;
return (
<button key={t.id} id={`game-tab-${t.id}`} type="button" role="tab" aria-selected={on} aria-controls={`game-panel-${t.id}`}
tabIndex={on ? 0 : -1} onClick={() => onTab(t.id)}
className={cx("relative flex h-10 shrink-0 items-center gap-1.5 rounded-t-control px-2.5 text-[0.8125rem] font-medium whitespace-nowrap transition-colors",
"focus-visible:outline-2 focus-visible:outline-accent", on ? "text-fg" : "text-fg-muted hover:bg-raised/60 hover:text-fg")}>
{t.label}
{t.count !== undefined && <CountPill n={t.count} />}
{on && <span aria-hidden="true" className="absolute inset-x-2 -bottom-px h-0.5 rounded-full bg-accent" />}
</button>
);
})}
</div>
);
}
function TabContent({ tab, profile: p, game, fresh, busy, onResearch, onForget }: {
tab: TabId; profile: GameProfile; game: Game; fresh: Set<string>; busy: boolean; onResearch: () => void; onForget: (i: number) => void;
}) {
switch (tab) {
case "overview":
return (
<>
{p.summary ? <p className="max-w-[95ch] text-sm leading-relaxed text-fg-muted">{p.summary}</p>
: <p className="text-sm text-fg-subtle">Sem resumo.</p>}
<div className="grid gap-3 lg:grid-cols-2">
<ListBlock sectionKey="mechanics" items={p.mechanics ?? []} fresh={fresh} />
<ListBlock sectionKey="news" items={p.news ?? []} fresh={fresh} />
</div>
</>
);
case "clip":
return (
<div className="grid gap-3 lg:grid-cols-2">
<ListBlock sectionKey="clip_worthy" items={p.clip_worthy ?? []} fresh={fresh} />
<ListBlock sectionKey="avoid" items={p.avoid ?? []} fresh={fresh} />
</div>
);
case "missions":
return <MissionList missions={p.missions} fresh={fresh} busy={busy} onResearch={onResearch} />;
case "triggers":
return (
<>
<p className="text-xs leading-relaxed text-fg-subtle">
A IA usa estes sinais para terminar o corte no clímax de uma missão. Cada missão pode ter os próprios gatilhos, na aba Missões.
</p>
<ListBlock sectionKey="end_triggers" items={p.end_triggers ?? []} fresh={fresh} numbered />
</>
);
case "terms":
return (
<div className="grid gap-3">
<ListBlock sectionKey="jargon" items={p.jargon ?? []} fresh={fresh} chips />
<ListBlock sectionKey="hashtags" items={p.hashtags ?? []} fresh={fresh} chips />
<ListBlock sectionKey="aliases" items={p.aliases ?? aliasesOf(game)} fresh={fresh} chips />
</div>
);
case "sources":
return (p.sources ?? []).length === 0 ? <p className="text-sm text-fg-subtle">Nenhuma fonte registrada.</p> : (
<ol className="grid gap-1.5">
{p.sources.map((s, i) => (
<li key={i} className="flex min-w-0 items-center gap-2 text-[0.8125rem]">
<LinkIcon size={13} className="shrink-0 text-fg-subtle" />
{/^https?:\/\//.test(s)
? <a href={s} target="_blank" rel="noreferrer noopener" className="truncate text-fg-muted hover:text-fg hover:underline">{s.replace(/^https?:\/\/(www\.)?/, "")}</a>
: <span className="truncate text-fg-subtle">{s}</span>}
</li>
))}
</ol>
);
case "notes":
return <SavedNotes notes={game.notes ?? []} disabled={busy} onForget={onForget} />;
}
}
/* ---------- Missões ---------- */
function MissionList({ missions, fresh, busy, onResearch }: { missions: GameMission[] | undefined; fresh: Set<string>; busy: boolean; onResearch: () => void }) {
const [query, setQuery] = useState("");
const [openIndex, setOpenIndex] = useState<number | null>(null);
const searchId = useId();
const list = useMemo(() => (missions ?? []).map((m, i) => ({ m, i })), [missions]);
const needle = query.trim().toLowerCase();
const shown = needle
? list.filter(({ m }) => [m.name, m.chapter, m.summary].some((t) => (t ?? "").toLowerCase().includes(needle)))
: list;
if (!missions || missions.length === 0) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title={missions ? "Lista de missões ainda não é pública" : "Sem missões neste perfil"}
action={<Button size="sm" variant="secondary" disabled={busy} onClick={onResearch}><RefreshIcon size={15} />Pesquisar de novo</Button>}>
{missions
? "A IA não achou uma lista confiável na web. Quando sair (wiki, guias), pesquise de novo ou peça à IA para acrescentar."
: "Este perfil é de antes das missões. Pesquise de novo para a IA procurar a lista e os gatilhos de fim."}
</EmptyState>
);
}
// Agrupa por capítulo, na ordem em que aparecem.
const groups: { chapter: string; rows: typeof shown }[] = [];
for (const row of shown) {
const chapter = row.m.chapter?.trim() || "";
const last = groups[groups.length - 1];
if (last && last.chapter === chapter) last.rows.push(row);
else groups.push({ chapter, rows: [row] });
}
const multipleChapters = groups.some((g) => g.chapter);
return (
<div className="grid gap-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-xs text-fg-subtle">
{missions.length} {missions.length === 1 ? "missão" : "missões"}. Clique numa missão para ver o que marca o fim dela.
</p>
{missions.length >= MISSION_SEARCH_FROM && (
<label htmlFor={searchId} className="relative block">
<span className="sr-only">Buscar missão</span>
<SearchIcon size={14} className="pointer-events-none absolute top-1/2 left-2.5 -translate-y-1/2 text-fg-subtle" />
<Input id={searchId} type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar missão…" className="h-8 w-52 pl-8 text-[0.8125rem]" />
</label>
)}
</div>
{shown.length === 0 ? <p className="text-sm text-fg-muted">Nenhuma missão com “{query.trim()}”.</p> : (
<div className="grid gap-3">
{groups.map((g, gi) => (
<section key={`${g.chapter}-${gi}`} aria-label={g.chapter || "Missões"} className="grid gap-1">
{multipleChapters && <h4 className="px-1 text-eyebrow font-semibold text-fg-subtle uppercase">{g.chapter || "Sem capítulo"}</h4>}
<ul className="grid divide-y divide-line overflow-hidden rounded-control border border-line bg-sunken/30">
{g.rows.map(({ m, i }) => (
<MissionRow key={i} mission={m} index={i} open={openIndex === i} isNew={fresh.has(`missions:${m.name.toLowerCase()}`)}
showChapter={!multipleChapters}
onToggle={() => setOpenIndex(openIndex === i ? null : i)} />
))}
</ul>
</section>
))}
</div>
)}
</div>
);
}
function MissionRow({ mission: m, index, open, isNew, showChapter, onToggle }: {
mission: GameMission; index: number; open: boolean; isNew: boolean;
/** Sem títulos de grupo (um capítulo só ou nenhum): o capítulo aparece dentro da missão. */
showChapter: boolean; onToggle: () => void;
}) {
const triggers = m.completion_triggers ?? [];
const panelId = `mission-${index}`;
return (
<li className={cx(isNew && "bg-success-soft/40")}>
<button type="button" aria-expanded={open} aria-controls={panelId} onClick={onToggle}
className="flex w-full items-center gap-3 px-3 py-2 text-left transition-colors hover:bg-raised/50 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent">
<span className="w-6 shrink-0 text-right text-xs text-fg-subtle tabular-nums">{index + 1}</span>
<span className="grid min-w-0 flex-1">
<span className="truncate text-[0.8125rem] font-medium text-fg">{m.name}</span>
{m.summary && !open && <span className="truncate text-xs text-fg-subtle">{m.summary}</span>}
</span>
{isNew && <Badge tone="success" dot={false}>novo</Badge>}
<span className={cx("shrink-0 text-xs tabular-nums", triggers.length ? "text-accent" : "text-fg-subtle")}>
{triggers.length ? `${triggers.length} gatilho${triggers.length === 1 ? "" : "s"}` : "sem gatilho"}
</span>
<Chevron open={open} />
</button>
{open && (
<div id={panelId} className="grid gap-2 px-3 pt-1 pb-3 pl-12 text-[0.8125rem]">
{showChapter && m.chapter && <p className="text-xs text-fg-subtle">{m.chapter}</p>}
{m.summary && <p className="leading-relaxed text-fg-muted">{m.summary}</p>}
<div className="grid gap-1">
<p className="text-eyebrow font-semibold text-accent uppercase">Fim da missão</p>
{triggers.length === 0 ? <p className="text-xs text-fg-subtle">Sem gatilho próprio: valem os gatilhos gerais do jogo.</p> : (
<ol className="grid gap-1">
{triggers.map((t, j) => (
<li key={j} className="flex gap-2 text-fg-muted">
<span aria-hidden="true" className="mt-2 size-1.5 shrink-0 rounded-full bg-accent" />{t}
</li>
))}
</ol>
)}
</div>
</div>
)}
</li>
);
}
/** Rótulo curto do estado, reaproveitado pela tabela. */
export function GameStatusBadge({ game }: { game: Game }): ReactNode {
if (game.status === "pending") return <Badge tone="info" pulse>pesquisando</Badge>;
if (game.status === "error") return <span title={game.error ?? undefined}><Badge tone="danger">erro</Badge></span>;
return <Badge tone="success">pronto</Badge>;
}
+460
View File
@@ -0,0 +1,460 @@
"use client";
// Peças do perfil de jogo do Clipador, usadas pelo modal do jogo (clipper-game-dialog.tsx) e pela página Jogos:
// seções do perfil (cor, dica, atalhos de pedido), ações com retorno, chat com a IA, memória de pedidos e o editor à
// mão (listas, aliases, gatilhos de fim e missões).
import { useEffect, useId, useRef, useState } from "react";
import type { ApiResult } from "./api-client";
import { clipperCall, type Game, type GameMission, type GameProfile } from "./clipper-client";
import { BookIcon, CheckIcon, ChevronDownIcon, PlusIcon, SendIcon, SparkIcon, TrashIcon, XIcon } from "./icons";
import { Button, Field, Input, Spinner, Switch, Textarea, cx, formatRelative } from "./ui";
/* ---------- Seções ---------- */
/** Listas de texto do perfil (missões são objetos e têm editor próprio). */
export type ListKey = "clip_worthy" | "avoid" | "mechanics" | "news" | "jargon" | "hashtags" | "sources" | "aliases" | "end_triggers";
/** Seção que o chat da IA edita ("" = o perfil inteiro). Mesmos nomes do `section` de POST games/{id}/refine. */
export type SectionKey = ListKey | "summary" | "missions" | "";
export type Tone = "success" | "danger" | "info" | "violet" | "neutral" | "accent";
/** Como cada lista aparece: cor, dica de edição e atalhos de pedido para o chat. */
export const SECTIONS: Record<ListKey, { title: string; tone: Tone; hint: string; suggestions: string[] }> = {
clip_worthy: {
title: "O que rende corte", tone: "success", hint: "Uma situação por linha.",
suggestions: ["Reação do streamer conta (grito, risada, raiva)", "Momentos em que o chat explode de emotes", "Falha engraçada ou bug bizarro"],
},
avoid: {
title: "Evitar", tone: "danger", hint: "Uma situação por linha.",
suggestions: ["Tela de carregamento e fila", "Streamer lendo doação sem reação", "AFK ou pausa"],
},
mechanics: { title: "Mecânicas", tone: "info", hint: "Uma por linha.", suggestions: ["Explique melhor as mecânicas que aparecem nas lives", "Acrescente as mecânicas da última atualização"] },
news: { title: "Novidades", tone: "violet", hint: "Uma por linha, com mês/ano.", suggestions: ["Pesquise as novidades deste mês", "Tire as novidades com mais de 6 meses"] },
jargon: { title: "Gírias e termos", tone: "neutral", hint: "Um por linha.", suggestions: ["Acrescente as gírias que o chat usa", "Explique cada gíria em poucas palavras"] },
hashtags: {
title: "Hashtags", tone: "violet",
hint: "Uma por linha, a principal primeiro. As 3 primeiras entram em toda legenda de corte deste jogo, junto com a do canal e as do momento.",
suggestions: ["Pesquise as hashtags que o público usa para este jogo no TikTok", "Acrescente a hashtag do modo que o streamer joga"],
},
aliases: {
title: "Outros nomes", tone: "neutral",
hint: "Um por linha (ex.: GTA 6, GTA VI). A categoria da live e o que a IA vê na tela caem neste mesmo perfil.",
suggestions: ["Acrescente as abreviações que o chat usa para o jogo"],
},
end_triggers: {
title: "Gatilhos de fim de missão", tone: "accent",
hint: "Um sinal por linha: banner na tela, tela de resultado, fala ou som que marca o fim de uma missão ou objetivo.",
suggestions: ["Pesquise o que aparece na tela quando uma missão termina", "Acrescente a tela de missão falhada", "Acrescente o sinal de fim de assalto"],
},
sources: { title: "Fontes", tone: "neutral", hint: "Uma URL por linha.", suggestions: [] },
};
export const MISSION_SUGGESTIONS = [
"Pesquise a lista oficial de missões da história",
"Acrescente os gatilhos de fim de cada missão",
"Separe as missões por capítulo",
];
export const TONE_TEXT: Record<Tone, string> = {
success: "text-success", danger: "text-danger", info: "text-info", violet: "text-violet", neutral: "text-fg-subtle", accent: "text-accent",
};
export const TONE_BAR: Record<Tone, string> = {
success: "bg-success", danger: "bg-danger", info: "bg-info", violet: "bg-violet", neutral: "bg-line-strong", accent: "bg-accent",
};
/** Título de uma seção pelo nome usado no serviço (as notas guardam `section`). */
export function sectionTitle(section: string | undefined): string | null {
if (!section) return null;
if (section === "missions") return "Missões";
if (section === "summary") return "Resumo";
return section in SECTIONS ? SECTIONS[section as ListKey].title : null;
}
/* ---------- Utilidades ---------- */
export type GamesReply = { games: Game[] };
export type RefineReply = GamesReply & { reply?: string };
/** Caminho do jogo na API do Clipador. */
export function gamePath(id: string): string {
return `games/${encodeURIComponent(id)}`;
}
/** Iniciais do jogo para o selo: primeira e última palavra ("Call of Duty: Warzone" → "CW"). */
export function monogram(title: string): string {
const words = title.replace(/[^\p{L}\p{N} ]/gu, " ").split(/\s+/).filter(Boolean);
if (words.length === 0) return "?";
return (words.length === 1 ? words[0].slice(0, 2) : words[0][0] + words[words.length - 1][0]).toUpperCase();
}
/** Itens que entraram/saíram numa lista (para destacar o que a IA acrescentou). */
export function diffList(before: string[] = [], after: string[] = []) {
const had = new Set(before.map((s) => s.toLowerCase()));
const has = new Set(after.map((s) => s.toLowerCase()));
return { added: after.filter((s) => !had.has(s.toLowerCase())), removed: before.filter((s) => !has.has(s.toLowerCase())) };
}
/** Lista de nomes do perfil para comparar missões (o diff do chat conta missão nova como item novo). */
export function missionNames(profile: GameProfile | null | undefined): string[] {
return (profile?.missions ?? []).map((m) => m.name);
}
/**
* Outros nomes do jogo para mostrar ("GTA 6", "GTA VI"): os das duas versões do perfil, sem repetir. O `aliases` de
* cima vem do serviço como id ("gta-6") e só entra se o perfil não tiver nenhum (para casar, use `gameIdOf`).
*/
export function aliasesOf(game: Game): string[] {
const fromProfiles = [...(game.profile?.aliases ?? []), ...(game.profileAi?.aliases ?? [])];
const all = fromProfiles.length ? fromProfiles : game.aliases ?? [];
const seen = new Set<string>();
return all.filter((a) => {
const key = a.trim().toLowerCase();
if (!key || seen.has(key)) return false;
seen.add(key);
return true;
});
}
/**
* Ações do jogo que não são o chat: pesquisar, salvar à mão, traduzir, esquecer pedido, apagar.
* A resposta pode trazer a lista nova (`{games}`); se não trouxer, a lista é relida.
* Pesquisa pode levar minutos: se o painel desistir de esperar, o serviço segue.
*/
export function useGameActions(onGamesChanged: (games: Game[]) => void) {
const [pending, setPending] = useState<string | null>(null);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
async function reloadList() {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
async function run(action: string, call: () => Promise<ApiResult<Partial<GamesReply> | null>>, okText: string, slow = false) {
setPending(action);
setMessage(null);
const r = await call();
setPending(null);
if (r.ok) {
if (r.data && Array.isArray(r.data.games)) onGamesChanged(r.data.games);
else await reloadList();
setMessage({ ok: true, text: okText });
return true;
}
setMessage({ ok: false, text: slow ? `${r.error} Se demorou demais, a IA pode continuar no serviço: a lista atualiza sozinha.` : r.error });
if (slow) await reloadList();
return false;
}
return { pending, message, setMessage, run, reloadList };
}
/* ---------- Chat com a IA ---------- */
export type ChatTurn = { role: "user" | "ai"; text: string; error?: boolean; added?: number; removed?: number };
/**
* Conversa com a IA sobre uma seção do perfil: você fala ("adicione que reação do streamer conta"), ela edita a
* lista e responde o que fez. Enter envia; Shift+Enter quebra linha. A conversa vale enquanto o chat está aberto;
* cada pedido fica guardado no serviço e volta nas próximas pesquisas.
*/
export function AiChat({ sectionTitle: title, suggestions, compact = false, disabled, onAsk, onClose }: {
sectionTitle: string; suggestions: string[]; compact?: boolean; disabled: boolean;
onAsk: (text: string, search: boolean, history: ChatTurn[]) => Promise<ChatTurn>; onClose: () => void;
}) {
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [text, setText] = useState("");
const [search, setSearch] = useState(false);
const [thinking, setThinking] = useState(false);
const inputId = useId();
const logRef = useRef<HTMLOListElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" }); }, [turns, thinking]);
async function send(raw: string) {
const clean = raw.trim();
if (clean.length < 3 || thinking || disabled) return;
const history = turns.filter((t) => !t.error);
setTurns((t) => [...t, { role: "user", text: clean }]);
setText("");
setThinking(true);
const reply = await onAsk(clean, search, history);
setThinking(false);
setTurns((t) => [...t, reply]);
inputRef.current?.focus();
}
return (
<section aria-label={`Conversa com a IA sobre ${title}`}
className={cx("grid gap-3 rounded-control border border-accent/30 bg-accent-soft/40", compact ? "p-3" : "p-4")}>
<div className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-accent text-accent-fg"><SparkIcon size={13} /></span>
<p className="min-w-0 flex-1 text-[0.8125rem] font-medium text-fg">IA · editando <span className="text-accent">{title}</span></p>
<button type="button" onClick={onClose} aria-label="Fechar conversa"
className="rounded-md p-1 text-fg-subtle hover:bg-overlay hover:text-fg"><XIcon size={14} /></button>
</div>
{turns.length === 0 && !thinking ? (
<div className="grid gap-2">
<p className="text-xs leading-relaxed text-fg-muted">
Diga em português o que acrescentar, tirar ou corrigir. A IA edita a versão em inglês (a que ela lê), traduz de volta e explica o que fez.
</p>
{suggestions.length > 0 && (
<ul className="flex flex-wrap gap-1.5">
{suggestions.map((s) => (
<li key={s}>
<button type="button" disabled={disabled} onClick={() => void send(s)}
className="rounded-full border border-line bg-raised/70 px-2.5 py-1 text-xs text-fg-muted transition-colors hover:border-accent/50 hover:text-fg disabled:opacity-50">
{s}
</button>
</li>
))}
</ul>
)}
</div>
) : (
<ol ref={logRef} aria-live="polite" className="grid max-h-72 gap-2 overflow-y-auto pr-1">
{turns.map((t, i) => (
<li key={i} className={cx("flex", t.role === "user" ? "justify-end" : "justify-start")}>
<div className={cx("max-w-[85%] rounded-2xl px-3 py-2 text-[0.8125rem] leading-relaxed",
t.role === "user" ? "rounded-br-md bg-accent text-accent-fg"
: t.error ? "rounded-bl-md border border-danger/30 bg-danger-soft text-danger"
: "rounded-bl-md border border-line bg-raised text-fg")}>
{t.text}
{t.role === "ai" && !t.error && (t.added || t.removed) ? (
<span className="mt-1.5 flex gap-2 text-xs font-medium">
{t.added ? <span className="text-success">+{t.added} {t.added === 1 ? "item novo" : "itens novos"}</span> : null}
{t.removed ? <span className="text-danger">−{t.removed} {t.removed === 1 ? "removido" : "removidos"}</span> : null}
</span>
) : null}
</div>
</li>
))}
{thinking && (
<li className="flex justify-start">
<div role="status" className="flex items-center gap-1.5 rounded-2xl rounded-bl-md border border-line bg-raised px-3 py-2.5 text-xs text-fg-muted">
<span className="sr-only">A IA está editando…</span>
{[0, 150, 300].map((d) => <span key={d} aria-hidden="true" className="size-1.5 animate-bounce rounded-full bg-fg-subtle" style={{ animationDelay: `${d}ms` }} />)}
{search && <span className="ml-1">pesquisando na web…</span>}
</div>
</li>
)}
</ol>
)}
<form className="grid gap-2" onSubmit={(e) => { e.preventDefault(); void send(text); }}>
<label htmlFor={inputId} className="sr-only">Pedido para a IA</label>
<div className="flex items-end gap-2 rounded-control border border-line-strong bg-canvas/70 p-1.5 focus-within:border-accent/60">
<textarea ref={inputRef} id={inputId} rows={1} maxLength={1500} value={text} disabled={thinking}
placeholder="Ex.: adicione que reação do streamer conta para corte"
className="max-h-32 min-h-9 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm text-fg placeholder:text-fg-subtle focus:outline-none"
onChange={(e) => { setText(e.target.value); e.target.style.height = "auto"; e.target.style.height = `${e.target.scrollHeight}px`; }}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send(text); } }} />
<Button type="submit" size="sm" aria-label="Enviar" disabled={text.trim().length < 3 || thinking || disabled}>
{thinking ? <Spinner className="size-3.5" /> : <SendIcon size={14} />}
</Button>
</div>
<Switch label="Confirmar na web" checked={search} onChange={setSearch} disabled={thinking}
hint={search ? "Mais lento: a IA pesquisa antes (até alguns minutos)." : "Rápido: usa só o que você escreveu."} />
</form>
</section>
);
}
/* ---------- Memória de pedidos ---------- */
/** Pedidos que você fez à IA: voltam em toda pesquisa nova (para "Pesquisar de novo" não apagar o que você acrescentou). */
export function SavedNotes({ notes, disabled, onForget }: { notes: { text: string; at: string; section?: string }[]; disabled: boolean; onForget: (index: number) => void }) {
if (notes.length === 0) {
return (
<p className="flex items-center gap-2 text-sm text-fg-muted">
<BookIcon size={15} className="text-fg-subtle" />Nenhum pedido guardado. O que você pedir à IA aqui volta em toda pesquisa nova.
</p>
);
}
return (
<div className="grid gap-2">
<p className="text-xs text-fg-subtle">Voltam em toda pesquisa nova, para “Pesquisar de novo” não apagar o que você acrescentou.</p>
<ul className="grid gap-1">
{notes.map((n, i) => (
<li key={`${n.at}-${i}`} className="flex items-start gap-2 rounded-lg border border-line bg-raised/40 px-2.5 py-1.5 text-xs text-fg-muted">
{sectionTitle(n.section) && <span className="shrink-0 font-medium text-accent">{sectionTitle(n.section)}</span>}
<span className="min-w-0 flex-1 leading-relaxed break-words">{n.text}</span>
<span className="shrink-0 text-fg-subtle">{formatRelative(n.at)}</span>
<button type="button" aria-label={`Esquecer o pedido “${n.text.slice(0, 40)}”`} disabled={disabled}
title="Esquecer (não volta nas próximas pesquisas; o perfil atual fica como está)"
className="shrink-0 rounded p-0.5 text-fg-subtle hover:bg-overlay hover:text-danger disabled:opacity-50"
onClick={() => onForget(i)}>
<XIcon size={13} />
</button>
</li>
))}
</ul>
</div>
);
}
/* ---------- Edição à mão ---------- */
const EDIT_LISTS: ListKey[] = ["clip_worthy", "avoid", "mechanics", "news", "jargon", "hashtags", "aliases", "end_triggers", "sources"];
type MissionDraft = { name: string; chapter: string; summary: string; triggers: string };
type ProfileDraft = { name: string; genre: string; summary: string; lists: Record<string, string>; missions: MissionDraft[] };
const splitLines = (text: string) => text.split(/\r?\n/).map((l) => l.replace(/^\s*[-•*]\s*/, "").trim()).filter(Boolean);
function toDraft(profile: GameProfile | null | undefined, fallbackName: string): ProfileDraft {
return {
name: profile?.name || fallbackName,
genre: profile?.genre ?? "",
summary: profile?.summary ?? "",
lists: Object.fromEntries(EDIT_LISTS.map((key) => [key, (profile?.[key] ?? []).join("\n")])),
missions: (profile?.missions ?? []).map((m) => ({
name: m.name, chapter: m.chapter ?? "", summary: m.summary ?? "", triggers: (m.completion_triggers ?? []).join("; "),
})),
};
}
function fromDraft(draft: ProfileDraft): GameProfile {
const lists = Object.fromEntries(EDIT_LISTS.map((key) => [key, splitLines(draft.lists[key] ?? "")]));
const missions: GameMission[] = draft.missions
.filter((m) => m.name.trim())
.map((m) => ({
name: m.name.trim(), chapter: m.chapter.trim(), summary: m.summary.trim(),
completion_triggers: m.triggers.split(";").map((t) => t.trim()).filter(Boolean),
}));
return { name: draft.name.trim(), genre: draft.genre.trim(), summary: draft.summary.trim(), ...lists, missions } as GameProfile;
}
/** Editor à mão do perfil num idioma (`language` só muda os textos de ajuda). */
export function ProfileEditor({ profile, fallbackName, language, saving, onSave, onCancel }: {
profile: GameProfile | null | undefined; fallbackName: string; language: "pt" | "en"; saving: boolean;
onSave: (profile: GameProfile) => void; onCancel: () => void;
}) {
const [draft, setDraft] = useState(() => toDraft(profile, fallbackName));
const setList = (key: string, value: string) => setDraft((d) => ({ ...d, lists: { ...d.lists, [key]: value } }));
const setMission = (i: number, values: Partial<MissionDraft>) =>
setDraft((d) => ({ ...d, missions: d.missions.map((m, j) => (j === i ? { ...m, ...values } : m)) }));
return (
<form className="grid gap-5" onSubmit={(e) => { e.preventDefault(); onSave(fromDraft(draft)); }}>
<p className="rounded-control border border-info/25 bg-info-soft/50 px-3 py-2 text-xs leading-relaxed text-info">
{language === "pt"
? "Editando a versão em português (a que você lê). Ao salvar, o Clipador traduz para o inglês que vai para a IA."
: "Editing the English version (what the AI reads). Ao salvar, o Clipador traduz para o português que você lê."}
</p>
<div className="grid gap-4 md:grid-cols-2">
<Field label="Nome do jogo">
<Input value={draft.name} maxLength={120} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
</Field>
<Field label="Gênero">
<Input value={draft.genre} maxLength={120} onChange={(e) => setDraft({ ...draft, genre: e.target.value })} />
</Field>
</div>
<Field label="Resumo" hint="O que é o jogo e como se joga (2–3 frases).">
<Textarea rows={3} maxLength={1500} value={draft.summary} onChange={(e) => setDraft({ ...draft, summary: e.target.value })} />
</Field>
<div className="grid gap-4 md:grid-cols-2">
{EDIT_LISTS.map((key) => (
<Field key={key} label={<span className={TONE_TEXT[SECTIONS[key].tone]}>{SECTIONS[key].title}</span>} hint={SECTIONS[key].hint}>
<Textarea rows={Math.min(10, Math.max(3, (draft.lists[key] ?? "").split("\n").length + 1))}
value={draft.lists[key] ?? ""} onChange={(e) => setList(key, e.target.value)}
className={key === "sources" ? "font-mono text-xs" : undefined} />
</Field>
))}
</div>
<fieldset className="grid gap-3">
<legend className="mb-1 flex w-full items-center gap-2 text-[0.8125rem] font-medium text-fg-muted">
Missões <span className="rounded-full bg-overlay px-1.5 text-[0.6875rem] tabular-nums text-fg-subtle">{draft.missions.length}</span>
</legend>
<p className="-mt-1 text-xs text-fg-subtle">Uma linha por missão. Gatilhos de fim separados por “;” (ex.: banner MISSION PASSED; cutscene final).</p>
{draft.missions.length > 0 && (
<ol className="grid max-h-[28rem] gap-2 overflow-y-auto pr-1">
{draft.missions.map((m, i) => (
<li key={i} className="grid gap-2 rounded-control border border-line bg-sunken/40 p-2.5 md:grid-cols-[2rem_minmax(0,1.3fr)_minmax(0,0.8fr)_auto]">
<span className="pt-2 text-right text-xs text-fg-subtle tabular-nums">{i + 1}.</span>
<Input aria-label={`Nome da missão ${i + 1}`} placeholder="Nome da missão" value={m.name} maxLength={160}
onChange={(e) => setMission(i, { name: e.target.value })} className="h-9" />
<Input aria-label={`Capítulo da missão ${i + 1}`} placeholder="Capítulo / ato" value={m.chapter} maxLength={80}
onChange={(e) => setMission(i, { chapter: e.target.value })} className="h-9" />
<Button type="button" variant="ghost" size="sm" aria-label={`Remover a missão ${i + 1}`} className="px-2 hover:bg-danger-soft hover:text-danger"
onClick={() => setDraft((d) => ({ ...d, missions: d.missions.filter((_, j) => j !== i) }))}>
<TrashIcon size={14} />
</Button>
<span className="max-md:hidden" />
<Input aria-label={`Resumo da missão ${i + 1}`} placeholder="Resumo em uma frase" value={m.summary} maxLength={400}
onChange={(e) => setMission(i, { summary: e.target.value })} className="h-9 md:col-span-2" />
<span className="max-md:hidden" />
<span className="max-md:hidden" />
<Input aria-label={`Gatilhos de fim da missão ${i + 1}`} placeholder="Gatilhos de fim (separe com ;)" value={m.triggers} maxLength={600}
onChange={(e) => setMission(i, { triggers: e.target.value })} className="h-9 md:col-span-2" />
</li>
))}
</ol>
)}
<div>
<Button type="button" variant="secondary" size="sm"
onClick={() => setDraft((d) => ({ ...d, missions: [...d.missions, { name: "", chapter: "", summary: "", triggers: "" }] }))}>
<PlusIcon size={14} />Adicionar missão
</Button>
</div>
</fieldset>
<div className="sticky bottom-0 flex justify-end gap-2 border-t border-line bg-canvas/95 py-3 backdrop-blur">
<Button type="button" variant="ghost" size="sm" disabled={saving} onClick={onCancel}>Cancelar</Button>
<Button type="submit" size="sm" disabled={saving}>
{saving ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar e traduzir
</Button>
</div>
</form>
);
}
/* ---------- Leitura ---------- */
/** Uma lista do perfil em bloco (barra de cor, título, contagem). `chips` mostra em pílulas (gírias, hashtags). */
export function ListBlock({ sectionKey, items, fresh, chips = false, numbered = false, className }: {
sectionKey: ListKey; items: string[]; fresh: Set<string>; chips?: boolean; numbered?: boolean; className?: string;
}) {
const { title, tone } = SECTIONS[sectionKey];
const isFresh = (item: string) => fresh.has(`${sectionKey}:${item.toLowerCase()}`);
return (
<section className={cx("relative grid content-start gap-3 overflow-hidden rounded-control border border-line bg-sunken/40 p-4 pl-5", className)}>
<span aria-hidden="true" className={cx("absolute inset-y-0 left-0 w-1", TONE_BAR[tone])} />
<div className="flex items-center gap-2">
<h4 className={cx("text-eyebrow font-semibold uppercase", TONE_TEXT[tone])}>{title}</h4>
<span className="rounded-full bg-overlay px-1.5 text-[0.6875rem] font-medium tabular-nums text-fg-subtle">{items.length}</span>
</div>
{items.length === 0 ? (
<p className="text-xs text-fg-subtle">Vazio. Peça à IA para preencher.</p>
) : chips ? (
<ul className="flex flex-wrap gap-1.5">
{items.map((j, i) => (
<li key={i} className={cx("rounded-lg border px-2 py-1 text-xs transition-colors",
isFresh(j) ? "border-success/50 bg-success-soft text-success" : "border-line bg-raised/60 text-fg-muted")}>{j}</li>
))}
</ul>
) : (
<ol className="grid gap-1.5 text-[0.8125rem] text-fg-muted">
{items.map((it, i) => (
<li key={i} className={cx("flex gap-2 rounded-md leading-relaxed transition-colors", isFresh(it) && "-mx-2 bg-success-soft px-2 py-1 text-fg")}>
{numbered
? <span aria-hidden="true" className={cx("w-5 shrink-0 text-right text-xs font-semibold tabular-nums", TONE_TEXT[tone])}>{i + 1}.</span>
: <span aria-hidden="true" className={cx("mt-2 size-1.5 shrink-0 rounded-full", TONE_BAR[tone], !isFresh(it) && "opacity-60")} />}
<span className="min-w-0 flex-1">{it}</span>
{isFresh(it) && <span className="mt-0.5 h-fit shrink-0 rounded-full bg-success px-1.5 text-[0.625rem] font-semibold text-canvas uppercase">novo</span>}
</li>
))}
</ol>
)}
</section>
);
}
/** Pílula de quantidade para a sub-navegação do modal. */
export function CountPill({ n }: { n: number }) {
return <span className="grid h-5 min-w-5 place-items-center rounded-full bg-overlay px-1.5 text-[0.6875rem] font-semibold tabular-nums text-fg-subtle">{n}</span>;
}
/** Seta que gira quando o bloco abre. */
export function Chevron({ open }: { open: boolean }) {
return <ChevronDownIcon size={14} className={cx("shrink-0 transition-transform motion-reduce:transition-none", open && "rotate-180")} />;
}
+269
View File
@@ -0,0 +1,269 @@
"use client";
// Jogos (/clipper/games): o que a IA sabe de cada jogo, em lista. Clicar numa linha abre o modal do jogo
// (clipper-game-dialog.tsx), com o estado na URL (?game=ID: abrir grava no histórico, fechar não).
// "Adicionar jogo" cadastra e pesquisa em segundo plano; enquanto houver jogo pesquisando, a lista é relida a cada 10 s.
// Busca por nome/alias a partir de 4 jogos. Os dados vêm do ClipperProvider.
import { useSearchParams } from "next/navigation";
import { Suspense, useCallback, useEffect, useId, useState, type FormEvent, type MouseEvent } from "react";
import { askConfirm } from "./confirm-dialog";
import { clipperCall, type Game } from "./clipper-client";
import { GameDialog, GameStatusBadge } from "./clipper-game-dialog";
import { aliasesOf, gamePath, monogram, useGameActions, type GamesReply } from "./clipper-game-parts";
import { useClipper } from "./clipper-provider";
import { Dialog } from "./dialog";
import { ArrowRightIcon, BookIcon, GlobeIcon, PlusIcon, RefreshIcon, SearchIcon, TrashIcon } from "./icons";
import {
Badge, Button, EmptyState, Feedback, Field, Input, SectionHeader, Spinner, Table, Td, Textarea, Th, THead, cx, formatRelative, hueOf,
} from "./ui";
const SEARCH_FROM = 4;
/** Releitura da lista enquanto algum jogo está pesquisando (a pesquisa leva de 1 a 5 min). */
const PENDING_POLL_MS = 10_000;
export function GamesPage() {
return (
<Suspense fallback={<div role="status" className="flex items-center gap-2 text-sm text-fg-muted"><Spinner />Carregando jogos…</div>}>
<GamesView />
</Suspense>
);
}
function GamesView() {
const { games, setGames, refresh } = useClipper();
const params = useSearchParams();
const [query, setQuery] = useState("");
const [adding, setAdding] = useState(false);
const searchId = useId();
const all = games ?? [];
const needle = query.trim().toLowerCase();
const shown = needle
? all.filter((g) => [g.name, g.profile?.genre ?? "", ...aliasesOf(g)].some((t) => t.toLowerCase().includes(needle)))
: all;
const openId = params.get("game");
const openGame = openId ? all.find((g) => g.id === openId) : undefined;
const setOpen = useCallback((id: string | null) => {
const next = new URLSearchParams(window.location.search);
if (id) next.set("game", id); else next.delete("game");
const query = next.toString();
const url = `${window.location.pathname}${query ? `?${query}` : ""}`;
if (id) window.history.pushState(null, "", url);
else window.history.replaceState(null, "", url);
}, []);
// Jogo pesquisando: relê só a lista de jogos a cada 10 s (o provider só consulta sozinho com live/corte em andamento).
const anyPending = all.some((g) => g.status === "pending");
useEffect(() => {
if (!anyPending) return;
const timer = setInterval(async () => {
if (document.visibilityState === "hidden") return;
const r = await clipperCall<GamesReply>("games");
if (r.ok) setGames(r.data.games);
}, PENDING_POLL_MS);
return () => clearInterval(timer);
}, [anyPending, setGames]);
if (games === null) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Perfis de jogo indisponíveis">
O Clipador no ar ainda é a versão antiga. Reinicie o serviço para a IA pesquisar os jogos das lives.
</EmptyState>
);
}
return (
<section aria-labelledby="jogos-titulo" className="grid gap-4">
<SectionHeader id="jogos-titulo"
title={<>Jogos{all.length > 0 && <span className="ml-2 text-base font-normal text-fg-subtle tabular-nums">{all.length}</span>}</>}
description="O que a IA sabe de cada jogo. Você lê em português; a IA recebe em inglês."
actions={
<div className="flex flex-wrap items-center gap-2">
{all.length >= SEARCH_FROM && (
<label htmlFor={searchId} className="relative block">
<span className="sr-only">Buscar jogo pelo nome</span>
<SearchIcon size={15} className="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-fg-subtle" />
<Input id={searchId} type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar jogo…" className="h-9 w-56 pl-9" />
</label>
)}
<Button onClick={() => setAdding(true)}><PlusIcon size={16} />Adicionar jogo</Button>
</div>
} />
{all.length === 0 ? (
<EmptyState compact icon={<BookIcon size={18} />} title="Nenhum jogo ainda"
action={<Button size="sm" onClick={() => setAdding(true)}><PlusIcon size={15} />Adicionar jogo</Button>}>
Adicione um jogo aqui, ou ele entra sozinho quando uma sessão identifica o jogo (pela categoria ou pela tela).
</EmptyState>
) : needle && shown.length === 0 ? (
<p className="text-sm text-fg-muted">Nenhum jogo com “{query.trim()}”.</p>
) : (
<Table>
<THead>
<Th>Jogo</Th><Th>Estado</Th><Th className="text-right">Missões</Th><Th className="text-right">Gatilhos</Th>
<Th>IA lê em</Th><Th>Atualizado</Th><Th className="text-right">Ações</Th>
</THead>
<tbody>
{shown.map((g) => (
<GameRow key={g.id} game={g} active={g.id === openId} onOpen={() => setOpen(g.id)} onGamesChanged={setGames} />
))}
</tbody>
</Table>
)}
<AddGameDialog open={adding} onClose={() => setAdding(false)} existing={all}
onCreated={(list) => { if (list) setGames(list); else void refresh(); setAdding(false); }} />
<GameDialog game={openGame} name={openGame?.name ?? openId ?? ""} open={Boolean(openGame)} onClose={() => setOpen(null)} onGamesChanged={setGames} />
</section>
);
}
/* ---------- Linha ---------- */
function GameRow({ game: g, active, onOpen, onGamesChanged }: { game: Game; active: boolean; onOpen: () => void; onGamesChanged: (games: Game[]) => void }) {
const { pending, message, run } = useGameActions(onGamesChanged);
const p = g.profile;
const title = p?.name || g.name;
const hue = hueOf(title);
const aliases = aliasesOf(g);
const missions = p?.missions;
const triggers = (g.profileAi ?? p)?.end_triggers;
const updated = [g.editedAt, g.researchedAt].filter(Boolean).sort().at(-1) ?? null;
const busy = pending !== null || g.status === "pending";
const path = gamePath(g.id);
// Clique na linha abre o modal, menos em botões e links.
const onClick = (e: MouseEvent<HTMLTableRowElement>) => {
if ((e.target as HTMLElement).closest("button, a, input")) return;
onOpen();
};
return (
<>
<tr onClick={onClick}
className={cx("cursor-pointer border-t border-line transition-colors first:border-t-0 hover:bg-raised/40", active && "bg-accent-soft/30")}>
<Td>
<div className="flex min-w-0 items-center gap-3">
<span aria-hidden="true" className="grid size-9 shrink-0 place-items-center rounded-lg text-xs font-bold text-white"
style={{ background: `linear-gradient(135deg, hsl(${hue} 65% 52%), hsl(${(hue + 40) % 360} 70% 40%))` }}>
{monogram(title)}
</span>
<span className="grid min-w-0">
<button type="button" onClick={onOpen} className="w-fit truncate text-left font-semibold text-fg hover:text-accent focus-visible:outline-2 focus-visible:outline-accent">
{title}
</button>
<span className="truncate text-xs text-fg-subtle">
{[p?.genre, aliases.length ? aliases.slice(0, 3).join(" · ") : null].filter(Boolean).join(" · ") || "—"}
</span>
</span>
</div>
</Td>
<Td><GameStatusBadge game={g} /></Td>
<Td className="text-right tabular-nums">
{missions === undefined ? <span className="text-fg-subtle">—</span>
: missions.length === 0 ? <span className="text-xs text-fg-subtle">não públicas</span>
: <span className="font-medium text-fg">{missions.length}</span>}
</Td>
<Td className="text-right tabular-nums">
{triggers?.length ? <span className="font-medium text-accent">{triggers.length}</span> : <span className="text-fg-subtle">—</span>}
</Td>
<Td>
{g.profileAi ? <Badge tone="success" dot={false}><GlobeIcon size={12} />EN</Badge> : (
<span className="flex items-center gap-1.5">
<Badge tone="warning" dot={false}>PT</Badge>
{p && (
<Button variant="ghost" size="sm" disabled={busy} title="Gerar a versão em inglês que vai para a IA"
onClick={() => void run("translate", () => clipperCall<GamesReply>(`${path}/translate`, "POST"), "Versão da IA gerada.", true)}>
{pending === "translate" ? <Spinner className="size-3.5" /> : null}traduzir
</Button>
)}
</span>
)}
</Td>
<Td className="text-xs text-fg-subtle">{updated ? formatRelative(updated) : "—"}</Td>
<Td className="text-right">
<div role="group" aria-label={`Ações do jogo ${title}`} className="flex items-center justify-end gap-1">
<Button variant="ghost" size="sm" disabled={busy} title="Pesquisar de novo na web" aria-label={`Pesquisar de novo ${title}`} className="px-2"
onClick={async () => {
if (g.editedAt && !(await askConfirm({ title: "Pesquisar de novo?",
message: "Refaz o perfil do zero e apaga o que você editou à mão. Os pedidos que você fez à IA são aplicados de novo.",
confirmLabel: "Pesquisar de novo", tone: "danger" }))) return;
void run("research", () => clipperCall<GamesReply>(`${path}/research`, "POST"), "Pesquisa concluída.", true);
}}>
{pending === "research" || g.status === "pending" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}
</Button>
<Button variant="ghost" size="sm" disabled={busy} title="Apagar jogo" aria-label={`Apagar o jogo ${title}`}
className="px-2 text-fg-subtle hover:bg-danger-soft hover:text-danger"
onClick={async () => {
if (!(await askConfirm({ title: `Apagar o jogo “${title}”?`,
message: "O perfil, as missões e os pedidos guardados somem. As sessões não mudam; se o jogo voltar numa live, a IA pesquisa de novo.",
confirmLabel: "Apagar jogo", tone: "danger" }))) return;
void run("delete", () => clipperCall<GamesReply | null>(path, "DELETE"), "Jogo apagado.");
}}>
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}
</Button>
<Button variant="ghost" size="sm" title="Abrir" aria-label={`Abrir o jogo ${title}`} className="px-2" onClick={onOpen}>
<ArrowRightIcon size={15} />
</Button>
</div>
</Td>
</tr>
{(message || (g.status === "error" && g.error)) && (
<tr className="border-t border-line">
<td colSpan={7} className="px-4 py-2" aria-live="polite">
{message ? <Feedback ok={message.ok}>{message.text}</Feedback> : <p className="text-xs break-words text-danger">{g.error}</p>}
</td>
</tr>
)}
</>
);
}
/* ---------- Adicionar jogo ---------- */
function AddGameDialog({ open, onClose, existing, onCreated }: {
open: boolean; onClose: () => void; existing: Game[]; onCreated: (games: Game[] | null) => void;
}) {
const formId = useId();
const [name, setName] = useState("");
const [notes, setNotes] = useState("");
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
const clean = name.trim().toLowerCase();
const duplicate = clean ? existing.find((g) => g.name.toLowerCase() === clean || aliasesOf(g).some((a) => a.toLowerCase() === clean)) : undefined;
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!name.trim() || duplicate) return;
setPending(true);
setError(null);
const r = await clipperCall<Partial<GamesReply> | null>("games", "POST", { name: name.trim(), ...(notes.trim() ? { notes: notes.trim() } : {}) });
setPending(false);
if (!r.ok) { setError(r.error); return; }
setName("");
setNotes("");
onCreated(r.data && Array.isArray(r.data.games) ? r.data.games : null);
}
return (
<Dialog open={open} onClose={onClose} size="sm" eyebrow="Jogos" title="Adicionar jogo"
description="A IA pesquisa na web em inglês (resumo, missões, gatilhos de fim, gírias, o que rende corte) e traduz para você ler. Leva de 1 a 5 min."
footer={<>
<Button type="button" variant="ghost" onClick={onClose}>Cancelar</Button>
<Button type="submit" form={formId} disabled={pending || !name.trim() || Boolean(duplicate)}>
{pending ? <><Spinner />Cadastrando…</> : <><PlusIcon size={16} />Adicionar e pesquisar</>}
</Button>
</>}>
<form id={formId} onSubmit={submit} className="grid gap-4">
<Field label="Nome do jogo" hint={duplicate ? undefined : "Use o nome oficial (ex.: Grand Theft Auto VI). Abreviações viram “outros nomes” depois."}>
<Input value={name} onChange={(e) => setName(e.target.value)} required maxLength={120} autoFocus placeholder="Ex.: Grand Theft Auto VI" />
</Field>
{duplicate && <p className="text-xs text-warning">Este jogo já está na lista como “{duplicate.name}”.</p>}
<Field label="O que a IA deve saber ou pesquisar (opcional)" hint="Vira um pedido guardado: volta em toda pesquisa nova deste jogo.">
<Textarea rows={3} maxLength={1500} value={notes} onChange={(e) => setNotes(e.target.value)}
placeholder="Ex.: o streamer joga o modo história; liste as missões e o que aparece na tela quando cada uma termina." />
</Field>
<div aria-live="polite" className="empty:hidden">{error && <Feedback ok={false}>{error}</Feedback>}</div>
</form>
</Dialog>
);
}
+18 -539
View File
@@ -1,17 +1,15 @@
"use client";
// Contexto do jogo e emotes do Clipador: o jogo da sessão (com correção à mão e aviso quando a tela
// diverge da categoria), o perfil que a IA pesquisou ("O que a IA sabe do jogo") e a tabela de emotes
// do canal com o peso que eles aprenderam com as suas aprovações.
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react";
// diverge da categoria), o atalho "O que a IA sabe do jogo" (abre o modal do jogo, clipper-game-dialog.tsx) e a
// tabela de emotes do canal com o peso que eles aprenderam com as suas aprovações.
// A página Jogos (lista + modal) fica em clipper-games-page.tsx.
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
GAME_SOURCE_LABEL, clipperCall, gameIdOf, useClipperAction, type ClipperSession, type Emote, type Game, type GameProfile,
GAME_SOURCE_LABEL, clipperCall, gameIdOf, useClipperAction, type ClipperSession, type Emote, type Game,
} from "./clipper-client";
import type { ApiResult } from "./api-client";
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, LinkIcon, PenIcon, RefreshIcon, SendIcon, SparkIcon, XIcon } from "./icons";
import {
Badge, Button, EmptyState, Feedback, Field, Input, Spinner, Switch, Table, Td, Th, THead, Textarea, Tr, cx, formatRelative, hueOf,
} from "./ui";
import { askConfirm } from "./confirm-dialog";
import { GameDialog } from "./clipper-game-dialog";
import { AlertIcon, BookIcon, ChatIcon, CheckIcon, ChevronDownIcon, PenIcon } from "./icons";
import { Badge, Button, Feedback, Input, Spinner, Table, Td, Th, THead, Tr, cx, formatRelative } from "./ui";
/* ---------- Jogo da sessão ---------- */
@@ -25,7 +23,7 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
const screen = session.screenGame ?? "";
const confirmed = session.gameSource === "user";
const mismatch = Boolean(game && screen && !confirmed && gameIdOf(screen) !== gameIdOf(game));
const profile = game ? games.find((g) => g.id === gameIdOf(game)) : undefined;
const profile = game ? findGame(games, game) : undefined;
/** Confirma o jogo: trava a troca automática e a IA deixa de questionar o que vê na tela. */
async function confirmGame(name: string) {
@@ -51,10 +49,9 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
)}
<Button variant="ghost" size="sm" onClick={() => setChoosing(true)}><PenIcon size={14} />{confirmed ? "Trocar jogo" : "Escolher o jogo"}</Button>
{game && (
<Button variant="ghost" size="sm" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<Button variant="ghost" size="sm" aria-haspopup="dialog" onClick={() => setOpen(true)}>
<BookIcon size={14} />O que a IA sabe do jogo
{profile?.status === "pending" && <Spinner className="size-3" />}
<ChevronDownIcon size={14} className={cx("transition-transform", open && "rotate-180")} />
</Button>
)}
</div>
@@ -68,14 +65,19 @@ export function SessionGame({ session, games, onChanged, onGamesChanged }: {
)}
<GameChoiceDialog open={choosing} session={session} pending={pending === "game"}
onClose={() => setChoosing(false)} onConfirm={(name) => void confirmGame(name)} />
{open && game && (
<GameCard game={profile} name={game} onGamesChanged={onGamesChanged} />
)}
{game && <GameDialog game={profile} name={game} open={open} onClose={() => setOpen(false)} onGamesChanged={onGamesChanged} />}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
/** Jogo cadastrado com esse nome: pelo id ou por um dos outros nomes (aliases). */
function findGame(games: Game[], name: string): Game | undefined {
const id = gameIdOf(name);
return games.find((g) => g.id === id)
?? games.find((g) => [...(g.aliases ?? []), ...(g.profile?.aliases ?? []), ...(g.profileAi?.aliases ?? [])].some((a) => gameIdOf(a) === id));
}
/* ---------- Escolher/confirmar o jogo ---------- */
/** Modal nativo: o usuário confirma qual jogo está sendo jogado (categoria, o que a IA viu na tela ou outro nome). */
@@ -150,529 +152,6 @@ function GameChoiceDialog({ open, session, pending, onClose, onConfirm }: {
);
}
/* ---------- Perfil do jogo ---------- */
type GameAction = "research" | "save" | "note";
type GamesReply = { games: Game[] };
type RefineReply = GamesReply & { reply?: string };
type ListKey = Exclude<keyof GameProfile, "name" | "summary" | "genre">;
/** Seção que o chat da IA edita ("" = o perfil inteiro). */
type SectionKey = ListKey | "summary" | "";
/** Como cada seção aparece: cor, ícone, dica de edição e atalhos de pedido para o chat. */
const SECTIONS: Record<ListKey, { title: string; tone: "success" | "danger" | "info" | "violet" | "neutral"; hint: string; suggestions: string[] }> = {
clip_worthy: {
title: "O que rende corte", tone: "success", hint: "Uma situação por linha.",
suggestions: ["Reação do streamer conta (grito, risada, raiva)", "Momentos em que o chat explode de emotes", "Falha engraçada ou bug bizarro"],
},
avoid: {
title: "Evitar", tone: "danger", hint: "Uma situação por linha.",
suggestions: ["Tela de carregamento e fila", "Streamer lendo doação sem reação", "AFK ou pausa"],
},
mechanics: { title: "Mecânicas", tone: "info", hint: "Uma por linha.", suggestions: ["Explique melhor as mecânicas que aparecem nas lives", "Acrescente as mecânicas da última atualização"] },
news: { title: "Novidades", tone: "violet", hint: "Uma por linha, com mês/ano.", suggestions: ["Pesquise as novidades deste mês", "Tire as novidades com mais de 6 meses"] },
jargon: { title: "Gírias e termos", tone: "neutral", hint: "Um por linha.", suggestions: ["Acrescente as gírias que o chat usa", "Explique cada gíria em poucas palavras"] },
hashtags: {
title: "Hashtags", tone: "violet",
hint: "Uma por linha, a principal primeiro. As 3 primeiras entram em toda legenda de corte deste jogo, junto com a do canal e as do momento.",
suggestions: ["Pesquise as hashtags que o público usa para este jogo no TikTok", "Acrescente a hashtag do modo que o streamer joga"],
},
sources: { title: "Fontes", tone: "neutral", hint: "Uma URL por linha.", suggestions: [] },
};
const TONE_TEXT = { success: "text-success", danger: "text-danger", info: "text-info", violet: "text-violet", neutral: "text-fg-subtle" } as const;
const TONE_BAR = { success: "bg-success", danger: "bg-danger", info: "bg-info", violet: "bg-violet", neutral: "bg-line-strong" } as const;
/**
* Ações do perfil do jogo que não são o chat: pesquisar de novo, salvar a edição à mão, esquecer um pedido.
* Pesquisa pode levar minutos: se o painel desistir de esperar, o serviço segue.
*/
function useGameActions(onGamesChanged: (games: Game[]) => void) {
const [pending, setPending] = useState<GameAction | null>(null);
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
async function run(action: GameAction, call: () => Promise<ApiResult<GamesReply>>, okText: string, slow = false) {
setPending(action);
setMessage(null);
const r = await call();
setPending(null);
if (r.ok) {
onGamesChanged(r.data.games);
setMessage({ ok: true, text: okText });
return true;
}
setMessage({ ok: false, text: slow ? `${r.error} Se demorou demais, a IA pode continuar no serviço: clique em Atualizar daqui a pouco.` : r.error });
if (slow) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return false;
}
return { pending, message, run };
}
/** Iniciais do jogo para o selo: primeira e última palavra ("Call of Duty: Warzone" → "CW"). */
function monogram(title: string): string {
const words = title.replace(/[^\p{L}\p{N} ]/gu, " ").split(/\s+/).filter(Boolean);
if (words.length === 0) return "?";
return (words.length === 1 ? words[0].slice(0, 2) : words[0][0] + words[words.length - 1][0]).toUpperCase();
}
/** Itens que entraram/saíram numa lista (para destacar o que a IA acrescentou). */
function diffList(before: string[] = [], after: string[] = []) {
const had = new Set(before.map((s) => s.toLowerCase()));
const has = new Set(after.map((s) => s.toLowerCase()));
return { added: after.filter((s) => !had.has(s.toLowerCase())), removed: before.filter((s) => !has.has(s.toLowerCase())) };
}
export function GameCard({ game, name, onGamesChanged }: { game: Game | undefined; name: string; onGamesChanged: (games: Game[]) => void }) {
const { pending, message, run } = useGameActions(onGamesChanged);
const [editing, setEditing] = useState(false);
const [chatOpen, setChatOpen] = useState<SectionKey | null>(null);
const [chatBusy, setChatBusy] = useState(false);
const [fresh, setFresh] = useState<Set<string>>(new Set()); // itens que a IA acabou de acrescentar (destaque)
const id = game?.id ?? gameIdOf(name);
const path = `games/${encodeURIComponent(id)}`;
const busy = pending !== null || chatBusy || game?.status === "pending";
const title = game?.profile?.name || game?.name || name;
const hue = hueOf(title);
async function research() {
// Pesquisar refaz o perfil do zero: a edição à mão some; os pedidos guardados entram de novo na pesquisa.
if (game?.editedAt && !(await askConfirm({ title: "Pesquisar de novo?",
message: "Refaz o perfil do zero e apaga o que você editou à mão. Os pedidos que você fez à IA são aplicados de novo.",
confirmLabel: "Pesquisar de novo", tone: "danger" }))) return;
void run("research", () => clipperCall<GamesReply>(`${path}/research`, "POST"), "Pesquisa concluída.", true);
}
/** Manda um pedido do chat; aplica o perfil novo e devolve a resposta da IA + o que mudou na seção. */
async function ask(section: SectionKey, instruction: string, search: boolean, history: ChatTurn[]): Promise<ChatTurn> {
setChatBusy(true);
const before = game?.profile;
const r = await clipperCall<RefineReply>(`${path}/refine`, "POST", {
instruction, search, section, history: history.map(({ role, text }) => ({ role, text })),
});
setChatBusy(false);
if (!r.ok) {
if (search) {
const list = await clipperCall<GamesReply>("games");
if (list.ok) onGamesChanged(list.data.games);
}
return { role: "ai", text: r.error, error: true };
}
onGamesChanged(r.data.games);
const after = r.data.games.find((g) => g.id === id)?.profile;
let added = 0, removed = 0;
const nextFresh = new Set<string>();
for (const key of Object.keys(SECTIONS) as ListKey[]) {
const d = diffList(before?.[key], after?.[key]);
added += d.added.length;
removed += d.removed.length;
for (const item of d.added) nextFresh.add(`${key}:${item.toLowerCase()}`);
}
setFresh(nextFresh);
return { role: "ai", text: r.data.reply || "Pronto, atualizei o perfil.", added, removed };
}
return (
<article className="overflow-hidden rounded-panel border border-line bg-surface/60">
{/* Cabeçalho: monograma do jogo, nome, gênero, de onde veio e ações. */}
<header className="relative flex flex-wrap items-start gap-4 border-b border-line p-4 sm:p-5"
style={{ backgroundImage: `linear-gradient(120deg, hsl(${hue} 70% 50% / 0.10), transparent 55%)` }}>
<div aria-hidden="true" className="grid size-12 shrink-0 place-items-center rounded-xl text-lg font-bold text-white shadow-sm"
style={{ background: `linear-gradient(135deg, hsl(${hue} 65% 52%), hsl(${(hue + 40) % 360} 70% 40%))` }}>
{monogram(title)}
</div>
<div className="grid min-w-0 flex-1 gap-1.5">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-semibold tracking-tight text-fg">{title}</h3>
{!game ? <Badge>não pesquisado</Badge>
: game.status === "pending" ? <Badge tone="info" pulse>pesquisando</Badge>
: game.status === "error" ? <Badge tone="danger">erro na pesquisa</Badge> : null}
</div>
{game?.profile?.genre && <p className="text-xs font-medium text-fg-muted">{game.profile.genre}</p>}
<p className="flex flex-wrap gap-x-2 text-xs text-fg-subtle">
{game?.researchedAt && <span>pesquisado {formatRelative(game.researchedAt)}</span>}
{game?.editedAt && <span>· editado {formatRelative(game.editedAt)}</span>}
{game?.model && <span className="font-mono">· {game.model}</span>}
</p>
</div>
<div className="flex flex-wrap gap-1.5">
{game?.profile && !editing && (
<Button variant="secondary" size="sm" disabled={busy} onClick={() => setChatOpen(chatOpen === "" ? null : "")}>
<SparkIcon size={14} />Conversar com a IA
</Button>
)}
{game && !editing && (
<Button variant="ghost" size="sm" disabled={busy} onClick={() => setEditing(true)}><PenIcon size={14} />Editar</Button>
)}
<Button variant="ghost" size="sm" disabled={busy || editing} onClick={research}>
{pending === "research" ? <><Spinner className="size-3.5" />Pesquisando…</> : <><RefreshIcon size={15} />{game?.profile ? "Pesquisar de novo" : "Pesquisar"}</>}
</Button>
</div>
</header>
<div className="grid gap-4 p-4 sm:p-5">
{game?.status === "error" && game.error && <Feedback ok={false}>{game.error}</Feedback>}
{chatOpen === "" && game?.profile && !editing && (
<AiChat key="general" sectionTitle="o perfil inteiro" suggestions={["Reação do streamer conta como corte", "Acrescente as gírias que o chat usa", "Deixe o resumo mais curto"]}
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask("", text, search, history)} onClose={() => setChatOpen(null)} />
)}
{editing && game ? (
<ProfileEditor profile={game.profile} fallbackName={game.name} saving={pending === "save"} onCancel={() => setEditing(false)}
onSave={async (profile) => {
const ok = await run("save", () => clipperCall<GamesReply>(path, "PUT", profile), "Perfil salvo. A IA já usa a versão nova.");
if (ok) setEditing(false);
}} />
) : game?.profile ? (
<ProfileView profile={game.profile} fresh={fresh} chatOpen={chatOpen} disabled={busy && !chatBusy}
onToggleChat={(key) => setChatOpen(chatOpen === key ? null : key)}
renderChat={(key) => (
<AiChat key={key} sectionTitle={SECTIONS[key].title} suggestions={SECTIONS[key].suggestions} compact
disabled={busy && !chatBusy} onAsk={(text, search, history) => ask(key, text, search, history)} onClose={() => setChatOpen(null)} />
)} />
) : (
<EmptyState compact icon={<BookIcon size={18} />} title="Ainda sem perfil">
A IA pesquisa o jogo na web (mecânicas, gírias, o que costuma render corte) e usa isso para entender a live.
</EmptyState>
)}
{game && !editing && <SavedNotes notes={game.notes ?? []} disabled={busy}
onForget={(i) => void run("note", () => clipperCall<GamesReply>(`${path}/notes/${i}`, "DELETE"), "Pedido esquecido.")} />}
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</article>
);
}
/* ---------- Chat com a IA ---------- */
type ChatTurn = { role: "user" | "ai"; text: string; error?: boolean; added?: number; removed?: number };
/**
* Conversa com a IA sobre uma seção do perfil: você fala ("adicione que reação do streamer conta"), ela edita a
* lista e responde o que fez. Enter envia; Shift+Enter quebra linha. A conversa vale enquanto o chat está aberto;
* cada pedido fica guardado no serviço e volta nas próximas pesquisas.
*/
function AiChat({ sectionTitle, suggestions, compact = false, disabled, onAsk, onClose }: {
sectionTitle: string; suggestions: string[]; compact?: boolean; disabled: boolean;
onAsk: (text: string, search: boolean, history: ChatTurn[]) => Promise<ChatTurn>; onClose: () => void;
}) {
const [turns, setTurns] = useState<ChatTurn[]>([]);
const [text, setText] = useState("");
const [search, setSearch] = useState(false);
const [thinking, setThinking] = useState(false);
const inputId = useId();
const logRef = useRef<HTMLOListElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
useEffect(() => { logRef.current?.scrollTo({ top: logRef.current.scrollHeight, behavior: "smooth" }); }, [turns, thinking]);
async function send(raw: string) {
const clean = raw.trim();
if (clean.length < 3 || thinking || disabled) return;
const history = turns.filter((t) => !t.error);
setTurns((t) => [...t, { role: "user", text: clean }]);
setText("");
setThinking(true);
const reply = await onAsk(clean, search, history);
setThinking(false);
setTurns((t) => [...t, reply]);
inputRef.current?.focus();
}
return (
<section aria-label={`Conversa com a IA sobre ${sectionTitle}`}
className={cx("grid gap-3 rounded-control border border-accent/30 bg-accent-soft/40", compact ? "p-3" : "p-4")}>
<div className="flex items-center gap-2">
<span className="grid size-6 place-items-center rounded-full bg-accent text-accent-fg"><SparkIcon size={13} /></span>
<p className="min-w-0 flex-1 text-[0.8125rem] font-medium text-fg">IA · editando <span className="text-accent">{sectionTitle}</span></p>
<button type="button" onClick={onClose} aria-label="Fechar conversa"
className="rounded-md p-1 text-fg-subtle hover:bg-overlay hover:text-fg"><XIcon size={14} /></button>
</div>
{turns.length === 0 && !thinking ? (
<div className="grid gap-2">
<p className="text-xs leading-relaxed text-fg-muted">
Diga o que acrescentar, tirar ou corrigir — a IA edita a lista e explica o que fez.
</p>
{suggestions.length > 0 && (
<ul className="flex flex-wrap gap-1.5">
{suggestions.map((s) => (
<li key={s}>
<button type="button" disabled={disabled} onClick={() => void send(s)}
className="rounded-full border border-line bg-raised/70 px-2.5 py-1 text-xs text-fg-muted transition-colors hover:border-accent/50 hover:text-fg disabled:opacity-50">
{s}
</button>
</li>
))}
</ul>
)}
</div>
) : (
<ol ref={logRef} aria-live="polite" className="grid max-h-72 gap-2 overflow-y-auto pr-1">
{turns.map((t, i) => (
<li key={i} className={cx("flex", t.role === "user" ? "justify-end" : "justify-start")}>
<div className={cx("max-w-[85%] rounded-2xl px-3 py-2 text-[0.8125rem] leading-relaxed",
t.role === "user" ? "rounded-br-md bg-accent text-accent-fg"
: t.error ? "rounded-bl-md border border-danger/30 bg-danger-soft text-danger"
: "rounded-bl-md border border-line bg-raised text-fg")}>
{t.text}
{t.role === "ai" && !t.error && (t.added || t.removed) ? (
<span className="mt-1.5 flex gap-2 text-xs font-medium">
{t.added ? <span className="text-success">+{t.added} {t.added === 1 ? "item novo" : "itens novos"}</span> : null}
{t.removed ? <span className="text-danger">−{t.removed} {t.removed === 1 ? "removido" : "removidos"}</span> : null}
</span>
) : null}
</div>
</li>
))}
{thinking && (
<li className="flex justify-start">
<div role="status" className="flex items-center gap-1.5 rounded-2xl rounded-bl-md border border-line bg-raised px-3 py-2.5 text-xs text-fg-muted">
<span className="sr-only">A IA está editando…</span>
{[0, 150, 300].map((d) => <span key={d} aria-hidden="true" className="size-1.5 animate-bounce rounded-full bg-fg-subtle" style={{ animationDelay: `${d}ms` }} />)}
{search && <span className="ml-1">pesquisando na web…</span>}
</div>
</li>
)}
</ol>
)}
<form className="grid gap-2" onSubmit={(e) => { e.preventDefault(); void send(text); }}>
<label htmlFor={inputId} className="sr-only">Pedido para a IA</label>
<div className="flex items-end gap-2 rounded-control border border-line-strong bg-canvas/70 p-1.5 focus-within:border-accent/60">
<textarea ref={inputRef} id={inputId} rows={1} maxLength={1500} value={text} disabled={thinking}
placeholder="Ex.: adicione que reação do streamer conta para corte"
className="max-h-32 min-h-9 flex-1 resize-none bg-transparent px-2 py-1.5 text-sm text-fg placeholder:text-fg-subtle focus:outline-none"
onChange={(e) => { setText(e.target.value); e.target.style.height = "auto"; e.target.style.height = `${e.target.scrollHeight}px`; }}
onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void send(text); } }} />
<Button type="submit" size="sm" aria-label="Enviar" disabled={text.trim().length < 3 || thinking || disabled}>
{thinking ? <Spinner className="size-3.5" /> : <SendIcon size={14} />}
</Button>
</div>
<Switch label="Confirmar na web" checked={search} onChange={setSearch} disabled={thinking}
hint={search ? "Mais lento: a IA pesquisa antes (até alguns minutos)." : "Rápido: usa só o que você escreveu."} />
</form>
</section>
);
}
/** Pedidos que você fez à IA: voltam em toda pesquisa nova. Recolhido por padrão. */
function SavedNotes({ notes, disabled, onForget }: { notes: { text: string; at: string; section?: string }[]; disabled: boolean; onForget: (index: number) => void }) {
const [open, setOpen] = useState(false);
if (notes.length === 0) return null;
return (
<div className="grid gap-2 border-t border-line pt-3">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex w-fit items-center gap-1.5 text-xs font-medium text-fg-muted hover:text-fg">
<BookIcon size={13} />Memória da IA · {notes.length} {notes.length === 1 ? "pedido seu" : "pedidos seus"}
<ChevronDownIcon size={13} className={cx("transition-transform", open && "rotate-180")} />
</button>
{open && (
<>
<p className="text-xs text-fg-subtle">Voltam em toda pesquisa nova, para “Pesquisar de novo” não apagar o que você acrescentou.</p>
<ul className="grid gap-1">
{notes.map((n, i) => (
<li key={`${n.at}-${i}`} className="flex items-start gap-2 rounded-lg border border-line bg-raised/40 px-2.5 py-1.5 text-xs text-fg-muted">
{n.section && n.section in SECTIONS && (
<span className={cx("shrink-0 font-medium", TONE_TEXT[SECTIONS[n.section as ListKey].tone])}>{SECTIONS[n.section as ListKey].title}</span>
)}
<span className="min-w-0 flex-1 leading-relaxed break-words">{n.text}</span>
<span className="shrink-0 text-fg-subtle">{formatRelative(n.at)}</span>
<button type="button" aria-label={`Esquecer o pedido “${n.text.slice(0, 40)}”`} disabled={disabled}
title="Esquecer (não volta nas próximas pesquisas; o perfil atual fica como está)"
className="shrink-0 rounded p-0.5 text-fg-subtle hover:bg-overlay hover:text-danger disabled:opacity-50"
onClick={() => onForget(i)}>
<XIcon size={13} />
</button>
</li>
))}
</ul>
</>
)}
</div>
);
}
/* ---------- Edição à mão ---------- */
const EDIT_LISTS = (Object.keys(SECTIONS) as ListKey[]).map((key) => ({ key, label: SECTIONS[key].title, hint: SECTIONS[key].hint }));
type ProfileDraft = { name: string; genre: string; summary: string; lists: Record<string, string> };
function toDraft(profile: GameProfile | null, fallbackName: string): ProfileDraft {
return {
name: profile?.name || fallbackName,
genre: profile?.genre ?? "",
summary: profile?.summary ?? "",
lists: Object.fromEntries(EDIT_LISTS.map(({ key }) => [key, (profile?.[key] ?? []).join("\n")])),
};
}
function fromDraft(draft: ProfileDraft): GameProfile {
const lines = (text: string) => text.split(/\r?\n/).map((l) => l.replace(/^\s*[-•*]\s*/, "").trim()).filter(Boolean);
const lists = Object.fromEntries(EDIT_LISTS.map(({ key }) => [key, lines(draft.lists[key] ?? "")]));
return { name: draft.name.trim(), genre: draft.genre.trim(), summary: draft.summary.trim(), ...lists } as GameProfile;
}
function ProfileEditor({ profile, fallbackName, saving, onSave, onCancel }: {
profile: GameProfile | null; fallbackName: string; saving: boolean; onSave: (profile: GameProfile) => void; onCancel: () => void;
}) {
const [draft, setDraft] = useState(() => toDraft(profile, fallbackName));
const setList = (key: string, value: string) => setDraft((d) => ({ ...d, lists: { ...d.lists, [key]: value } }));
return (
<form className="grid gap-4" onSubmit={(e) => { e.preventDefault(); onSave(fromDraft(draft)); }}>
<div className="grid gap-4 md:grid-cols-2">
<Field label="Nome do jogo">
<Input value={draft.name} maxLength={120} onChange={(e) => setDraft({ ...draft, name: e.target.value })} />
</Field>
<Field label="Gênero">
<Input value={draft.genre} maxLength={120} onChange={(e) => setDraft({ ...draft, genre: e.target.value })} />
</Field>
</div>
<Field label="Resumo" hint="O que é o jogo e como se joga (2–3 frases).">
<Textarea rows={3} maxLength={1500} value={draft.summary} onChange={(e) => setDraft({ ...draft, summary: e.target.value })} />
</Field>
<div className="grid gap-4 md:grid-cols-2">
{EDIT_LISTS.map(({ key, label, hint }) => (
<Field key={key} label={<span className={TONE_TEXT[SECTIONS[key].tone]}>{label}</span>} hint={hint}>
<Textarea rows={Math.min(10, Math.max(3, (draft.lists[key] ?? "").split("\n").length + 1))}
value={draft.lists[key] ?? ""} onChange={(e) => setList(key, e.target.value)}
className={key === "sources" ? "font-mono text-xs" : undefined} />
</Field>
))}
</div>
<div className="sticky bottom-0 flex justify-end gap-2 border-t border-line bg-surface/90 py-3 backdrop-blur">
<Button type="button" variant="ghost" size="sm" disabled={saving} onClick={onCancel}>Cancelar</Button>
<Button type="submit" size="sm" disabled={saving}>
{saving ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar perfil
</Button>
</div>
</form>
);
}
/* ---------- Leitura do perfil ---------- */
function ProfileView({ profile: p, fresh, chatOpen, disabled, onToggleChat, renderChat }: {
profile: GameProfile; fresh: Set<string>; chatOpen: SectionKey | null; disabled: boolean;
onToggleChat: (key: ListKey) => void; renderChat: (key: ListKey) => ReactNode;
}) {
const block = (key: ListKey, wide = false) => (
<SectionBlock key={key} sectionKey={key} items={p[key] ?? []} fresh={fresh} wide={wide}
chatOpen={chatOpen === key} disabled={disabled} onToggleChat={() => onToggleChat(key)} chat={chatOpen === key ? renderChat(key) : null} />
);
return (
<div className="grid gap-4 text-[0.8125rem]">
{p.summary && <p className="max-w-[95ch] text-sm leading-relaxed text-fg-muted">{p.summary}</p>}
<div className="grid gap-3 lg:grid-cols-2">
{block("clip_worthy")}
{block("avoid")}
{block("mechanics")}
{block("news")}
{block("jargon", true)}
{block("hashtags", true)}
</div>
{p.sources?.length > 0 && <Sources sources={p.sources} />}
</div>
);
}
function SectionBlock({ sectionKey, items, fresh, wide, chatOpen, disabled, onToggleChat, chat }: {
sectionKey: ListKey; items: string[]; fresh: Set<string>; wide: boolean; chatOpen: boolean; disabled: boolean;
onToggleChat: () => void; chat: ReactNode;
}) {
const { title, tone } = SECTIONS[sectionKey];
const isFresh = (item: string) => fresh.has(`${sectionKey}:${item.toLowerCase()}`);
const chips = sectionKey === "jargon" || sectionKey === "hashtags";
return (
<section className={cx("relative grid content-start gap-3 overflow-hidden rounded-control border bg-sunken/40 p-4 pl-5 transition-colors",
chatOpen ? "border-accent/40" : "border-line", wide && "lg:col-span-2")}>
<span aria-hidden="true" className={cx("absolute inset-y-0 left-0 w-1", TONE_BAR[tone])} />
<div className="flex items-center gap-2">
<h4 className={cx("text-eyebrow font-semibold uppercase", TONE_TEXT[tone])}>{title}</h4>
<span className="rounded-full bg-overlay px-1.5 text-[0.6875rem] font-medium tabular-nums text-fg-subtle">{items.length}</span>
<button type="button" disabled={disabled} aria-expanded={chatOpen} onClick={onToggleChat}
className={cx("ml-auto flex items-center gap-1 rounded-full px-2 py-1 text-xs font-medium transition-colors disabled:opacity-50",
chatOpen ? "bg-accent text-accent-fg" : "text-fg-subtle hover:bg-accent-soft hover:text-accent")}>
<SparkIcon size={12} />{chatOpen ? "Fechar IA" : "Pedir à IA"}
</button>
</div>
{items.length === 0 ? (
<p className="text-xs text-fg-subtle">Vazio. Peça à IA para preencher.</p>
) : chips ? (
<ul className="flex flex-wrap gap-1.5">
{items.map((j, i) => (
<li key={i} className={cx("rounded-lg border px-2 py-1 text-xs transition-colors",
isFresh(j) ? "border-success/50 bg-success-soft text-success" : "border-line bg-raised/60 text-fg-muted")}>{j}</li>
))}
</ul>
) : (
<ul className="grid gap-1.5 text-fg-muted">
{items.map((it, i) => (
<li key={i} className={cx("flex gap-2 rounded-md leading-relaxed transition-colors",
isFresh(it) && "-mx-2 bg-success-soft px-2 py-1 text-fg")}>
<span aria-hidden="true" className={cx("mt-2 size-1.5 shrink-0 rounded-full", TONE_BAR[tone], !isFresh(it) && "opacity-60")} />
<span className="min-w-0 flex-1">{it}</span>
{isFresh(it) && <span className="mt-0.5 h-fit shrink-0 rounded-full bg-success px-1.5 text-[0.625rem] font-semibold text-canvas uppercase">novo</span>}
</li>
))}
</ul>
)}
{chat}
</section>
);
}
function Sources({ sources }: { sources: string[] }) {
const [open, setOpen] = useState(false);
return (
<div className="grid gap-1.5">
<button type="button" aria-expanded={open} onClick={() => setOpen((o) => !o)}
className="flex w-fit items-center gap-1.5 text-xs font-medium text-fg-subtle hover:text-fg">
<LinkIcon size={13} />{sources.length} {sources.length === 1 ? "fonte" : "fontes"}
<ChevronDownIcon size={13} className={cx("transition-transform", open && "rotate-180")} />
</button>
{open && (
<ul className="grid gap-1">
{sources.map((s, i) => (
<li key={i} className="truncate text-xs">
{/^https?:\/\//.test(s)
? <a href={s} target="_blank" rel="noreferrer noopener" className="text-fg-muted hover:text-fg hover:underline">{s.replace(/^https?:\/\/(www\.)?/, "")}</a>
: <span className="text-fg-subtle">{s}</span>}
</li>
))}
</ul>
)}
</div>
);
}
/* ---------- Aba Jogos ---------- */
export function GamesPanel({ games, available, onGamesChanged }: { games: Game[]; available: boolean; onGamesChanged: (games: Game[]) => void }) {
if (!available) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Perfis de jogo indisponíveis">
O Clipador no ar ainda é a versão antiga. Reinicie o serviço para a IA pesquisar os jogos das lives.
</EmptyState>
);
}
if (games.length === 0) {
return (
<EmptyState compact icon={<BookIcon size={18} />} title="Nenhum jogo pesquisado ainda">
Quando uma sessão identifica o jogo (pela categoria ou pela tela), a IA pesquisa o que ele tem de engraçado, as gírias e as novidades.
</EmptyState>
);
}
return (
<ul className="grid gap-5">
{games.map((g) => <li key={g.id}><GameCard game={g} name={g.name} onGamesChanged={onGamesChanged} /></li>)}
</ul>
);
}
/* ---------- Emotes do canal ---------- */
const EMOTE_SOURCE: Record<string, string> = { twitch: "Twitch", "7tv": "7TV", bttv: "BTTV", ffz: "FFZ", kick: "Kick", emoji: "emoji" };
+44 -7
View File
@@ -1,6 +1,8 @@
"use client";
// Juiz (IA) do Clipador: provedor (Codex/GPT, Claude ou desligado), os dois juízes (analista e editor),
// nota mínima e as opções da IA (varredura, visão, achar câmera). Roda pela CLI já logada no PC.
// Juiz (IA) do Clipador: provedor (Codex/GPT, Claude, Gemini ou desligado), os dois juízes (analista e editor),
// nota mínima e as opções da IA (varredura, visão, achar câmera). Roda pela CLI do PC; login, chave de API e IA
// reserva ficam em Configurações → IA (/settings/ai, contrato em doc/ia.md).
import Link from "next/link";
import { useState } from "react";
import {
PROVIDER_LABEL, clipperCall, formatScore, useClipperAction, type JudgeConfig, type JudgeOptions, type JudgeProvider,
@@ -22,8 +24,8 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
const [options, setOptions] = useState<JudgeOptions>(savedOptions);
const { pending, message, run } = useClipperAction();
const models = provider === "off" ? [] : judge.models[provider];
const fallback = provider === "off" ? "" : judge.models.defaults[provider];
const models = provider === "off" ? [] : judge.models[provider] ?? [];
const fallback = provider === "off" ? "" : judge.models.defaults[provider] ?? "";
// Modelo vazio = padrão do provedor. Ao trocar de provedor, o modelo antigo não vale mais.
const currentModel = models.some((m) => m.id === model) ? model : "";
const currentAnalyst = models.some((m) => m.id === analyst) ? analyst : "";
@@ -54,14 +56,18 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
title={<span className="flex flex-wrap items-center gap-3">
Quem decide o que vira corte
{judge.provider === "off" ? <Badge>desligado</Badge>
: judge.available ? <Badge tone="success">disponível</Badge> : <Badge tone="danger">CLI não encontrada</Badge>}
: !judge.available ? <Badge tone="danger">CLI não encontrada</Badge>
: judge.unavailableReason ? <Badge tone="warning">indisponível</Badge> : <Badge tone="success">disponível</Badge>}
</span>}
description="A IA confirma o momento, dá nota de 0 a 10 e escreve título e legenda. Roda pelo Codex ou pelo Claude já logado no PC, sem chave de API.">
description={<>A IA confirma o momento, dá nota de 0 a 10 e escreve título e legenda. Roda pela CLI do Codex, do Claude ou do Gemini
no PC; login ou chave de API e a IA reserva (se a escolhida cair, a próxima assume) se configuram
em <Link href="/settings/ai" className="font-medium text-accent underline-offset-2 hover:underline">Configurações → IA</Link>.</>}>
<form className="grid gap-7" onSubmit={(e) => { e.preventDefault(); void save(); }}>
<ChoiceGroup name="provider" legend="Provedor" value={provider} onChange={(p) => { setProvider(p); setModel(""); setAnalyst(""); }}
options={[
{ value: "codex", label: "Codex (GPT)", hint: "padrão" },
{ value: "claude", label: "Claude" },
{ value: "gemini", label: "Gemini", hint: "chave de API" },
{ value: "off", label: "Desligado", hint: "só heurística" },
]} />
@@ -130,9 +136,15 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
{judge.provider !== "off" && !judge.available && (
<Feedback ok={false}>
A CLI do {PROVIDER_LABEL[judge.provider]} não foi encontrada. Instale e faça login no terminal ({judge.provider === "codex" ? <code>codex login</code> : <code>claude</code>}), ou escolha outro provedor.
A CLI do {PROVIDER_LABEL[judge.provider]} não foi encontrada. Instale e faça login no terminal ({judge.provider === "codex" ? <code>codex login</code> : judge.provider === "gemini" ? <code>npm install -g @google/gemini-cli</code> : <code>claude</code>}), ou escolha outro provedor.
</Feedback>
)}
{judge.provider !== "off" && judge.available && judge.unavailableReason && (
<Feedback ok={false}>
{PROVIDER_LABEL[judge.provider]}: {judge.unavailableReason}. Ajuste em <Link href="/settings/ai" className="underline">Configurações → IA</Link>{judge.fallback?.chain.length ? " (até lá, a reserva responde)" : ""}.
</Feedback>
)}
{judge.provider !== "off" && <FallbackLine judge={judge} />}
{judge.path && <p className="font-mono text-xs break-all text-fg-subtle">{judge.path}</p>}
<div className="flex flex-wrap items-center gap-3">
@@ -144,3 +156,28 @@ export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (ne
</Card>
);
}
/** Linha discreta com a cadeia de reserva efetiva e as IAs em pausa (só aparece se o serviço mandar). */
function FallbackLine({ judge }: { judge: JudgeConfig }) {
const fb = judge.fallback;
const pauses = judge.pauses ?? [];
if (!fb && pauses.length === 0) return null;
const time = (iso: string) => new Date(iso).toLocaleTimeString("pt-BR", { hour: "2-digit", minute: "2-digit" });
return (
<div className="grid gap-1 text-xs text-fg-subtle">
{fb && (
<p>
{fb.enabled
? <>Ordem de tentativa: {fb.chain.length ? fb.chain.map((p) => PROVIDER_LABEL[p]).join(" → ") : "nenhuma IA pronta"} · pausa de {fb.cooldownMin} min depois de falha.</>
: <>IA reserva desligada: só {PROVIDER_LABEL[judge.provider]} é usada.</>}
</p>
)}
{pauses.map((p) => (
<p key={p.provider} className="flex items-start gap-1.5 text-warning">
<AlertIcon size={12} className="mt-0.5" />
<span>{PROVIDER_LABEL[p.provider]} em pausa até {time(p.until)}: <span className="break-words">{p.reason}</span></span>
</p>
))}
</div>
);
}
+164
View File
@@ -0,0 +1,164 @@
"use client";
// Dados do Clipador compartilhados pelas subpáginas (/clipper, /clipper/sessions, /clipper/sources, /clipper/games,
// /clipper/settings): estado do serviço, cortes, sessões, fontes, juiz e jogos, lidos de /api/clipper/*.
// Consulta de novo a cada 5 s enquanto houver sessão gravando/processando ou corte na fila (e a cada 10 s com o
// serviço fora do ar, para perceber quando ele volta); para quando a aba fica oculta.
// O provider fica no layout do grupo (studio): trocar de subpágina não recarrega nada nem zera o que já veio.
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import type { ChannelAccounts } from "./clipper-channels";
import {
ACTIVE_CLIP, ACTIVE_SESSION, clipperCall, isOfflineError, sourceName,
type Clip, type ClipperChannel, type ClipperSession, type ClipperStatus, type Game, type JudgeConfig,
} from "./clipper-client";
import { AlertIcon, RefreshIcon } from "./icons";
import { Button, Spinner } from "./ui";
const POLL_ACTIVE_MS = 5000;
const POLL_OFFLINE_MS = 10_000;
export type ClipperData = { status: ClipperStatus; clips: Clip[]; sessions: ClipperSession[]; channels: ClipperChannel[] };
export type ClipperContextValue = {
/** null até a 1ª resposta boa (ou enquanto o serviço está fora do ar sem nunca ter respondido). */
data: ClipperData | null;
/** Mensagem de "fora do ar"/"não instalado"; null com o serviço respondendo. */
offline: string | null;
/** Erro parcial (uma das listas falhou) — os dados anteriores continuam valendo. */
loadError: string | null;
loadedOnce: boolean;
refreshing: boolean;
/** A consulta periódica está ligada (há algo mudando sozinho ou o serviço está fora). */
polling: boolean;
judge: JudgeConfig | null;
setJudge: (next: JudgeConfig) => void;
/** Jogos pesquisados pela IA; null = serviço antigo, sem a rota /games. */
games: Game[] | null;
setGames: (next: Game[]) => void;
refresh: (withJudge?: boolean) => Promise<void>;
/** Recarregar tudo (depois de uma ação). */
reload: () => void;
/** Canais de publicação ligados a cada fonte (vem do servidor do painel). */
channelAccounts: ChannelAccounts;
nameOfSession: (s: ClipperSession) => string;
nameOfClip: (c: Clip) => string;
};
const ClipperContext = createContext<ClipperContextValue | null>(null);
export function ClipperProvider({ channelAccounts, children }: { channelAccounts: ChannelAccounts; children: ReactNode }) {
const [data, setData] = useState<ClipperData | null>(null);
const [judge, setJudge] = useState<JudgeConfig | null>(null);
const [offline, setOffline] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [loadedOnce, setLoadedOnce] = useState(false);
const [visible, setVisible] = useState(true);
const [games, setGames] = useState<Game[] | null>(null);
const refresh = useCallback(async (withJudge = false) => {
setRefreshing(true);
const [status, clips, sessions, channels, judgeResult, gamesResult] = await Promise.all([
clipperCall<ClipperStatus>("status"),
clipperCall<{ clips: Clip[] }>("clips?limit=500"),
clipperCall<{ sessions: ClipperSession[] }>("sessions?limit=50"),
clipperCall<{ channels: ClipperChannel[] }>("channels"),
withJudge ? clipperCall<JudgeConfig>("judge") : Promise.resolve(null),
clipperCall<{ games: Game[] }>("games"),
]);
setRefreshing(false);
setLoadedOnce(true);
if (!status.ok) {
if (isOfflineError(status.error)) { setOffline(status.error); setLoadError(null); }
else setLoadError(status.error);
return;
}
setOffline(null);
const firstError = [clips, sessions, channels].find((r) => !r.ok);
setLoadError(firstError && !firstError.ok ? firstError.error : null);
setData((prev) => ({
status: status.data,
clips: clips.ok ? clips.data.clips : prev?.clips ?? [],
sessions: sessions.ok ? sessions.data.sessions : prev?.sessions ?? [],
channels: channels.ok ? channels.data.channels : prev?.channels ?? [],
}));
if (judgeResult?.ok) setJudge(judgeResult.data);
setGames(gamesResult.ok ? gamesResult.data.games : null);
}, []);
useEffect(() => { void refresh(true); }, [refresh]);
useEffect(() => {
const onVisibility = () => {
const now = document.visibilityState === "visible";
setVisible(now);
if (now) void refresh();
};
document.addEventListener("visibilitychange", onVisibility);
return () => document.removeEventListener("visibilitychange", onVisibility);
}, [refresh]);
const active = Boolean(data && (data.sessions.some((s) => ACTIVE_SESSION.includes(s.status)) || data.clips.some((c) => ACTIVE_CLIP.includes(c.status))));
const interval = !visible ? null : offline ? POLL_OFFLINE_MS : active ? POLL_ACTIVE_MS : null;
useEffect(() => {
if (interval === null) return;
// Voltou do "fora do ar": recarrega também o juiz.
const timer = setInterval(() => void refresh(offline !== null), interval);
return () => clearInterval(timer);
}, [interval, offline, refresh]);
const reload = useCallback(() => void refresh(), [refresh]);
const channels = data?.channels;
const nameOfSession = useCallback((s: ClipperSession) => sourceName(s.channelId, s.url, channels ?? []), [channels]);
const nameOfClip = useCallback((c: Clip) => sourceName(c.channelId, c.sessionUrl, channels ?? []), [channels]);
const value = useMemo<ClipperContextValue>(() => ({
data, offline, loadError, loadedOnce, refreshing, polling: interval !== null, judge, setJudge, games, setGames,
refresh, reload, channelAccounts, nameOfSession, nameOfClip,
}), [data, offline, loadError, loadedOnce, refreshing, interval, judge, games, refresh, reload, channelAccounts, nameOfSession, nameOfClip]);
return <ClipperContext.Provider value={value}>{children}</ClipperContext.Provider>;
}
export function useClipper(): ClipperContextValue {
const ctx = useContext(ClipperContext);
if (!ctx) throw new Error("useClipper precisa estar dentro de <ClipperProvider> (layout de /clipper).");
return ctx;
}
/** Dados já carregados. Só use dentro de <ClipperGate>, que garante que existem. */
export function useClipperData(): ClipperData {
const { data } = useClipper();
if (!data) throw new Error("useClipperData fora de <ClipperGate>.");
return data;
}
/**
* Mostra "consultando…" antes da 1ª resposta e o aviso de "fora do ar" quando o serviço não responde; com dados,
* renderiza o conteúdo. Cada subpágina envolve o próprio conteúdo nele.
*/
export function ClipperGate({ children }: { children: ReactNode }) {
const { loadedOnce, offline, data, loadError, refreshing, refresh } = useClipper();
if (!loadedOnce) {
return <div role="status" className="flex items-center gap-3 py-6 text-sm text-fg-muted"><Spinner />Consultando o Clipador…</div>;
}
if (offline || !data) {
return (
<div className="grid gap-4">
<div role="alert" className="grid gap-2 rounded-card border border-danger/30 bg-danger-soft px-5 py-4 text-sm">
<p className="flex items-start gap-2 font-semibold text-danger"><AlertIcon size={16} className="mt-0.5" />O Clipador está fora do ar.</p>
{(offline ?? loadError) && <p className="font-mono text-xs break-words text-danger/90">{offline ?? loadError}</p>}
<p className="text-fg-muted">
Rode <code>start.bat</code> (ou <code>pnpm dev</code>) para subir o painel com o Clipador (porta 4520). Se ainda não instalou,
rode <code>setup.bat</code> antes. Esta página tenta de novo a cada 10 s.
</p>
</div>
<div>
<Button variant="secondary" onClick={() => void refresh(true)} disabled={refreshing}>
{refreshing ? <Spinner /> : <RefreshIcon size={16} />}Tentar de novo
</Button>
</div>
</div>
);
}
return <>{children}</>;
}
+77 -720
View File
@@ -1,42 +1,33 @@
"use client";
// Fila de cortes do Clipador: filtros por etapa (para aprovar, na fila, aprovados…) e um cartão por
// corte com o vídeo (9:16, ou 16:9 se o corte for horizontal; sem `aspect` = vertical), título e legenda editáveis, o veredito da IA, os sinais do chat, ajuste fino
// de início/fim e as ações da etapa. "Ordenar" (mais novos, maior nota da IA, sinal mais forte…) só reordena
// o que a aba mostra, no navegador; a escolha fica lembrada no localStorage. Os dados vêm de cima (ClipperStudio); cada ação recarrega tudo.
// Apagar: "Apagar" em cada cartão (confirmação curta no próprio cartão). Seleção discreta (pedido do dono: "bem
// sutil, no cantinho"): "Selecionar" e o menu "⋯" (com "Apagar todos desta aba", modal que respeita o filtro de
// sessão) no canto da linha das abas; a caixa de cada cartão só aparece no hover/foco ou no modo de seleção; com algo
// selecionado, uma pílula pequena no canto de baixo. Nada disso ocupa espaço na página: a lista nunca se mexe.
// O resultado sai num aviso fixo, que também não empurra a lista.
// Fila de cortes do Clipador — o que é da LISTA e não de um corte: as etapas (para aprovar, na fila, aprovados…),
// as ordenações (lembradas no localStorage), o estado da publicação dos aprovados (jobs do Publicador por corte),
// apagar (um, vários ou a aba inteira, com confirmação) e a UI discreta da seleção: "Selecionar" + menu "⋯" na barra,
// pílula pequena no canto de baixo com algo selecionado, aviso fixo com o resultado. Nada disso ocupa espaço na
// lista: ela nunca se mexe. As peças de um corte (vídeo, veredito, ações) ficam em clipper-clip-parts.tsx.
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import {
ACTIVE_CLIP, CLIP_DELETE_MAX, CLIP_STATUS, FACE_LABEL, UNDELETABLE_CLIP, aspectOf, SITUATION_LABEL, SOURCE_LABEL, TAG_LABEL, clipperCall, deleteSummary, formatClock, formatDuration, formatScore, useClipperAction,
type Clip, type ClipAnalysis, type ClipDeleteResult, type ClipDeleted, type ClipStatus, type ClipTags, type ClipperSession, type Situation,
} from "./clipper-client";
import { ClipPublishButton } from "./clip-publish";
import { askConfirm } from "./confirm-dialog";
import { AlertIcon, ChatIcon, CheckIcon, ClockIcon, EyeIcon, PublishIcon, RefreshIcon, ScissorsIcon, SparkIcon, TrashIcon, UndoIcon, XIcon } from "./icons";
import { CLIP_DELETE_MAX, clipperCall, deleteSummary, type Clip, type ClipDeleteResult, type ClipDeleted, type ClipStatus } from "./clipper-client";
import { judgeScore } from "./clipper-clip-parts";
import { AlertIcon, CheckIcon, TrashIcon, XIcon } from "./icons";
import { listJobs, type PublishJob } from "./publishing-client";
import { PublishChips, TextLink } from "./publishing-ui";
import { Badge, Button, EmptyState, Feedback, Input, LinkButton, Select, Spinner, Textarea, cx, fileUrl, formatRelative } from "./ui";
import { Spinner, cx } from "./ui";
/* ---------- Etapas ---------- */
export type QueueFilter = "ready" | "queue" | "approved" | "discarded" | "rejected" | "error";
export const QUEUE_FILTERS: { id: QueueFilter; label: string; statuses: ClipStatus[]; empty: string }[] = [
{ id: "ready", label: "Para aprovar", statuses: ["ready"], empty: "Quando a IA aprovar um momento e o vídeo ficar pronto, ele aparece aqui para você decidir." },
{ id: "queue", label: "Na fila", statuses: ["candidate", "pending", "rendering"], empty: "Nada esperando a IA ou o render agora." },
{ id: "approved", label: "Aprovados", statuses: ["approved", "published"], empty: "Os cortes que você aprovar ficam aqui." },
{ id: "approved", label: "Aprovados", statuses: ["approved", "published"], empty: "Os cortes que você aprovar ficam aqui, com o estado em cada rede." },
{ id: "discarded", label: "Descartados pela IA", statuses: ["discarded"], empty: "A IA não descartou nenhum momento. Os descartados podem ser renderizados à força." },
{ id: "rejected", label: "Rejeitados", statuses: ["rejected"], empty: "Nenhum corte rejeitado." },
{ id: "error", label: "Com erro", statuses: ["error"], empty: "Nenhum corte com erro." },
];
export type QueueSort = "newest" | "oldest" | "bestScore" | "worstScore" | "strongestSignal" | "longest";
/* ---------- Ordenação ---------- */
/** Nota da IA (0–10) do corte; `null` quando a IA ainda não julgou ou deu erro. */
function judgeScore(clip: Clip): number | null {
return clip.judge && "score" in clip.judge ? clip.judge.score : null;
}
export type QueueSort = "newest" | "oldest" | "bestScore" | "worstScore" | "strongestSignal" | "longest";
/** O id cresce com a criação: serve de "mais novo" e de desempate estável. */
const byNewest = (a: Clip, b: Clip) => b.id - a.id;
@@ -63,7 +54,7 @@ export const QUEUE_SORTS: { id: QueueSort; label: string; compare: (a: Clip, b:
/** A ordem escolhida fica lembrada neste navegador (conveniência; sem ela, volta para "Mais novos"). */
const SORT_STORAGE_KEY = "cenaforge.clipper.queueSort";
function useQueueSort() {
export function useQueueSort() {
const [sort, setSort] = useState<QueueSort>("newest");
useEffect(() => {
try {
@@ -78,20 +69,19 @@ function useQueueSort() {
return [sort, change] as const;
}
/** Duração mínima e máxima de um corte (limites do serviço; Shorts aceita até 180 s). */
const MIN_CLIP_S = 5;
const MAX_CLIP_S = 180;
/** Estado da publicação na aba Aprovados: relê a cada 15 s enquanto a aba está aberta. */
/* ---------- Publicação dos aprovados ---------- */
/** Estado da publicação na etapa Aprovados: relê a cada 15 s enquanto ela está aberta. */
const PUBLISH_POLL_MS = 15_000;
/**
* Jobs de publicação dos cortes (GET /api/publishing/jobs?sourceKind=clip), agrupados pelo id do corte.
* Só busca com a aba Aprovados aberta e a página visível. `null` = ainda não leu; `error` = rota fora.
* Só busca com a etapa Aprovados aberta e a página visível. `byClip` null = ainda não leu; `error` = rota fora.
*/
function useClipPublishing(active: boolean) {
export function useClipPublishing(active: boolean) {
const [byClip, setByClip] = useState<Map<string, PublishJob[]> | null>(null);
const [error, setError] = useState<string | null>(null);
// Muda para reler na hora (depois de "Publicar" num cartão), sem esperar os 15 s.
// Muda para reler na hora (depois de "Publicar"), sem esperar os 15 s.
const [version, setVersion] = useState(0);
const reload = useCallback(() => setVersion((v) => v + 1), []);
useEffect(() => {
@@ -113,60 +103,20 @@ function useClipPublishing(active: boolean) {
}, [active, version]);
return { byClip, error, reload };
}
/** Passos do ajuste: o início volta bastante (a ação costuma vir antes da reação); o fim estica um pouco. */
const START_STEPS = [-30, -10, -5, -2, 2] as const;
const END_STEPS = [-2, 2, 5, 10] as const;
export function ClipQueue({ clips, sessions, sessionFilter, onSessionFilter, nameOf, onChanged }: {
clips: Clip[];
sessions: ClipperSession[];
sessionFilter: number | null;
onSessionFilter: (id: number | null) => void;
/** Nome da fonte de um corte (vem das fontes cadastradas ou do link). */
nameOf: (clip: Clip) => string;
onChanged: () => void;
}) {
const [filter, setFilter] = useState<QueueFilter>("ready");
const scoped = sessionFilter === null ? clips : clips.filter((c) => c.sessionId === sessionFilter);
const current = QUEUE_FILTERS.find((f) => f.id === filter)!;
const [sort, setSort] = useQueueSort();
const compare = (QUEUE_SORTS.find((s) => s.id === sort) ?? QUEUE_SORTS[0]).compare;
const shown = scoped.filter((c) => current.statuses.includes(c.status)).sort(compare);
const sessionIds = [...new Set(clips.map((c) => c.sessionId))];
const publishing = useClipPublishing(filter === "approved");
/* ---------- Apagar ---------- */
// Seleção para apagar: vale só para o que está na aba (trocar de aba ou de sessão limpa).
const [selected, setSelected] = useState<ReadonlySet<number>>(() => new Set());
export type DeleteNotice = { ok: boolean; text: string; key: number };
/**
* Apagar cortes com o resultado num aviso: um corte vai pela rota própria; vários, pelo lote (de 500 em 500).
* `confirmMany` pergunta antes (modal com a contagem e o alcance) e apaga a seleção ou a aba inteira.
*/
export function useClipDeletion(onChanged: () => void) {
const [deleting, setDeleting] = useState<ReadonlySet<number>>(() => new Set());
const [notice, setNotice] = useState<DeleteNotice | null>(null);
// Modo de seleção: ligado pelo botão "Selecionar" (ou ao marcar a 1ª caixa). Esc sai e limpa.
const [selecting, setSelecting] = useState(false);
const selectable = shown.filter(canDelete);
const chosen = selectable.filter((c) => selected.has(c.id));
const working = deleting.size > 0;
const choosing = selecting || chosen.length > 0;
const exitSelecting = useCallback(() => { setSelecting(false); setSelected(new Set()); }, []);
const changeFilter = (id: QueueFilter) => { setFilter(id); exitSelecting(); };
const changeSession = (id: number | null) => { onSessionFilter(id); exitSelecting(); };
useEffect(() => {
if (!choosing) return;
const onKey = (e: KeyboardEvent) => {
// Esc de um modal, menu ou confirmação do cartão é deles (o modal nativo também dispara keydown aqui).
if (e.key !== "Escape" || e.defaultPrevented || document.querySelector("dialog[open]")) return;
exitSelecting();
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [choosing, exitSelecting]);
const toggle = useCallback((id: number, on: boolean) => setSelected((prev) => {
const next = new Set(prev);
if (on) next.add(id); else next.delete(id);
return next;
}), []);
/** Apaga e mostra o resultado no aviso. Um corte vai pela rota própria; vários, pelo lote (de 500 em 500). */
const remove = useCallback(async (targets: Clip[], confirmPublished: boolean): Promise<boolean> => {
const remove = useCallback(async (targets: Clip[], confirmPublished: boolean): Promise<{ ok: boolean; gone: Set<number> }> => {
const ids = targets.map((c) => c.id);
setDeleting((prev) => new Set([...prev, ...ids]));
const total: Pick<ClipDeleteResult, "deleted" | "failed"> = { deleted: [], failed: [] };
@@ -183,150 +133,49 @@ export function ClipQueue({ clips, sessions, sessionFilter, onSessionFilter, nam
}
setDeleting((prev) => new Set([...prev].filter((id) => !ids.includes(id))));
const gone = new Set(total.deleted.map((d) => d.id));
setSelected((prev) => new Set([...prev].filter((id) => !gone.has(id))));
const text = !error ? deleteSummary(total) : total.deleted.length ? `${deleteSummary(total)}. O resto falhou: ${error}` : error;
setNotice({ ok: !error && total.failed.length === 0, text, key: Date.now() });
// Recarrega no lugar (os dados de cima trocam; nada some da tela antes da resposta, a lista não pula).
if (total.deleted.length) onChanged();
return error === null;
return { ok: error === null, gone };
}, [onChanged]);
/** Seleção ou aba inteira: modal com a contagem e o alcance (filtro de sessão); o 2º clique apaga. */
const confirmMany = async (targets: Clip[], scope: "selected" | "tab") => {
/** Seleção ou aba inteira: modal com a contagem e o alcance; confirmado, apaga. Devolve os ids que sumiram. */
const confirmMany = useCallback(async (targets: Clip[], scope: "selected" | "tab", context: {
stageLabel: string; shownCount: number;
/** Frase do alcance do filtro ("Vale só para a sessão #11…"); null = sem filtro além da etapa. */
scopeNote: string | null;
}): Promise<Set<number>> => {
const n = targets.length;
if (n === 0) return;
if (n === 0) return new Set();
const what = n === 1 ? "1 corte" : `${n} cortes`;
const published = targets.filter((c) => c.status === "published").length;
const left = scope === "tab" ? shown.length - n : 0;
const left = scope === "tab" ? context.shownCount - n : 0;
const ok = await askConfirm({
tone: "danger",
title: scope === "tab"
? (n === 1 ? `Apagar o único corte de “${current.label}”?` : `Apagar todos os ${n} cortes de “${current.label}”?`)
? (n === 1 ? `Apagar o único corte de “${context.stageLabel}”?` : `Apagar todos os ${n} cortes de “${context.stageLabel}”?`)
: `Apagar ${what} selecionado${n === 1 ? "" : "s"}?`,
message: <>
<p>Some o vídeo, a capa, a miniatura e o projeto de edição de cada um. Não dá para desfazer, e a IA não recria esses momentos.</p>
{scope === "tab" && (
<p className="mt-2 font-medium text-fg">
{sessionFilter !== null
? `Vale só para a sessão #${sessionFilter} (o filtro da fila). Os cortes das outras sessões ficam.`
: "Vale para todas as sessões desta aba."}
</p>
)}
{scope === "tab" && <p className="mt-2 font-medium text-fg">{context.scopeNote ?? "Vale para todas as fontes e sessões desta etapa."}</p>}
{published > 0 && <p className="mt-2">Inclui {published === 1 ? "1 corte publicado" : `${published} cortes publicados`}: só a cópia local some.</p>}
{left > 0 && <p className="mt-2">{left === 1 ? "1 corte em andamento (IA ou render) fica" : `${left} cortes em andamento (IA ou render) ficam`}.</p>}
</>,
confirmLabel: `Apagar ${what}`,
});
if (ok) await remove(targets, published > 0);
};
if (!ok) return new Set();
return (await remove(targets, published > 0)).gone;
}, [remove]);
return (
<section aria-labelledby="fila-titulo" className="grid gap-5">
<h2 id="fila-titulo" className="sr-only">Fila de cortes</h2>
<div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
<div role="group" aria-label="Filtrar cortes por etapa"
className="flex flex-wrap gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{QUEUE_FILTERS.map((f) => {
const count = scoped.filter((c) => f.statuses.includes(c.status)).length;
const selected = f.id === filter;
return (
<button key={f.id} type="button" aria-pressed={selected} onClick={() => changeFilter(f.id)}
className={cx("flex items-center gap-2 rounded-[0.45rem] px-3 py-1.5 text-[0.8125rem] font-medium transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
selected ? "bg-overlay text-fg shadow-[0_1px_0_0_rgb(255_255_255/0.06)_inset,0_1px_3px_rgb(0_0_0/0.5)]" : "text-fg-muted hover:text-fg")}>
{f.label}
<span className={cx("grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[0.6875rem] font-semibold tabular-nums",
selected ? (f.id === "error" && count > 0 ? "bg-danger-soft text-danger" : "bg-accent-soft text-accent") : "bg-overlay text-fg-subtle")}>
{count}
</span>
</button>
);
})}
</div>
<div className="ml-auto flex min-w-0 flex-wrap items-center justify-end gap-x-3 gap-y-2">
{sessionIds.length > 1 || sessionFilter !== null ? (
<label className="flex min-w-0 items-center gap-2 text-[0.8125rem] text-fg-muted">
Sessão
<Select value={sessionFilter ?? ""} onChange={(e) => changeSession(e.target.value ? Number(e.target.value) : null)} className="h-9 w-auto min-w-48">
<option value="">Todas as sessões</option>
{sessions.filter((s) => sessionIds.includes(s.id) || s.id === sessionFilter).map((s) => (
<option key={s.id} value={s.id}>#{s.id} · {s.title || s.url.replace(/^https?:\/\/(www\.)?/, "")}</option>
))}
</Select>
</label>
) : null}
<label className="flex min-w-0 items-center gap-2 text-[0.8125rem] text-fg-muted">
Ordenar
<Select value={sort} onChange={(e) => setSort(e.target.value as QueueSort)} className="h-9 w-auto min-w-44">
{QUEUE_SORTS.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}
</Select>
</label>
{/* Sempre no lugar (mesmo vazio, desabilitado): ligar/desligar a seleção não mexe no layout. */}
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" aria-pressed={selecting} disabled={selectable.length === 0 || working}
onClick={() => (selecting ? exitSelecting() : setSelecting(true))} title="Escolher cortes para apagar (Esc sai)"
className={cx("text-fg-muted", selecting && "bg-raised text-fg")}>
<CheckIcon size={15} />{selecting ? "Selecionando" : "Selecionar"}
</Button>
<TabMenu count={selectable.length} disabled={selectable.length === 0 || working}
onDeleteAll={() => void confirmMany(selectable, "tab")} />
</div>
</div>
</div>
{filter === "approved" && (
<p className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs leading-relaxed text-fg-muted">
<PublishIcon size={14} className="text-fg-subtle" />
{publishing.error
? <span className="text-warning">Não deu para ler o estado da publicação agora ({publishing.error}).</span>
: <span>Use “Publicar” em cada corte para escolher o canal, as redes e quando sai. Se a fonte estiver ligada a um canal, os aprovados saem sozinhos nele. Cada cartão mostra como está em cada rede.</span>}
<TextLink href="/publishing">Abrir Publicações</TextLink>
</p>
)}
{shown.length === 0 ? (
<EmptyState compact icon={<ScissorsIcon size={18} />} title={`Nenhum corte em “${current.label}”`}>
{current.empty}
{sessionFilter !== null && <> Filtrando pela sessão #{sessionFilter}.</>}
</EmptyState>
) : (
<ul className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,40rem),1fr))] gap-5">
{shown.map((clip) => (
<li key={clip.id} className="min-w-0">
<ClipCard clip={clip} name={nameOf(clip)} onChanged={onChanged} revealed={choosing}
publishJobs={filter === "approved" && publishing.byClip ? publishing.byClip.get(String(clip.id)) ?? [] : null}
onPublished={publishing.reload}
selected={selected.has(clip.id)} onSelect={toggle} deleting={deleting.has(clip.id)}
onDelete={(c, confirmPublished) => remove([c], confirmPublished)} />
</li>
))}
</ul>
)}
{choosing && (
<SelectionPill chosen={chosen.length} total={selectable.length} working={working}
onSelectAll={(on) => setSelected(on ? new Set(selectable.map((c) => c.id)) : new Set())}
onDelete={() => void confirmMany(chosen, "selected")} onExit={exitSelecting} />
)}
{notice && <DeleteToast key={notice.key} notice={notice} raised={choosing} onClose={() => setNotice(null)} />}
</section>
);
return { deleting, notice, setNotice, remove, confirmMany };
}
/* ---------- Apagar: seleção, barra e aviso ---------- */
/** O serviço recusa apagar enquanto a IA avalia (`candidate`) ou o FFmpeg renderiza (`rendering`). */
function canDelete(clip: Clip): boolean {
return !UNDELETABLE_CLIP.includes(clip.status);
}
type DeleteNotice = { ok: boolean; text: string; key: number };
type DeleteClip = (clip: Clip, confirmPublished: boolean) => Promise<boolean>;
const PILL_BUTTON = "inline-flex h-7 items-center gap-1.5 rounded-full px-2.5 font-medium text-fg-muted transition-colors hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none";
/** Pílula da seleção: pequena, neutra, presa no canto de baixo à direita (deixa o canto extremo para o indicador
* do Next em desenvolvimento). Fica por cima da página sem ocupar espaço nela: nada se mexe ao aparecer. */
function SelectionPill({ chosen, total, working, onSelectAll, onDelete, onExit }: {
export function SelectionPill({ chosen, total, working, onSelectAll, onDelete, onExit }: {
chosen: number; total: number; working: boolean; onSelectAll: (on: boolean) => void; onDelete: () => void; onExit: () => void;
}) {
const all = total > 0 && chosen === total;
@@ -354,8 +203,8 @@ function SelectionPill({ chosen, total, working, onSelectAll, onDelete, onExit }
);
}
/** Menu "⋯" da aba: ações em massa que não precisam de seleção. Esc fecha e devolve o foco ao botão. */
function TabMenu({ count, disabled, onDeleteAll }: { count: number; disabled: boolean; onDeleteAll: () => void }) {
/** Menu "⋯" da etapa: ações em massa que não precisam de seleção. Esc fecha e devolve o foco ao botão. */
export function TabMenu({ count, disabled, onDeleteAll }: { count: number; disabled: boolean; onDeleteAll: () => void }) {
const [open, setOpen] = useState(false);
const wrapRef = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
@@ -372,8 +221,8 @@ function TabMenu({ count, disabled, onDeleteAll }: { count: number; disabled: bo
<div ref={wrapRef} className="relative"
onKeyDown={(e) => { if (e.key === "Escape" && open) { e.preventDefault(); e.stopPropagation(); close(); } }}
onBlur={(e) => { if (open && !wrapRef.current?.contains(e.relatedTarget as Node)) setOpen(false); }}>
<button ref={buttonRef} type="button" aria-haspopup="menu" aria-expanded={open} aria-label="Mais ações desta aba"
title="Mais ações desta aba" disabled={disabled} onClick={() => setOpen((v) => !v)}
<button ref={buttonRef} type="button" aria-haspopup="menu" aria-expanded={open} aria-label="Mais ações desta etapa"
title="Mais ações desta etapa" disabled={disabled} onClick={() => setOpen((v) => !v)}
className={cx("grid size-8 place-items-center rounded-control text-fg-muted transition-colors hover:bg-raised hover:text-fg",
"focus-visible:outline-2 focus-visible:outline-accent disabled:pointer-events-none disabled:opacity-45 motion-reduce:transition-none",
open && "bg-raised text-fg")}>
@@ -382,12 +231,12 @@ function TabMenu({ count, disabled, onDeleteAll }: { count: number; disabled: bo
</svg>
</button>
{open && (
<div role="menu" aria-label="Ações desta aba"
<div role="menu" aria-label="Ações desta etapa"
className="absolute top-full right-0 z-30 mt-1 min-w-60 rounded-control border border-line-strong bg-raised p-1 shadow-pop">
<button ref={itemRef} type="button" role="menuitem"
onClick={() => { close(); onDeleteAll(); }}
className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[0.8125rem] text-fg-muted hover:bg-danger-soft hover:text-danger focus-visible:bg-danger-soft focus-visible:text-danger focus-visible:outline-none">
<TrashIcon size={15} />Apagar todos desta aba ({count})
<TrashIcon size={15} />Apagar todos desta etapa ({count})
</button>
</div>
)}
@@ -395,9 +244,9 @@ function TabMenu({ count, disabled, onDeleteAll }: { count: number; disabled: bo
);
}
/** Resultado da exclusão num aviso fixo no canto (não muda a altura da página). Recebe o foco: o cartão apagado
/** Resultado da exclusão num aviso fixo no canto (não muda a altura da página). Recebe o foco: a linha apagada
* some e o teclado não fica perdido. Esc ou o X fecham. `raised`: sobe para não ficar em cima da pílula. */
function DeleteToast({ notice, raised, onClose }: { notice: DeleteNotice; raised: boolean; onClose: () => void }) {
export function DeleteToast({ notice, raised, onClose }: { notice: DeleteNotice; raised: boolean; onClose: () => void }) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => { ref.current?.focus({ preventScroll: true }); }, []);
return (
@@ -422,524 +271,32 @@ function DeleteToast({ notice, raised, onClose }: { notice: DeleteNotice; raised
);
}
/** "Apagar" com confirmação curta no próprio cartão: o 1º clique pergunta, o 2º apaga; Cancelar ou Esc desiste. */
function DeleteControl({ clip, deleting, disabled, onDelete }: { clip: Clip; deleting: boolean; disabled: boolean; onDelete: DeleteClip }) {
const [asking, setAsking] = useState(false);
const openRef = useRef<HTMLButtonElement>(null);
const cancelRef = useRef<HTMLButtonElement>(null);
const wasAsking = useRef(false);
useEffect(() => {
// Foco: ao perguntar vai para Cancelar (Enter de novo não apaga por engano); ao desistir volta para Apagar.
if (asking) cancelRef.current?.focus();
else if (wasAsking.current) openRef.current?.focus();
wasAsking.current = asking;
}, [asking]);
const published = clip.status === "published";
if (!asking) {
return (
<Button ref={openRef} variant="ghost" size="sm" disabled={disabled || deleting} onClick={() => setAsking(true)}
className="text-fg-muted hover:bg-danger-soft hover:text-danger" aria-label={`Apagar o corte ${clip.id}`}>
{deleting ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
);
}
/** Filtro de etapa em pílulas (segmented), com a contagem de cada uma. */
export function StageFilter({ value, counts, onChange }: { value: QueueFilter; counts: Record<QueueFilter, number>; onChange: (id: QueueFilter) => void }) {
return (
<div role="group" aria-label={`Confirmar: apagar o corte ${clip.id}`}
onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); setAsking(false); } }}
// Mesma altura do botão "Apagar" (h-8): perguntar não muda a altura do cartão.
className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-danger">{published ? "Publicado: apagar só a cópia local?" : "Apagar vídeo e edição?"}</span>
<Button variant="danger" size="sm" disabled={deleting}
onClick={async () => {
// Deu certo: o foco já foi para o aviso (o cartão vai sumir); não volta para cá.
if (await onDelete(clip, published)) wasAsking.current = false;
setAsking(false);
}}>
{deleting ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar
</Button>
<Button ref={cancelRef} variant="ghost" size="sm" disabled={deleting} onClick={() => setAsking(false)}>Cancelar</Button>
<div role="group" aria-label="Filtrar cortes por etapa"
className="flex flex-wrap gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{QUEUE_FILTERS.map((f) => {
const count = counts[f.id];
const selected = f.id === value;
return (
<button key={f.id} type="button" aria-pressed={selected} onClick={() => onChange(f.id)}
className={cx("flex items-center gap-2 rounded-[0.45rem] px-3 py-1.5 text-[0.8125rem] font-medium transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
selected ? "bg-overlay text-fg shadow-[0_1px_0_0_rgb(255_255_255/0.06)_inset,0_1px_3px_rgb(0_0_0/0.5)]" : "text-fg-muted hover:text-fg")}>
{f.label}
<span className={cx("grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[0.6875rem] font-semibold tabular-nums",
selected ? (f.id === "error" && count > 0 ? "bg-danger-soft text-danger" : "bg-accent-soft text-accent") : "bg-overlay text-fg-subtle")}>
{count}
</span>
</button>
);
})}
</div>
);
}
/* ---------- Cartão do corte ---------- */
function ClipCard({ clip, name, onChanged, revealed, selected, onSelect, deleting, onDelete, publishJobs = null, onPublished }: {
clip: Clip; name: string; onChanged: () => void;
/** Aba Aprovados: jobs de publicação deste corte (um por rede/canal); null = não mostrar. */
publishJobs?: PublishJob[] | null;
/** Depois de "Publicar": relê o estado da publicação. */
onPublished?: () => void;
/** Modo de seleção ligado: a caixa aparece em todos os cartões (senão, só no hover/foco do cartão). */
revealed: boolean;
selected: boolean; onSelect: (id: number, on: boolean) => void; deleting: boolean; onDelete: DeleteClip;
}) {
const { pending, message, setMessage, run } = useClipperAction(onChanged);
const base = `clips/${clip.id}`;
const status = CLIP_STATUS[clip.status];
// "Publicar" só aparece com o estado da publicação lido (aba Aprovados): o diálogo precisa saber o que cada rede já tem.
const publish = publishJobs ? {
jobs: publishJobs,
onDone: (m: { ok: boolean; text: string }) => { setMessage(m); onPublished?.(); },
} : null;
const busy = ACTIVE_CLIP.includes(clip.status);
// Rascunho de título e legenda: a consulta periódica não apaga o que está sendo digitado.
const [saved, setSaved] = useState({ title: clip.title, caption: clip.caption });
const [title, setTitle] = useState(clip.title);
const [caption, setCaption] = useState(clip.caption);
if (saved.title !== clip.title || saved.caption !== clip.caption) {
setSaved({ title: clip.title, caption: clip.caption });
if (title === saved.title) setTitle(clip.title);
if (caption === saved.caption) setCaption(clip.caption);
}
const textDirty = title !== clip.title || caption !== clip.caption;
// Versão do vídeo: muda quando um render termina (mesmo caminho de arquivo, conteúdo novo).
const [videoVersion, setVideoVersion] = useState(clip.updatedAt);
const [lastStatus, setLastStatus] = useState(clip.status);
if (lastStatus !== clip.status) {
setLastStatus(clip.status);
if (ACTIVE_CLIP.includes(lastStatus)) setVideoVersion(clip.updatedAt);
}
const editable = !busy && clip.status !== "published";
const horizontal = aspectOf(clip) === "horizontal";
// Horizontal: o vídeo 16:9 vai em cima, na largura do cartão (numa coluna de 13rem ficaria minúsculo).
return (
<article aria-label={clip.title || `Corte ${clip.id}`}
className={cx("group/card grid h-full gap-5 rounded-card border bg-surface p-4 shadow-card", !horizontal && "sm:grid-cols-[13rem_minmax(0,1fr)]",
selected ? "border-accent/70 ring-1 ring-accent/40" : clip.status === "ready" ? "border-accent/25" : "border-line",
deleting && "opacity-60")}>
<ClipMedia clip={clip} version={videoVersion} />
<div className="grid min-w-0 content-start gap-4">
<header className="grid gap-2">
<div className="flex flex-wrap items-center gap-2">
<Badge tone={status.tone} pulse={status.pulse}>{status.label}</Badge>
<Badge tone={clip.source === "manual" ? "info" : clip.source === "ai" ? "violet" : "neutral"} dot={false}>
{clip.source === "manual" ? <ScissorsIcon size={12} /> : clip.source === "chat" ? <ChatIcon size={12} /> : clip.source === "ai" ? <EyeIcon size={12} /> : null}
{SOURCE_LABEL[clip.source]}
</Badge>
{horizontal && <Badge tone="info" dot={false}>horizontal 16:9</Badge>}
<span className="ml-auto text-xs text-fg-subtle" title={new Date(clip.createdAt).toLocaleString("pt-BR")}>{formatRelative(clip.createdAt)}</span>
{/* Caixa de seleção: sempre ocupa o lugar (nada se mexe), mas só aparece no hover/foco do cartão, no modo
de seleção ou marcada. Pelo teclado ela recebe foco normalmente e aparece ao receber. */}
<input type="checkbox" checked={selected} disabled={!canDelete(clip) || deleting}
onChange={(e) => onSelect(clip.id, e.target.checked)}
aria-label={`Selecionar o corte ${clip.id}${clip.title ? `: ${clip.title}` : ""}`}
title={canDelete(clip) ? "Selecionar para apagar" : "A IA ou o render está trabalhando neste corte"}
className={cx("size-4 shrink-0 cursor-pointer accent-accent transition-opacity duration-150 motion-reduce:transition-none disabled:cursor-not-allowed",
!canDelete(clip)
? (revealed ? "opacity-40" : "opacity-0 group-hover/card:opacity-40")
: revealed || selected ? "opacity-100" : "opacity-0 group-hover/card:opacity-100 group-focus-within/card:opacity-100")} />
</div>
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-muted">
<span className="font-medium text-fg">{name}</span>
<span className="inline-flex items-center gap-1"><ClockIcon size={13} className="text-fg-subtle" />{formatDuration(clip.durationS)}</span>
<span className="text-fg-subtle">sessão #{clip.sessionId} · {formatClock(clip.startS)}–{formatClock(clip.endS)}</span>
</p>
</header>
{publishJobs && (
<section aria-label="Publicação nas redes" className="grid gap-1.5">
<h4 className="text-eyebrow font-semibold text-fg-subtle uppercase">Publicação</h4>
<PublishChips jobs={publishJobs} showAccount={new Set(publishJobs.map((j) => j.accountId)).size > 1}
emptyText={<>Ainda não foi para nenhuma rede. Use “Publicar” abaixo para escolher o canal e as redes.</>} />
</section>
)}
<JudgeVerdict clip={clip} />
<ChatSignals clip={clip} />
<FaceSignal clip={clip} />
{clip.status === "error" && clip.error && (
<p className="rounded-control border border-danger/30 bg-danger-soft px-3 py-2 font-mono text-xs break-words text-danger">{clip.error}</p>
)}
<form className="grid gap-3" onSubmit={(e) => {
e.preventDefault();
void run("text", () => clipperCall<Clip>(base, "PATCH", { title, caption }), "Título e legenda salvos.");
}}>
<label className="grid gap-1.5">
<span className="text-[0.8125rem] font-medium text-fg-muted">Título</span>
<Input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={100} disabled={!editable} className="h-9" />
</label>
<label className="grid gap-1.5">
<span className="text-[0.8125rem] font-medium text-fg-muted">Legenda do post</span>
<Textarea value={caption} onChange={(e) => setCaption(e.target.value)} rows={3} maxLength={2200} disabled={!editable} className="text-[0.8125rem]" />
</label>
{textDirty && (
<div className="flex flex-wrap items-center gap-2">
<Button type="submit" variant="secondary" size="sm" disabled={pending !== null}>
{pending === "text" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar texto
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => { setTitle(clip.title); setCaption(clip.caption); }}>Desfazer</Button>
</div>
)}
</form>
{editable && <TrimControl clip={clip} pending={pending} run={run} />}
{clip.transcript && (
<details className="group rounded-control border border-line bg-sunken/30 px-3 py-2 text-[0.8125rem]">
<summary className="cursor-pointer text-fg-muted select-none hover:text-fg">Transcrição</summary>
<p className="mt-2 leading-relaxed text-fg-muted">{clip.transcript}</p>
</details>
)}
<ClipActions clip={clip} pending={pending} run={run} deleting={deleting} onDelete={onDelete} publish={publish} />
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
</article>
);
}
type Run = ReturnType<typeof useClipperAction>["run"];
function ClipMedia({ clip, version }: { clip: Clip; version: string }) {
const busy = ACTIVE_CLIP.includes(clip.status);
const poster = clip.thumb ? fileUrl(clip.thumb) : undefined;
const frame = aspectOf(clip) === "horizontal" ? "aspect-video" : "aspect-9/16 max-sm:max-w-60";
if (clip.file && !busy) {
return (
<video key={version} controls preload="metadata" poster={poster} aria-label={`Vídeo do corte: ${clip.title || clip.id}`}
src={`${fileUrl(clip.file)}&v=${encodeURIComponent(version)}`}
className={cx(frame, "w-full self-start rounded-control border border-line bg-sunken object-contain")} />
);
}
return (
<div className={cx(frame, "relative grid w-full self-start overflow-hidden rounded-control border border-line bg-sunken")}>
{/* eslint-disable-next-line @next/next/no-img-element -- miniatura local servida por /api/files */}
{poster && <img src={poster} alt="" className="absolute inset-0 size-full object-cover opacity-35" />}
<div className="relative grid place-content-center justify-items-center gap-2 p-4 text-center text-xs text-fg-muted">
{busy ? <Spinner className="size-5 text-accent" /> : <ScissorsIcon size={22} className="text-fg-subtle" />}
<span>{busy ? CLIP_STATUS[clip.status].label : clip.status === "discarded" ? "Não renderizado: a IA descartou" : "Sem vídeo"}</span>
</div>
</div>
);
}
function JudgeVerdict({ clip }: { clip: Clip }) {
const judge = clip.judge;
if (!judge) {
return (
<>
<Proposal clip={clip} />
<p className="flex items-center gap-2 text-xs text-fg-subtle">
<SparkIcon size={14} className={clip.status === "candidate" ? "text-violet" : undefined} />
{clip.status === "candidate" ? "A IA está avaliando este momento…"
: clip.source === "manual" ? "Corte manual: não passa pela IA."
: "Sem veredito da IA (juiz desligado ou avaliado só pela heurística)."}
</p>
</>
);
}
if ("error" in judge) {
return (
<>
<Proposal clip={clip} />
<p className="flex items-start gap-2 rounded-control border border-warning/25 bg-warning-soft px-3 py-2 text-xs text-warning">
<AlertIcon size={14} className="mt-px" />
<span>A IA não conseguiu avaliar: <span className="break-words">{judge.error}</span></span>
</p>
</>
);
}
const tone = judge.keep ? (judge.score >= 7 ? "text-success" : "text-fg") : "text-warning";
const a = judge.analysis;
return (
<>
<Proposal clip={clip} />
{a && <AnalysisView analysis={a} model={judge.analystModel} />}
<div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-3.5 gap-y-1 rounded-control border border-violet/20 bg-violet-soft/40 px-3.5 py-2.5">
<div className="row-span-2 grid justify-items-center leading-none" aria-label={`Nota da IA: ${formatScore(judge.score)} de 10`}>
<span className={cx("font-display text-2xl font-semibold tabular-nums", tone)}>{formatScore(judge.score)}</span>
<span className="mt-1 text-[0.6875rem] text-fg-subtle">de 10</span>
</div>
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="inline-flex items-center gap-1.5 font-semibold text-violet"><SparkIcon size={13} />{a ? "Editor" : "Juiz"}</span>
<Badge tone={judge.keep ? "success" : "warning"} dot={false}>{judge.keep ? "manteve" : "descartou"}</Badge>
<span className="font-mono text-[0.6875rem] text-fg-subtle">{judge.model}</span>
</p>
{judge.reason && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{judge.reason}</p>}
</div>
</>
);
}
/** Corte da varredura (source "ai"): a proposta que a IA fez ao assistir a janela, antes dos juízes. */
function Proposal({ clip }: { clip: Clip }) {
const r = clip.reasons ?? {};
if (clip.source !== "ai" || !(r.proposalTitle || r.proposalReason)) return null;
return (
<div className="grid gap-1 rounded-control border border-info/20 bg-info-soft/40 px-3.5 py-2.5 text-xs">
<p className="flex flex-wrap items-center gap-2">
<span className="inline-flex items-center gap-1.5 font-semibold text-info"><EyeIcon size={13} />Varredura viu na tela</span>
{r.proposalScore !== undefined && <Badge tone="info" dot={false}>proposta {formatScore(r.proposalScore)}/10</Badge>}
{r.scanFromS !== undefined && r.scanToS !== undefined && <span className="text-fg-subtle">janela {formatClock(r.scanFromS)}–{formatClock(r.scanToS)}</span>}
</p>
{r.proposalTitle && <p className="font-medium text-fg">{r.proposalTitle}</p>}
{r.proposalReason && <p className="leading-relaxed text-fg-muted">{r.proposalReason}</p>}
</div>
);
}
/** O que o ANALISTA (1º juiz) entendeu: situação, o que aconteceu, confiança; tela/fala/chat expansíveis. */
function AnalysisView({ analysis: a, model }: { analysis: ClipAnalysis; model?: string }) {
const confidence = Math.round(Math.min(1, Math.max(0, a.confidence ?? 0)) * 100);
const details = [
{ label: "Tela", text: a.screen }, { label: "Fala", text: a.speech }, { label: "Chat", text: a.chat_meaning }, { label: "Gancho", text: a.hook },
].filter((d) => d.text);
return (
<div className="grid gap-2 rounded-control border border-line bg-sunken/40 px-3.5 py-2.5">
<p className="flex flex-wrap items-center gap-2 text-xs">
<span className="font-semibold text-fg">O que aconteceu</span>
<Badge tone="accent" dot={false}>{SITUATION_LABEL[a.situation as Situation] ?? a.situation}</Badge>
<span className={cx("tabular-nums", confidence >= 70 ? "text-success" : confidence >= 40 ? "text-fg-muted" : "text-warning")}>
confiança {confidence}%
</span>
{model && <span className="font-mono text-[0.6875rem] text-fg-subtle">analista {model}</span>}
</p>
{a.what_happened && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{a.what_happened}</p>}
{details.length > 0 && (
<details className="text-xs">
<summary className="cursor-pointer text-fg-subtle select-none hover:text-fg">Tela, fala e chat</summary>
<dl className="mt-2 grid gap-1.5">
{details.map((d) => (
<div key={d.label} className="grid grid-cols-[4.5rem_minmax(0,1fr)] gap-2">
<dt className="font-semibold text-fg-subtle">{d.label}</dt>
<dd className="leading-relaxed text-fg-muted">{d.text}</dd>
</div>
))}
</dl>
</details>
)}
</div>
);
}
function ChatSignals({ clip }: { clip: Clip }) {
const { peakRatio, messages, tags, topMessages, emotes } = clip.reasons ?? {};
const tagEntries = Object.entries(tags ?? {}).filter(([, n]) => (n ?? 0) > 0) as [keyof ClipTags, number][];
const emoteEntries = Object.entries(emotes ?? {}).filter(([, n]) => n > 0).sort((x, y) => y[1] - x[1]);
if (peakRatio === undefined && messages === undefined && tagEntries.length === 0 && emoteEntries.length === 0 && !topMessages?.length) return null;
return (
<div className="grid gap-2">
<div className="flex flex-wrap items-center gap-1.5 text-xs">
{peakRatio !== undefined && <Chip strong>pico {formatScore(peakRatio)}× o normal</Chip>}
{messages !== undefined && <Chip>{messages} mensage{messages === 1 ? "m" : "ns"}</Chip>}
{tagEntries.map(([tag, n]) => <Chip key={tag} accent>{TAG_LABEL[tag] ?? tag} ×{n}</Chip>)}
</div>
{emoteEntries.length > 0 && (
<ul aria-label="Emotes do chat no pico" className="flex flex-wrap gap-1.5 text-xs">
{emoteEntries.slice(0, 8).map(([name, n]) => (
<li key={name} className="inline-flex h-6 items-center gap-1 rounded-full border border-option-b/25 bg-option-b-soft px-2.5 font-mono text-option-b">
{name}<span className="text-option-b/70">×{n}</span>
</li>
))}
</ul>
)}
{topMessages && topMessages.length > 0 && (
<ul aria-label="Mensagens do chat no pico" className="flex flex-wrap gap-1.5">
{topMessages.slice(0, 6).map((m, i) => (
<li key={i} title={m}
className="max-w-56 truncate rounded-lg border border-line bg-sunken/50 px-2 py-1 text-[0.75rem] text-fg-muted">
{m}
</li>
))}
</ul>
)}
</div>
);
}
/** Reação no rosto do streamer (rastreio local): rótulo, intensidade relativa ao normal dele e quando aconteceu. */
function FaceSignal({ clip }: { clip: Clip }) {
const face = clip.reasons?.face;
if (!face || face.label === "neutro") return null;
const support = clip.reasons?.support;
return (
<p className="flex flex-wrap items-center gap-1.5 text-xs" aria-label="Reação no rosto do streamer">
<Chip accent>rosto: {FACE_LABEL[face.label] ?? face.label}{face.strong ? " forte" : ""}</Chip>
<span title="Quantos desvios acima do rosto normal deste streamer (3 = começa a contar; 6 ou mais = forte)">
<Chip>intensidade {formatScore(face.intensity)}</Chip>
</span>
<span className="text-fg-subtle" title={`começou em ${formatClock(face.onsetS)}`}>pico em {formatClock(face.peakS)}</span>
{clip.source === "face" && support && (
<span className="text-fg-subtle">com apoio {support.chatReactions >= 2 ? `do chat (${support.chatReactions} reações)` : "do áudio"}</span>
)}
</p>
);
}
function Chip({ children, strong = false, accent = false }: { children: ReactNode; strong?: boolean; accent?: boolean }) {
return (
<span className={cx("inline-flex h-6 items-center rounded-full border px-2.5 font-medium whitespace-nowrap",
accent ? "border-accent/25 bg-accent-soft text-accent" : strong ? "border-line-strong bg-raised text-fg" : "border-line bg-raised/60 text-fg-muted")}>
{children}
</span>
);
}
/** Ajuste fino de início/fim (±2 s). Aplicar reenfileira o render. */
function TrimControl({ clip, pending, run }: { clip: Clip; pending: string | null; run: Run }) {
const [trim, setTrim] = useState<{ start: number; end: number } | null>(null);
const start = trim?.start ?? clip.startS;
const end = trim?.end ?? clip.endS;
const dirty = trim !== null && (trim.start !== clip.startS || trim.end !== clip.endS);
const length = end - start;
const valid = length >= MIN_CLIP_S && length <= MAX_CLIP_S;
const nudge = (step: number, edge: "start" | "end") => {
const next = edge === "start" ? { start: Math.max(0, start + step), end } : { start, end: end + step };
const span = next.end - next.start;
const ok = span >= MIN_CLIP_S && span <= MAX_CLIP_S && !(edge === "start" && step < 0 && start <= 0);
const word = step < 0 ? "antes" : "depois";
return (
<button key={`${edge}${step}`} type="button" disabled={!ok || pending !== null} onClick={() => setTrim(next)}
aria-label={`${edge === "start" ? "Começar" : "Terminar"} ${Math.abs(step)} segundos ${word}`}
className={cx("h-7 rounded-md px-1.5 font-mono text-xs transition-colors hover:bg-overlay hover:text-fg focus-visible:outline-2 focus-visible:outline-accent disabled:opacity-40",
Math.abs(step) >= 10 ? "text-accent" : "text-fg-muted")}>
{step > 0 ? "+" : "−"}{Math.abs(step)} s
</button>
);
};
const delta = (now: number, was: number) => {
const d = Math.round(now - was);
return d === 0 ? null : <span className="text-accent"> ({d > 0 ? "+" : "−"}{Math.abs(d)} s)</span>;
};
return (
<fieldset className="grid gap-2">
<legend className="mb-1.5 text-[0.8125rem] font-medium text-fg-muted">Ajuste do trecho</legend>
<div className="flex flex-wrap items-center gap-2">
<span className="inline-flex flex-wrap items-center gap-0.5 rounded-control border border-line-strong bg-sunken/60 p-0.5">
{START_STEPS.filter((st) => st < 0).map((st) => nudge(st, "start"))}
<span className="px-1.5 text-xs text-fg-subtle">início <span className="font-mono text-fg tabular-nums">{formatClock(start)}</span>{delta(start, clip.startS)}</span>
{START_STEPS.filter((st) => st > 0).map((st) => nudge(st, "start"))}
</span>
<span className="inline-flex flex-wrap items-center gap-0.5 rounded-control border border-line-strong bg-sunken/60 p-0.5">
{END_STEPS.filter((st) => st < 0).map((st) => nudge(st, "end"))}
<span className="px-1.5 text-xs text-fg-subtle">fim <span className="font-mono text-fg tabular-nums">{formatClock(end)}</span>{delta(end, clip.endS)}</span>
{END_STEPS.filter((st) => st > 0).map((st) => nudge(st, "end"))}
</span>
<span className={cx("text-xs tabular-nums", !valid ? "text-danger" : dirty ? "text-accent" : "text-fg-subtle")}>{formatDuration(length)}</span>
</div>
{dirty && (
<div className="flex flex-wrap items-center gap-2">
<Button type="button" size="sm" variant="secondary" disabled={pending !== null || !valid}
onClick={async () => {
const done = await run("trim", () => clipperCall<Clip>(`clips/${clip.id}`, "PATCH", { startS: start, endS: end }),
"Novo trecho salvo. O corte voltou para a fila de render.");
if (done) setTrim(null);
}}>
{pending === "trim" ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Aplicar e re-renderizar
</Button>
<Button type="button" variant="ghost" size="sm" onClick={() => setTrim(null)}>Desfazer</Button>
<span className="text-xs text-fg-subtle">Entre {MIN_CLIP_S} e {MAX_CLIP_S} s. A gravação inteira fica guardada por cerca de 6 h.</span>
</div>
)}
</fieldset>
);
}
function ClipActions({ clip, pending, run, deleting, onDelete, publish }: {
clip: Clip; pending: string | null; run: Run; deleting: boolean; onDelete: DeleteClip;
/** Aprovados/publicados: botão "Publicar" (null enquanto o estado da publicação não foi lido). */
publish: { jobs: PublishJob[]; onDone: (m: { ok: boolean; text: string }) => void } | null;
}) {
const base = `clips/${clip.id}`;
const icon = (key: string, fallback: ReactNode) => (pending === key ? <Spinner className="size-3.5" /> : fallback);
const setStatus = (key: string, status: "approved" | "rejected" | "ready", text: string) =>
run(key, () => clipperCall<Clip>(base, "PATCH", { status }), text);
const render = (text: string) => run("render", () => clipperCall<Clip>(`${base}/render`, "POST"), text);
const rejudge = () => run("rejudge", () => clipperCall<Clip>(`${base}/rejudge`, "POST"), "Mandado de novo para a IA.");
const disabled = pending !== null;
const rejudgeButton = clip.source !== "manual" && (
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void rejudge()}>
{icon("rejudge", <SparkIcon size={15} />)}Mandar de novo para a IA
</Button>
);
let buttons: ReactNode = null;
switch (clip.status) {
case "ready":
buttons = <>
<Button size="sm" disabled={disabled} onClick={() => void setStatus("approve", "approved", "Corte aprovado.")}>
{icon("approve", <CheckIcon size={15} />)}Aprovar
</Button>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("reject", "rejected", "Corte rejeitado.")}>
{icon("reject", <XIcon size={15} />)}Rejeitar
</Button>
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void render("Re-render pedido. O corte voltou para a fila.")}>
{icon("render", <RefreshIcon size={15} />)}Re-renderizar
</Button>
{rejudgeButton}
</>;
break;
case "approved":
buttons = <>
{publish && <ClipPublishButton clip={clip} jobs={publish.jobs} onDone={publish.onDone} />}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Aprovação desfeita.")}>
{icon("undo", <UndoIcon size={15} />)}Desfazer aprovação
</Button>
</>;
break;
case "published":
// Publicado: dá para mandar para outra rede ou outro canal; editar não (o vídeo já está no ar).
return (
<div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">
{publish && <ClipPublishButton clip={clip} jobs={publish.jobs} onDone={publish.onDone} variant="secondary" />}
<span className="ml-auto" />
<DeleteControl clip={clip} deleting={deleting} disabled={disabled} onDelete={onDelete} />
</div>
);
case "rejected":
buttons = <>
{clip.file && <Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("undo", "ready", "Corte de volta para aprovar.")}>
{icon("undo", <UndoIcon size={15} />)}Voltar para aprovar
</Button>}
<Button variant="ghost" size="sm" disabled={disabled} onClick={() => void render("Re-render pedido.")}>
{icon("render", <RefreshIcon size={15} />)}Re-renderizar
</Button>
</>;
break;
case "discarded":
buttons = <>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Render forçado: o corte entrou na fila.")}>
{icon("render", <ScissorsIcon size={15} />)}Forçar render
</Button>
{rejudgeButton}
</>;
break;
case "error":
buttons = <>
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void render("Tentando de novo: o corte entrou na fila.")}>
{icon("render", <RefreshIcon size={15} />)}Tentar render de novo
</Button>
{rejudgeButton}
</>;
break;
default:
// Na fila: só o pendente pode sair (a IA ou o render ainda não pegou); avaliando/renderizando, nada.
if (!canDelete(clip)) return null;
return (
<div className="flex flex-wrap items-center justify-end gap-2 border-t border-line pt-4">
<DeleteControl clip={clip} deleting={deleting} disabled={disabled} onDelete={onDelete} />
</div>
);
}
return (
<div className="flex flex-wrap items-center gap-2 border-t border-line pt-4">
{buttons}
{/* Editor em tela cheia: abre o projeto que a IA montou (ou o seu) para ajustar e exportar de novo. */}
<LinkButton href={`/clipper/edit/${clip.id}`} variant="secondary" size="sm" className="ml-auto">
<ScissorsIcon size={15} />{clip.edit?.origin === "user" ? "Continuar edição" : "Editar"}
</LinkButton>
<DeleteControl clip={clip} deleting={deleting} disabled={disabled} onDelete={onDelete} />
</div>
);
/** Rótulo compacto de um select da barra de filtros ("Fonte", "Sessão"…). */
export function FilterLabel({ children, control }: { children: ReactNode; control: ReactNode }) {
return <label className="flex min-w-0 items-center gap-2 text-[0.8125rem] text-fg-muted">{children}{control}</label>;
}
@@ -0,0 +1,523 @@
"use client";
// Detalhe de uma sessão do Clipador (/clipper/sessions/[id]): quem/estado/tempo e as ações; saúde em uma frase;
// o que está acontecendo (resumo da IA + jogo); os quatro blocos do pipeline (chat, transcrição, IA, cortes); os
// cortes da sessão por estado; o gráfico do chat; emotes; configuração do corte e câmera.
// Os dados vêm do ClipperProvider (consulta a cada 5 s): os blocos têm altura fixa para nada pular.
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState, type ReactNode } from "react";
import { askConfirm } from "./confirm-dialog";
import {
ACTIVE_SESSION, CLIP_STATUS, CLIP_STATUS_ORDER, PLATFORM_LABEL, captureLabel, channelKeyOf, chatStatusInfo, clipperCall, formatClock,
formatDuration, gameIdOf, gbPerHourLabel, languageLabel, useClipperAction,
type Clip, type ClipStatus, type ClipperSession, type Game, type Timeline,
} from "./clipper-client";
import { CutSettingsDialog, type CutScope } from "./clipper-cut-settings";
import { ChannelEmotes, SessionGame } from "./clipper-games";
import { useClipper, useClipperData } from "./clipper-provider";
import {
ClockLabel, ClockText, CutNow, Dot, PlatformIcon, SCAN_LATE_S, SCAN_WINDOW_S, STATUS_FRAME, StatusBadge, TONE_FILL, TONE_TEXT,
TRANSCRIPT_LATE_SEGMENTS, sessionHealth, useClockShown, useRecordingClock, useScanInterval, type RecordingClock,
} from "./clipper-sessions";
import { stopSession } from "./clipper-shell";
import {
AlertIcon, BroadcastIcon, ChatIcon, CheckIcon, EyeIcon, GlobeIcon, MicIcon, ScissorsIcon, SettingsIcon, SparkIcon, StopIcon, TrashIcon,
} from "./icons";
import {
Badge, Breadcrumb, Button, Card, EmptyState, Feedback, LinkButton, ProgressBar, Spinner, cx, formatDate, formatInteger, type Tone,
} from "./ui";
export function SessionDetailPage({ id }: { id: number }) {
const { sessions, clips } = useClipperData();
const { nameOfSession, reload, games, setGames } = useClipper();
const router = useRouter();
const session = sessions.find((s) => s.id === id);
const [cutScope, setCutScope] = useState<CutScope | null>(null);
if (!session) {
return (
<div className="grid gap-6">
<Breadcrumb items={[{ href: "/clipper", label: "Clipador" }, { href: "/clipper/sessions", label: "Sessões" }, { label: `Sessão #${id}` }]} />
<EmptyState icon={<BroadcastIcon />} title="Sessão não encontrada" action={<LinkButton href="/clipper/sessions">Ver todas as sessões</LinkButton>}>
Ela pode ter sido apagada, ou ser mais antiga do que as 50 sessões que a lista carrega.
</EmptyState>
</div>
);
}
const name = nameOfSession(session);
return (
<div className="grid gap-6">
<Breadcrumb items={[{ href: "/clipper", label: "Clipador" }, { href: "/clipper/sessions", label: "Sessões" }, { label: `#${session.id} ${name}` }]} />
<SessionDetail session={session} name={name} clips={clips.filter((c) => c.sessionId === session.id)} games={games ?? []}
onChanged={reload} onGamesChanged={setGames}
onConfigure={() => setCutScope({ kind: "session", session, name })}
onDeleted={() => router.push("/clipper/sessions")} />
<CutSettingsDialog scope={cutScope} onClose={() => setCutScope(null)} onSaved={reload} />
</div>
);
}
function SessionDetail({ session: s, name, clips, games, onChanged, onGamesChanged, onConfigure, onDeleted }: {
session: ClipperSession; name: string; clips: Clip[]; games: Game[];
onChanged: () => void; onGamesChanged: (games: Game[]) => void; onConfigure: () => void; onDeleted: () => void;
}) {
const { pending, message, run } = useClipperAction(onChanged);
const scanIntervalS = useScanInterval();
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;
const clock = useRecordingClock(s.durationS, s.status === "recording");
return (
<div className="grid gap-5">
{/* 1. Quem, estado, tempo e ações */}
<header className={cx("grid gap-4 rounded-card border bg-surface px-5 py-4 shadow-card [contain:inline-size]", frame.border)}>
<div className="flex flex-wrap items-start gap-x-5 gap-y-3">
<span className={cx("grid size-12 shrink-0 place-items-center rounded-control border", frame.icon)}>
<PlatformIcon platform={s.platform} size={22} />
</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.375rem] leading-tight font-semibold text-fg">{name}</span>
<StatusBadge status={s.status} clock={clock} />
<Badge dot={false}>{s.kind === "vod" ? "VOD" : "live"}</Badge>
{s.language && <Badge dot={false} tone="info"><GlobeIcon size={12} />{languageLabel(s.language)}</Badge>}
</p>
<p className="flex flex-wrap items-center gap-x-2 text-xs text-fg-subtle">
<span>sessão #{s.id}</span><Dot /><span>{PLATFORM_LABEL[s.platform]}</span><Dot />
<span>início {formatDate(s.startedAt)}</span><Dot />
{s.endedAt && <><span>fim {formatDate(s.endedAt)}</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.875rem] 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-3xl leading-none font-semibold text-fg tabular-nums"><ClockText clock={clock} /></span>
<ClockLabel clock={clock} live={live} />
</div>
</div>
<div className="flex flex-wrap items-center gap-2 border-t border-line pt-3">
{live && s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
{active && (
<Button variant="secondary" size="sm" disabled={pending !== null} onClick={() => void stopSession(s, name, run)}>
{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; processar encerra e
deixa a IA analisar o que foi gravado. Live em "processando" (live ainda no ar) também pode voltar a gravar. */}
{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="ml-auto 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;
const done = await run("delete", () => clipperCall(`sessions/${s.id}`, "DELETE"), "Sessão apagada.");
if (done !== null) onDeleted();
}}>
{pending === "delete" ? <Spinner className="size-3.5" /> : <TrashIcon size={15} />}Apagar sessão
</Button>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</header>
{/* 2. Saúde em uma frase */}
<p title={health.full}
className={cx("flex min-h-10 items-center gap-2 rounded-control border px-3.5 text-[0.875rem] 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">{health.text}</span>
</p>
{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>}
{/* 3. O que está acontecendo: resumo da IA + jogo */}
{showNow && (
<section aria-label="O que está acontecendo" className="grid rounded-card border border-line bg-surface shadow-card">
{lastMemory?.summary && (
<div className="flex items-start gap-2.5 px-5 py-3.5">
<SparkIcon size={15} className="mt-0.5 shrink-0 text-violet" />
<p className="line-clamp-3 min-h-[2lh] min-w-0 flex-1 text-[0.875rem] 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-5 py-2.5", 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 */}
<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>
{/* 5. Cortes por estado (a lista em si fica em /clipper?session=ID) */}
<Card title="Cortes desta sessão"
description={totalClips === 0 ? (active ? "A IA ainda não achou um momento que renda corte." : "Nenhum corte nesta sessão.") : undefined}
actions={totalClips > 0 && <LinkButton href={`/clipper?session=${s.id}`} size="sm" variant="secondary"><ScissorsIcon size={15} />Ver na lista de cortes</LinkButton>}>
{totalClips > 0 && (
<ul className="flex flex-wrap gap-2" aria-label="Cortes por estado">
{CLIP_STATUS_ORDER.filter((k) => (s.clips[k] ?? 0) > 0).map((k) => (
<li key={k}>
<Link href={`/clipper?session=${s.id}&stage=${stageOf(k)}`}
className="inline-flex h-8 items-center gap-2 rounded-full border border-line bg-raised/60 px-3 text-[0.8125rem] transition-colors hover:border-accent/40 hover:bg-raised focus-visible:outline-2 focus-visible:outline-accent">
<span aria-hidden="true" className={cx("size-2 rounded-full", TONE_FILL[CLIP_STATUS[k].tone])} />
<span className="font-semibold text-fg tabular-nums">{s.clips[k]}</span>
<span className="text-fg-muted">{CLIP_STATUS[k].label}</span>
</Link>
</li>
))}
</ul>
)}
</Card>
{/* 6. Gráfico do chat */}
<Card title="Chat ao longo da live" description="Mensagens por segundo; as faixas são os trechos dos cortes e as linhas, o pico usado em cada um.">
<SessionTimeline session={s} clips={clips} />
</Card>
{/* 7. Emotes (serviço novo) */}
{s.game !== undefined && (
<Card title="Emotes da fonte" description="Peso aprendido por emote: sobe nos cortes que você aprova, desce nos rejeitados.">
<ChannelEmotes channelKey={channelKeyOf(s)} title={<span className="sr-only">Emotes da fonte</span>} />
</Card>
)}
{/* 8. Configuração do corte e câmera */}
<Card title="Configuração do corte" description="Layout, câmera, legenda, gancho e duração desta sessão (sobrescreve o padrão da fonte campo a campo).">
<div className="flex flex-wrap items-center gap-3">
<Button variant="secondary" size="sm" onClick={onConfigure}>
<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} />
</div>
</Card>
</div>
);
}
/** Aba da lista de cortes (`?stage=`) onde um estado aparece (mesma tabela de QUEUE_FILTERS da lista). */
function stageOf(status: ClipStatus): string {
switch (status) {
case "ready": return "ready";
case "candidate": case "pending": case "rendering": return "queue";
case "approved": case "published": return "approved";
case "discarded": return "discarded";
case "rejected": return "rejected";
default: return "error";
}
}
/* ---------- Cadência do resumo ---------- */
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, href }: {
icon: ReactNode; label: string; state: { tone: Tone; text: string; pulse?: boolean };
value: ReactNode; unit?: ReactNode; meter?: ReactNode; detail: ReactNode; detailTone?: Tone;
/** Com link, o bloco inteiro é clicável (ex.: cortes → lista de cortes da sessão). */
href?: string;
}) {
// <dt>/<dd> precisam ficar direto dentro do <dl>/<div>: com link, um <a> invisível cobre o bloco (padrão de cartão-link).
const className = "relative grid min-w-0 content-start gap-2.5 rounded-control border border-line bg-raised/40 px-4 py-3";
const body = (<>
<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>
</>);
if (href) {
return (
<div className={cx(className, "transition-colors hover:border-accent/40 hover:bg-raised has-[a:focus-visible]:outline-2 has-[a:focus-visible]:outline-accent")}>
{body}
<Link href={href} aria-label={`${label}: ver os cortes desta sessão`} className="absolute inset-0 rounded-control focus-visible:outline-none" />
</div>
);
}
return <div className={className}>{body}</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} href={`/clipper?session=${s.id}`}
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>
);
}
@@ -0,0 +1,229 @@
"use client";
// Lista de sessões do Clipador (/clipper/sessions): uma linha por sessão (fonte, estado, duração, início, jogo,
// cortes, saúde em uma frase) com as ações da etapa; filtros por estado e por fonte; "Gravar pelo link" num diálogo.
// Clique na linha abre o detalhe (/clipper/sessions/[id]). Os dados vêm do ClipperProvider (consulta a cada 5 s).
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, type MouseEvent } from "react";
import {
ACTIVE_SESSION, CLIP_STATUS_ORDER, clipperCall, gameIdOf, languageLabel, languageShort, useClipperAction,
type ClipperSession, type SessionStatus,
} from "./clipper-client";
import { useClipper, useClipperData } from "./clipper-provider";
import { ClockText, CutNow, PlatformIcon, RecordForm, StatusBadge, TONE_TEXT, sessionHealth, useRecordingClock } from "./clipper-sessions";
import { stopSession } from "./clipper-shell";
import { Dialog } from "./dialog";
import { askConfirm } from "./confirm-dialog";
import { ArrowRightIcon, BroadcastIcon, SparkIcon, StopIcon, TrashIcon } from "./icons";
import { Badge, Button, EmptyState, Feedback, LinkButton, Select, Spinner, Table, THead, Td, Th, cx, formatDate, formatInteger } from "./ui";
type StateFilter = "all" | "live" | "processing" | "done" | "problem";
const STATE_FILTERS: { id: StateFilter; label: string; statuses: SessionStatus[] | null }[] = [
{ id: "all", label: "Todas", statuses: null },
{ id: "live", label: "Ao vivo", statuses: ["recording", "starting"] },
{ id: "processing", label: "Processando", statuses: ["processing"] },
{ id: "done", label: "Concluídas", statuses: ["done"] },
{ id: "problem", label: "Com problema", statuses: ["error", "interrupted", "stopped"] },
];
export function SessionsPage() {
const { sessions } = useClipperData();
const { nameOfSession, reload } = useClipper();
const [state, setState] = useState<StateFilter>("all");
const [source, setSource] = useState<string>("");
const [recording, setRecording] = useState(false);
const current = STATE_FILTERS.find((f) => f.id === state)!;
// Fontes que aparecem no filtro: as cadastradas + o que dá para tirar do link das sessões sem fonte (chave = nome).
const sourceNames = [...new Set(sessions.map(nameOfSession))].sort((a, b) => a.localeCompare(b, "pt-BR"));
const shown = sessions
.filter((s) => current.statuses === null || current.statuses.includes(s.status))
.filter((s) => !source || nameOfSession(s) === source);
const live = sessions.filter((s) => s.status === "recording" || s.status === "starting").length;
return (
<section aria-labelledby="sessoes-titulo" className="grid gap-5">
<div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">
<div className="grid gap-1">
<h2 id="sessoes-titulo" className="text-title text-fg">Sessões</h2>
<p className="text-sm text-fg-muted">
Cada live gravada ou VOD processado, da mais nova para a mais antiga.
{sessions.length > 0 && <span className="text-fg-subtle"> {formatInteger(sessions.length)} sess{sessions.length === 1 ? "ão" : "ões"}{live > 0 ? ` · ${live} gravando` : ""}.</span>}
</p>
</div>
<Button onClick={() => setRecording(true)}><BroadcastIcon size={16} />Gravar pelo link</Button>
</div>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<div role="group" aria-label="Filtrar sessões por estado" className="flex flex-wrap gap-1 rounded-control border border-line-strong bg-sunken/60 p-1">
{STATE_FILTERS.map((f) => {
const count = f.statuses === null ? sessions.length : sessions.filter((s) => f.statuses!.includes(s.status)).length;
const selected = f.id === state;
return (
<button key={f.id} type="button" aria-pressed={selected} onClick={() => setState(f.id)}
className={cx("flex items-center gap-2 rounded-[0.45rem] px-3 py-1.5 text-[0.8125rem] font-medium transition-colors",
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
selected ? "bg-overlay text-fg shadow-[0_1px_0_0_rgb(255_255_255/0.06)_inset,0_1px_3px_rgb(0_0_0/0.5)]" : "text-fg-muted hover:text-fg")}>
{f.label}
<span className={cx("grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[0.6875rem] font-semibold tabular-nums",
selected ? (f.id === "live" && count > 0 ? "bg-danger-soft text-danger" : "bg-accent-soft text-accent") : "bg-overlay text-fg-subtle")}>
{count}
</span>
</button>
);
})}
</div>
{sourceNames.length > 1 && (
<label className="ml-auto flex min-w-0 items-center gap-2 text-[0.8125rem] text-fg-muted">
Fonte
<Select value={source} onChange={(e) => setSource(e.target.value)} className="h-9 w-auto min-w-44">
<option value="">Todas as fontes</option>
{sourceNames.map((n) => <option key={n} value={n}>{n}</option>)}
</Select>
</label>
)}
</div>
{sessions.length === 0 ? (
<EmptyState compact icon={<BroadcastIcon size={18} />} title="Nenhuma sessão ainda"
action={<div className="flex flex-wrap justify-center gap-2">
<Button size="sm" onClick={() => setRecording(true)}><BroadcastIcon size={15} />Gravar pelo link</Button>
<LinkButton size="sm" variant="secondary" href="/clipper/sources">Cadastrar uma fonte</LinkButton>
</div>}>
Cole o link de uma live, ou ligue o monitor de uma fonte para gravar sozinho quando ela entrar ao vivo.
</EmptyState>
) : shown.length === 0 ? (
<EmptyState compact icon={<BroadcastIcon size={18} />} title={`Nenhuma sessão em “${current.label}”`}>
{source ? <>Filtrando pela fonte {source}.</> : "Troque o filtro acima para ver as outras."}
</EmptyState>
) : (
<Table>
<THead>
<Th>Fonte</Th><Th>Estado</Th><Th className="text-right">Duração</Th><Th>Início</Th><Th>Jogo</Th><Th>Cortes</Th><Th>Saúde</Th><Th className="text-right">Ações</Th>
</THead>
<tbody>
{shown.map((s) => <SessionRow key={s.id} session={s} name={nameOfSession(s)} onChanged={reload} />)}
</tbody>
</Table>
)}
<Dialog open={recording} onClose={() => setRecording(false)} size="sm" eyebrow="Clipador" title="Gravar pelo link"
description="Live no ar começa a gravar agora; VOD é baixado e processado inteiro.">
<RecordForm onChanged={reload} disabled={false} onDone={() => setRecording(false)} />
</Dialog>
</section>
);
}
function SessionRow({ session: s, name, onChanged }: { session: ClipperSession; name: string; onChanged: () => void }) {
const router = useRouter();
const { pending, message, run } = useClipperAction(onChanged);
const live = s.status === "recording" || s.status === "starting";
const active = ACTIVE_SESSION.includes(s.status);
const problem = ["interrupted", "stopped", "error"].includes(s.status);
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 clock = useRecordingClock(s.durationS, s.status === "recording");
const total = CLIP_STATUS_ORDER.reduce((n, k) => n + (s.clips[k] ?? 0), 0);
const ready = s.clips.ready ?? 0;
const href = `/clipper/sessions/${s.id}`;
/** Clique na linha abre o detalhe; cliques em botões, links e dentro do grupo de ações ficam com eles. */
const openDetail = (e: MouseEvent<HTMLTableRowElement>) => {
if ((e.target as HTMLElement).closest("a, button, input, select, [role=group]")) return;
router.push(href);
};
return (
<>
<tr onClick={openDetail}
className={cx("cursor-pointer border-t border-line transition-colors first:border-t-0 hover:bg-raised/40",
live && "bg-danger-soft/25 hover:bg-danger-soft/40")}>
<Td className="max-w-[20rem]">
<div className="flex items-center gap-3">
<span className={cx("grid size-9 shrink-0 place-items-center rounded-control border",
live ? "border-danger/35 bg-danger-soft text-danger" : "border-line-strong bg-raised text-fg-muted")}>
<PlatformIcon platform={s.platform} size={17} />
</span>
<div className="grid min-w-0 gap-0.5">
<Link href={href} className="truncate font-medium text-fg hover:underline focus-visible:outline-2 focus-visible:outline-accent">{name}</Link>
<p className="flex min-w-0 items-center gap-x-1.5 text-xs text-fg-subtle">
<span className="shrink-0">#{s.id}</span><span aria-hidden="true">·</span>
<span className="shrink-0">{s.kind === "vod" ? "VOD" : "live"}</span>
{s.language && <><span aria-hidden="true">·</span><span className="shrink-0" title={languageLabel(s.language)}>{languageShort(s.language)}</span></>}
{s.title && <><span aria-hidden="true">·</span><span className="truncate" title={s.title}>{s.title}</span></>}
</p>
</div>
</div>
</Td>
<Td><StatusBadge status={s.status} clock={clock} /></Td>
<Td className="text-right font-mono text-[0.8125rem] text-fg tabular-nums"><ClockText clock={clock} /></Td>
<Td className="whitespace-nowrap text-[0.8125rem] text-fg-muted">{formatDate(s.startedAt)}</Td>
<Td className="max-w-[10rem]">
{s.game ? (
<span className="flex items-center gap-1.5">
<span className="truncate text-[0.8125rem] text-fg" title={s.game}>{s.game}</span>
{mismatch && <Badge tone="warning" dot={false}>confirmar</Badge>}
</span>
) : <span className="text-fg-subtle">—</span>}
</Td>
<Td className="whitespace-nowrap">
{total > 0 ? (
<span className="grid leading-tight">
<span className={cx("text-[0.9375rem] font-semibold tabular-nums", ready > 0 ? "text-accent" : "text-fg")}>{formatInteger(ready)} <span className="text-xs font-normal text-fg-subtle">para aprovar</span></span>
<span className="text-xs text-fg-subtle tabular-nums">{formatInteger(total)} no total</span>
</span>
) : <span className="text-xs text-fg-subtle">{active ? "nenhum ainda" : "nenhum"}</span>}
</Td>
<Td className="max-w-[16rem]">
<span className={cx("block truncate text-[0.8125rem]", TONE_TEXT[health.tone])} title={health.full}>{health.text}</span>
</Td>
<Td className="text-right">
<div role="group" aria-label={`Ações da sessão ${s.id}`} className="flex flex-wrap items-center justify-end gap-1.5">
{live && s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
{active && (
<Button variant="ghost" size="sm" disabled={pending !== null} onClick={() => void stopSession(s, name, run)}>
{pending === "stop" ? <Spinner className="size-3.5" /> : <StopIcon size={15} />}Parar
</Button>
)}
{s.kind === "live" && !live && (problem || s.status === "processing") && (
<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
</Button>
)}
{problem && (
<Button variant="secondary" size="sm" disabled={pending !== null}
title="Encerra e manda a IA analisar o que já foi gravado."
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
</Button>
)}
<LinkButton href={href} variant="ghost" size="sm" aria-label={`Abrir a sessão ${s.id}`} title="Abrir">
<ArrowRightIcon size={15} />
</LinkButton>
{/* Apagar: a gravação e TODOS os cortes (inclusive aprovados) somem; por isso a confirmação em modal. */}
<Button variant="ghost" size="sm" disabled={pending !== null} aria-label={`Apagar a sessão ${s.id}`} title="Apagar sessão"
className="px-2 text-fg-subtle hover:bg-danger-soft hover:text-danger"
onClick={async () => {
if (!(await askConfirm({ title: `Apagar a sessão #${s.id} (${name})?`,
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} />}
</Button>
</div>
</Td>
</tr>
{message && (
<tr className="border-t border-line">
<td colSpan={8} className="px-4 py-2" aria-live="polite"><Feedback ok={message.ok}>{message.text}</Feedback></td>
</tr>
)}
</>
);
}
+52 -527
View File
@@ -1,35 +1,25 @@
"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";
// Sessões do Clipador: peças compartilhadas pela lista (/clipper/sessions) e pelo detalhe (/clipper/sessions/[id]):
// ícone da plataforma, "Gravar pelo link", "Cortar agora", a saúde da sessão em uma frase e o relógio da gravação.
// A lista fica em clipper-sessions-page.tsx; o detalhe (blocos do pipeline, gráfico do chat), em clipper-session-detail.tsx.
import { useEffect, useId, useLayoutEffect, useState, useSyncExternalStore, type FormEvent } 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,
LANGUAGES, SESSION_STATUS, clipperCall, formatClock, formatDuration, useClipperAction,
type Clip, type ClipperPlatform, type ClipperSession, type JudgeOptions,
} 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";
import { BroadcastIcon, KickIcon, ScissorsIcon, TwitchIcon, YouTubeIcon } from "./icons";
import { Badge, Button, Feedback, Field, Input, Select, Spinner, type Tone } from "./ui";
/** 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;
export 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;
export 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;
export const TRANSCRIPT_LATE_SEGMENTS = 4;
type Run = ReturnType<typeof useClipperAction>["run"];
@@ -40,47 +30,47 @@ export function PlatformIcon({ platform, size = 16, className }: { platform: Cli
/* ---------- Gravar pelo link ---------- */
export function RecordForm({ onChanged, disabled }: { onChanged: () => void; disabled: boolean }) {
/**
* Formulário "Gravar pelo link": live no ar começa a gravar; VOD baixa e processa. Cabe num diálogo ou solto.
* `language`: idioma falado na live (transcrição e textos da IA); vazio = padrão do serviço. O serviço antigo ignora.
* `onDone` é chamado depois do sucesso (quem abriu o diálogo fecha).
*/
export function RecordForm({ onChanged, disabled, onDone }: { onChanged: () => void; disabled: boolean; onDone?: (session: ClipperSession) => void }) {
const { pending, message, run } = useClipperAction(onChanged);
const [url, setUrl] = useState("");
const titleId = useId();
const [language, setLanguage] = useState("");
const hintId = useId();
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const done = await run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: url.trim() }),
const done = await run("record", () => clipperCall<ClipperSession>("sessions", "POST", { url: url.trim(), ...(language ? { language } : {}) }),
(s) => s.kind === "vod" ? `VOD na fila: sessão #${s.id}. Baixando e processando.` : `Gravando: sessão #${s.id}.`);
if (done) setUrl("");
if (done) { setUrl(""); onDone?.(done); }
}
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>
<form onSubmit={submit} className="grid gap-4">
<Field label="Link da live ou do VOD" hint={<span id={hintId}>Live no ar: começa a gravar agora. Vídeo (VOD) da Twitch, do YouTube ou da Kick: baixa e processa inteiro.</span>}>
<Input type="url" required value={url} onChange={(e) => setUrl(e.target.value)} disabled={disabled} autoFocus
aria-describedby={hintId} placeholder="https://www.twitch.tv/nome ou link de um vídeo" />
</Field>
<Field label="Idioma falado na live" hint="Usado na transcrição e nos textos que a IA escreve. Fonte cadastrada: deixe em branco para herdar o idioma dela.">
<Select value={language} onChange={(e) => setLanguage(e.target.value)} disabled={disabled}>
<option value="">Padrão (da fonte ou do serviço)</option>
{LANGUAGES.map((l) => <option key={l.id} value={l.id}>{l.label}</option>)}
</Select>
</Field>
<div className="flex flex-wrap items-center gap-3">
<Button disabled={disabled || pending !== null || !url.trim()}>
{pending === "record" ? <Spinner /> : <BroadcastIcon size={16} />}Gravar
</Button>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</section>
</form>
);
}
/* ---------- Cortar agora ---------- */
/** Botões "Cortar agora" (últimos 30/45/60 s). O corte manual nunca é descartado pela IA. */
@@ -105,45 +95,13 @@ export function CutNow({ sessionId, pending, run }: { sessionId: number; pending
/* ---------- 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 };
export 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 {
export function sessionHealth(s: ClipperSession, mismatch: boolean): Health {
const live = s.status === "recording" || s.status === "starting";
const issues: Issue[] = [];
const seg = s.segments;
@@ -189,16 +147,16 @@ function sessionHealth(s: ClipperSession, mismatch: boolean): Health {
return { tone: base.tone, text: parts.join(" · "), full: parts.join("\n") };
}
const TONE_TEXT: Record<Tone, string> = {
export 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> = {
export 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 }> = {
export 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" },
@@ -210,180 +168,7 @@ const STATUS_FRAME: Record<ClipperSession["status"], { icon: string; border: str
/* ---------- 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() {
export function Dot() {
return <span aria-hidden="true" className="text-line-strong">·</span>;
}
@@ -400,7 +185,7 @@ 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 {
export class RecordingClock {
private realS: number;
private running: boolean;
private receivedAt = performance.now();
@@ -489,7 +274,7 @@ class RecordingClock {
}
/** 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 {
export 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]);
@@ -497,19 +282,19 @@ function useRecordingClock(durationS: number, running: boolean): RecordingClock
return clock;
}
function useClockShown(clock: RecordingClock): number {
export function useClockShown(clock: RecordingClock): number {
return useSyncExternalStore(clock.subscribe, clock.getShown, clock.getShown);
}
function useClockStalled(clock: RecordingClock): boolean {
export function useClockStalled(clock: RecordingClock): boolean {
return useSyncExternalStore(clock.subscribe, clock.getStalled, clock.getStalled);
}
function ClockText({ clock }: { clock: RecordingClock }) {
export function ClockText({ clock }: { clock: RecordingClock }) {
return <>{formatClock(useClockShown(clock))}</>;
}
function ClockLabel({ clock, live }: { clock: RecordingClock; live: boolean }) {
export function ClockLabel({ clock, live }: { clock: RecordingClock; live: boolean }) {
const stalled = useClockStalled(clock);
if (stalled) {
return (
@@ -523,7 +308,7 @@ function ClockLabel({ clock, live }: { clock: RecordingClock; live: boolean }) {
}
/** 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 }) {
export function StatusBadge({ status, clock }: { status: ClipperSession["status"]; clock: RecordingClock }) {
const stalled = useClockStalled(clock) && status === "recording";
const info = SESSION_STATUS[status];
return (
@@ -536,7 +321,7 @@ function StatusBadge({ status, clock }: { status: ClipperSession["status"]; cloc
/* ---------- 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 {
export function useScanInterval(): number {
const [intervalS, setIntervalS] = useState(SCAN_WINDOW_S);
useEffect(() => {
let cancelled = false;
@@ -556,263 +341,3 @@ function useScanInterval(): number {
* `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>
);
}
@@ -0,0 +1,150 @@
"use client";
// Ajustes do Clipador (/clipper/settings), em abas: Juiz (IA) — provedor, modelos e o que a IA faz sozinha;
// Serviço — versão, ferramentas, transcrição e parâmetros do .env; Idiomas e públicos — como o idioma da fonte
// (transcrição e IA) se relaciona com o idioma do canal de publicação (público). Os dados vêm do ClipperProvider.
import Link from "next/link";
import type { ReactNode } from "react";
import { PROVIDER_LABEL, formatScore, languageLabel } from "./clipper-client";
import { JudgeForm } from "./clipper-judge";
import { useClipper, useClipperData } from "./clipper-provider";
import { BroadcastIcon, GlobeIcon, MicIcon, RefreshIcon, ServerIcon, SparkIcon, UsersIcon } from "./icons";
import { Tabs } from "./tabs";
import { Badge, Button, Card, Feedback, Spinner, cx } from "./ui";
type TabId = "juiz" | "servico" | "idiomas";
export function SettingsPage() {
return (
<Tabs<TabId> label="Seções dos ajustes do Clipador"
items={[
{ id: "juiz", label: "Juiz (IA)", icon: <SparkIcon size={16} /> },
{ id: "servico", label: "Serviço", icon: <ServerIcon size={16} /> },
{ id: "idiomas", label: "Idiomas e públicos", icon: <GlobeIcon size={16} /> },
]}
panels={{ juiz: <JudgeTab />, servico: <ServiceTab />, idiomas: <LanguagesTab /> }} />
);
}
function JudgeTab() {
const { judge, setJudge, refresh, refreshing } = useClipper();
if (!judge) {
return (
<Card>
<div className="grid justify-items-start gap-3">
<Feedback ok={false}>Não foi possível ler a configuração do juiz.</Feedback>
<Button variant="secondary" size="sm" onClick={() => void refresh(true)} disabled={refreshing}>
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Tentar de novo
</Button>
</div>
</Card>
);
}
return <JudgeForm key={JSON.stringify([judge.provider, judge.model, judge.minScore, judge.available])} judge={judge} onSaved={setJudge} />;
}
/* ---------- Serviço ---------- */
function ServiceTab() {
const { refresh, refreshing } = useClipper();
const { status } = useClipperData();
const j = status.judge;
return (
<Card eyebrow={<><ServerIcon size={13} />Serviço</>} title={<span className="flex flex-wrap items-center gap-3">Clipador <Badge tone="success">online</Badge><span className="text-sm font-normal text-fg-subtle">v{status.version} · 127.0.0.1:4520</span></span>}
description="O que o serviço encontrou no PC e os parâmetros com que está rodando. Os valores do .env valem depois de reiniciar o serviço."
actions={<Button variant="ghost" size="sm" onClick={() => void refresh(true)} disabled={refreshing}>{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Atualizar</Button>}>
<dl className="grid gap-x-8 gap-y-5 sm:grid-cols-2">
<Group icon={<ServerIcon size={14} />} title="Ferramentas">
<Tool name="Streamlink" path={status.tools.streamlink} />
<Tool name="FFmpeg" path={status.tools.ffmpeg} />
</Group>
<Group icon={<MicIcon size={14} />} title="Transcrição">
<Row label="Serviço de voz">
{!status.voice.configured ? <span className="text-fg-subtle">não configurado</span>
: status.voice.online ? <span className="text-success">online (Whisper, porta 4510)</span>
: <span className="text-warning">offline</span>}
</Row>
<Row label="Trechos">a cada {status.settings.segmentS} s</Row>
</Group>
<Group icon={<SparkIcon size={14} />} title="Juiz (IA)">
<Row label="Provedor">
{j.provider === "off" ? <span>desligado <span className="text-xs text-fg-subtle">· só heurística</span></span>
: <span className="flex flex-wrap items-center gap-2">{PROVIDER_LABEL[j.provider]}{j.available ? <Badge tone="success">disponível</Badge> : <Badge tone="danger">indisponível</Badge>}</span>}
</Row>
{j.provider !== "off" && <Row label="Modelo"><span className="font-mono text-xs">{j.model}</span> · nota mínima {formatScore(j.minScore)}</Row>}
</Group>
<Group icon={<GlobeIcon size={14} />} title="Gravação e idioma">
<Row label="Idioma padrão">
<span>{languageLabel(status.settings.language)}</span>
<span className="block text-xs text-fg-subtle">Muda em <code>clipper/.env</code> (<code>CLIPPER_LANGUAGE</code>); cada fonte pode ter o seu em <Link href="/clipper/sources" className="underline underline-offset-2 hover:text-fg">Fontes</Link>.</span>
</Row>
<Row label="Monitor das fontes">checa a cada {status.settings.pollS} s</Row>
<Row label="Gravação guardada">{status.settings.keepHours} h depois da live (depois só ficam os cortes)</Row>
</Group>
</dl>
</Card>
);
}
function Group({ icon, title, children }: { icon: ReactNode; title: string; children: ReactNode }) {
return (
<div className="grid content-start gap-2.5">
<h3 className="flex items-center gap-1.5 text-eyebrow font-semibold text-fg-subtle uppercase">{icon}{title}</h3>
<div className="grid gap-2 text-sm">{children}</div>
</div>
);
}
function Row({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="grid gap-0.5 sm:grid-cols-[9rem_minmax(0,1fr)] sm:gap-3">
<dt className="text-[0.8125rem] text-fg-subtle">{label}</dt>
<dd className="min-w-0 text-fg">{children}</dd>
</div>
);
}
function Tool({ name, path }: { name: string; path: string | null }) {
return (
<Row label={name}>
<span className="flex items-start gap-2">
<span className={cx("mt-1.5 size-1.5 shrink-0 rounded-full", path ? "bg-success" : "bg-danger")} aria-hidden="true" />
{path ? <span className="font-mono text-xs break-all text-fg-muted">{path}</span> : <span className="text-danger">não encontrado — rode o setup.bat</span>}
</span>
</Row>
);
}
/* ---------- Idiomas e públicos ---------- */
function LanguagesTab() {
const { status } = useClipperData();
return (
<Card eyebrow={<><GlobeIcon size={13} />Idiomas e públicos</>} title="Dois idiomas, dois lugares"
description="O idioma em que a live é falada e o idioma do público que recebe o corte são coisas diferentes, e cada um se configura no seu lugar.">
<div className="grid gap-5 md:grid-cols-2">
<Explain icon={<BroadcastIcon size={16} />} title="Idioma da fonte" where={<Link href="/clipper/sources" className="underline underline-offset-2 hover:text-fg">Fontes</Link>}>
O que o streamer fala. Guia a transcrição (Whisper) e os textos que a IA escreve para o corte (título, legenda, hashtags).
Sem escolha, vale o padrão do serviço: <strong className="font-medium text-fg">{languageLabel(status.settings.language)}</strong>.
</Explain>
<Explain icon={<UsersIcon size={16} />} title="Idioma do canal de publicação" where={<Link href="/accounts" className="underline underline-offset-2 hover:text-fg">Canais de publicação</Link>}>
O público que recebe o corte: um canal em português para o Brasil, outro em inglês para fora. Ao publicar, o painel avisa quando o
idioma do corte é diferente do idioma do canal.
</Explain>
</div>
<p className="mt-5 rounded-control border border-line bg-sunken/40 px-4 py-3 text-[0.8125rem] leading-relaxed text-fg-muted">
<strong className="font-medium text-fg">Próxima etapa:</strong> versões traduzidas de um corte (legenda queimada e textos em outro idioma, a partir da
mesma sessão) para os canais em outro idioma. O modelo já tem onde encaixar; hoje cada corte sai no idioma da fonte.
</p>
</Card>
);
}
function Explain({ icon, title, where, children }: { icon: ReactNode; title: string; where: ReactNode; children: ReactNode }) {
return (
<div className="grid content-start gap-2 rounded-control border border-line bg-raised/40 px-4 py-3.5">
<h3 className="flex items-center gap-2 text-sm font-semibold text-fg"><span className="text-accent">{icon}</span>{title}</h3>
<p className="text-[0.8125rem] leading-relaxed text-fg-muted">{children}</p>
<p className="text-xs text-fg-subtle">Onde: {where}</p>
</div>
);
}
+198
View File
@@ -0,0 +1,198 @@
"use client";
// Moldura das subpáginas do Clipador: cabeçalho compacto (título + estado do serviço em uma linha), a barra das
// lives gravando agora (sempre à mão, em qualquer subpágina) e a sub-navegação (Cortes, Sessões, Fontes, Jogos,
// Ajustes) com contadores. O conteúdo de cada subpágina vem em `children`.
import Link from "next/link";
import { usePathname } from "next/navigation";
import { type ComponentType, type ReactNode } from "react";
import { askConfirm } from "./confirm-dialog";
import { ACTIVE_CLIP, PROVIDER_LABEL, clipperCall, formatClock, useClipperAction, type ClipperSession } from "./clipper-client";
import { useClipper } from "./clipper-provider";
import { CutNow, PlatformIcon } from "./clipper-sessions";
import { BookIcon, BroadcastIcon, ClapperIcon, RefreshIcon, ScissorsIcon, SettingsIcon, StopIcon } from "./icons";
import { Badge, Button, Eyebrow, Feedback, Spinner, cx, formatInteger } from "./ui";
export type ClipperSection = { href: string; label: string; hint: string; icon: ComponentType<{ size?: number }> };
/** Subpáginas do Clipador, na ordem da sub-navegação (a sidebar usa a mesma lista). */
export const CLIPPER_SECTIONS: ClipperSection[] = [
{ href: "/clipper", label: "Cortes", hint: "Aprovar, publicar, editar", icon: ScissorsIcon },
{ href: "/clipper/sessions", label: "Sessões", hint: "Lives gravadas e VODs", icon: ClapperIcon },
{ href: "/clipper/sources", label: "Fontes", hint: "Streamers e monitor", icon: BroadcastIcon },
{ href: "/clipper/games", label: "Jogos", hint: "O que a IA sabe", icon: BookIcon },
{ href: "/clipper/settings", label: "Ajustes", hint: "Juiz, serviço, idioma", icon: SettingsIcon },
];
/** Subpágina ativa para um caminho: a mais específica que casa (o editor /clipper/edit não é nenhuma). */
export function activeSection(pathname: string): ClipperSection | null {
if (pathname.startsWith("/clipper/edit")) return null;
return [...CLIPPER_SECTIONS].sort((a, b) => b.href.length - a.href.length).find((s) => pathname === s.href || pathname.startsWith(`${s.href}/`)) ?? null;
}
export function ClipperShell({ children }: { children: ReactNode }) {
const pathname = usePathname();
const { data, offline, loadError, refreshing, refresh, polling, games, nameOfSession, reload } = useClipper();
const current = activeSection(pathname);
const clips = data?.clips ?? [];
const sessions = data?.sessions ?? [];
const live = sessions.filter((s) => s.status === "recording" || s.status === "starting");
const ready = clips.filter((c) => c.status === "ready").length;
const working = clips.filter((c) => ACTIVE_CLIP.includes(c.status)).length;
const counts: Record<string, number | undefined> = {
"/clipper": ready || undefined,
"/clipper/sessions": live.length || undefined,
"/clipper/sources": data?.channels.length,
"/clipper/games": games?.length,
};
return (
<div className="grid gap-6">
<header className="grid gap-4">
<div className="flex flex-wrap items-end justify-between gap-x-8 gap-y-3">
<div className="min-w-0">
<Eyebrow className="mb-2">Cortes de live</Eyebrow>
<h1 className="font-display text-[2rem] leading-none font-semibold tracking-[-0.03em] text-fg">Clipador</h1>
</div>
<ServiceLine offline={offline} loadError={loadError} polling={polling} working={working} />
</div>
{live.length > 0 && (
// Uma linha fina por live, num bloco só: com 5 canais no ar continua cabendo sem tomar a tela.
<section aria-labelledby="ao-vivo" className="overflow-hidden rounded-card border border-danger/30 bg-surface shadow-card">
<h2 id="ao-vivo" className="flex items-center gap-2 border-b border-danger/20 bg-danger-soft/50 px-3 py-1.5 text-eyebrow font-semibold text-danger uppercase">
<span aria-hidden="true" className="relative flex size-2"><span className="absolute inset-0 animate-ping rounded-full bg-danger/60" /><span className="relative size-2 rounded-full bg-danger" /></span>
Ao vivo agora · {live.length}
</h2>
<ul className="divide-y divide-line">
{live.map((s) => <li key={s.id}><LiveRow session={s} name={nameOfSession(s)} onChanged={reload} /></li>)}
</ul>
</section>
)}
<nav aria-label="Seções do Clipador" className="flex flex-wrap items-center gap-1 border-b border-line">
{CLIPPER_SECTIONS.map((s) => {
const active = current?.href === s.href;
const count = counts[s.href];
const Icon = s.icon;
return (
<Link key={s.href} href={s.href} aria-current={active ? "page" : undefined}
className={cx("group relative flex h-11 items-center gap-2 rounded-t-control px-3 text-sm font-medium transition-colors",
"focus-visible:outline-2 focus-visible:outline-accent",
active ? "text-fg" : "text-fg-muted hover:bg-raised/70 hover:text-fg")}>
<span className={cx("flex", active ? "text-accent" : "text-fg-subtle group-hover:text-fg-muted")}><Icon size={16} /></span>
<span className="max-sm:sr-only">{s.label}</span>
{count !== undefined && (
<span className={cx("grid h-5 min-w-5 place-items-center rounded-full px-1.5 text-[0.6875rem] font-semibold tabular-nums",
s.href === "/clipper/sessions" ? "bg-danger-soft text-danger" : active ? "bg-accent-soft text-accent" : "bg-overlay text-fg-subtle")}>
{count}
</span>
)}
{active && <span aria-hidden="true" className="absolute inset-x-2 -bottom-px h-0.5 rounded-full bg-accent" />}
</Link>
);
})}
<Button variant="ghost" size="sm" onClick={() => void refresh(true)} disabled={refreshing} aria-label="Atualizar os dados do Clipador"
className="ml-auto text-fg-subtle">
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}<span className="max-sm:sr-only">Atualizar</span>
</Button>
</nav>
</header>
{loadError && !offline && <Feedback ok={false}>Falha ao atualizar parte dos dados: {loadError}</Feedback>}
{children}
</div>
);
}
/** Estado do serviço em uma linha: ponto + "online · juiz Codex · voz ok" (o detalhe fica em Ajustes). */
function ServiceLine({ offline, loadError, polling, working }: { offline: string | null; loadError: string | null; polling: boolean; working: number }) {
const { data } = useClipper();
if (offline || !data) {
return (
<p className="flex items-center gap-2 text-xs text-danger">
<span aria-hidden="true" className="size-2 rounded-full bg-danger" />{offline ? "Clipador fora do ar" : loadError ? "sem resposta do Clipador" : "consultando…"}
</p>
);
}
const { status } = data;
const j = status.judge;
const problems = [
!status.tools.streamlink && "Streamlink não encontrado",
!status.tools.ffmpeg && "FFmpeg não encontrado",
status.voice.configured && !status.voice.online && "serviço de voz offline",
!status.voice.configured && "sem transcrição",
j.provider !== "off" && !j.available && `${PROVIDER_LABEL[j.provider]} indisponível`,
].filter(Boolean) as string[];
const tone = problems.length ? "bg-warning" : "bg-success";
return (
<Link href="/clipper/settings" className="group flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-fg-subtle hover:text-fg-muted"
title="Abrir os ajustes do Clipador">
<span aria-hidden="true" className={cx("size-2 rounded-full", tone)} />
<span className="text-fg-muted group-hover:text-fg">Serviço online</span>
<span aria-hidden="true">·</span>
<span>juiz {j.provider === "off" ? "desligado" : `${PROVIDER_LABEL[j.provider]} · ${j.model}`}</span>
{problems.length > 0 && <><span aria-hidden="true">·</span><span className="text-warning">{problems.join(" · ")}</span></>}
{working > 0 && <><span aria-hidden="true">·</span><span>{formatInteger(working)} na fila da IA/render</span></>}
{polling && <><span aria-hidden="true">·</span><span>atualizando a cada 5 s</span></>}
</Link>
);
}
/* ---------- Live gravando agora ---------- */
/** Uma linha por live: quem, relógio, chat, "Cortar agora" e Parar (só ícone). Altura fixa: a mensagem de retorno vai abaixo. */
function LiveRow({ session: s, name, onChanged }: { session: ClipperSession; name: string; onChanged: () => void }) {
const { pending, message, run } = useClipperAction(onChanged);
return (
<div className="grid gap-1 px-3 py-1.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1.5">
<Link href={`/clipper/sessions/${s.id}`} title="Abrir a sessão"
className="flex min-w-0 flex-1 basis-56 items-center gap-2.5 rounded-control text-sm focus-visible:outline-2 focus-visible:outline-accent">
<span className="grid size-7 shrink-0 place-items-center rounded-control border border-danger/35 bg-danger-soft text-danger"><PlatformIcon platform={s.platform} size={15} /></span>
<span className="truncate font-semibold text-fg">{name}</span>
{s.status === "starting" && <Badge tone="info" pulse>iniciando</Badge>}
<span className="truncate text-xs text-fg-muted tabular-nums">
{formatClock(s.durationS)} · {formatInteger(s.chatMessages)} msgs · #{s.id}
</span>
</Link>
<span className="flex items-center gap-1.5">
{s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
<Button variant="ghost" size="sm" disabled={pending !== null} aria-label={`Parar a gravação de ${name}`} title="Parar a gravação"
onClick={() => void stopSession(s, name, run)} className="px-2">
{pending === "stop" ? <Spinner className="size-3.5" /> : <StopIcon size={15} />}
</Button>
</span>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
type Run = ReturnType<typeof useClipperAction>["run"];
/**
* Parar uma sessão à mão: confirma e, por padrão, pausa o monitor da fonte (não grava de novo até você religar).
* A opção "voltar a gravar sozinho" mantém o monitor ligado. Serviço antigo ignora `pauseMonitor`.
*/
export async function stopSession(s: ClipperSession, name: string, run: Run): Promise<void> {
let keepMonitor = false;
const ok = await askConfirm({
title: `Parar a gravação de ${name}?`,
confirmLabel: "Parar",
message: <>
<p>O que já foi gravado continua sendo analisado.</p>
{s.channelId && (
<label className="mt-3 flex items-start gap-2.5 text-sm text-fg-muted">
<input type="checkbox" defaultChecked={false} onChange={(e) => { keepMonitor = e.target.checked; }} className="mt-0.5 size-4 accent-accent" />
<span>
<span className="font-medium text-fg">Voltar a gravar sozinho</span> se a live continuar ou voltar ao ar.
<span className="block text-xs text-fg-subtle">Desmarcado: o monitor desta fonte fica pausado até você religar em Fontes.</span>
</span>
</label>
)}
</>,
});
if (!ok) return;
void run("stop", () => clipperCall(`sessions/${s.id}/stop`, "POST", { pauseMonitor: !keepMonitor }),
!keepMonitor && s.channelId ? "Gravação parada. O monitor desta fonte ficou pausado até você religar." : "Gravação parada.");
}
-343
View File
@@ -1,343 +0,0 @@
"use client";
// Página do Clipador: lê estado, cortes, sessões e canais de /api/clipper/* e distribui em abas —
// Fila de cortes (o foco), Sessões, Canais e Juiz (IA). Acima das abas ficam o resumo do serviço e
// as lives gravando agora, com "Cortar agora" sempre à mão.
// Consulta de novo a cada 5 s enquanto houver sessão gravando/processando ou corte na fila (e a cada
// 10 s com o serviço fora do ar, para perceber quando ele volta); para quando a aba fica oculta.
import Link from "next/link";
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { ChannelAddForm, ChannelList, type ChannelAccounts } from "./clipper-channels";
import {
ACTIVE_CLIP, ACTIVE_SESSION, PROVIDER_LABEL, clipperCall, formatClock, formatScore, isOfflineError, sourceName, useClipperAction,
type Clip, type ClipperChannel, type ClipperSession, type ClipperStatus, type Game, type JudgeConfig,
} from "./clipper-client";
import { CutSettingsDialog, type CutScope } from "./clipper-cut-settings";
import { GamesPanel } from "./clipper-games";
import { JudgeForm } from "./clipper-judge";
import { ClipQueue } from "./clipper-queue";
import { CutNow, PlatformIcon, RecordForm, SessionList } from "./clipper-sessions";
import { AlertIcon, BookIcon, BroadcastIcon, ListIcon, MicIcon, RefreshIcon, ScissorsIcon, ServerIcon, SparkIcon, StopIcon } from "./icons";
import { Tabs } from "./tabs";
import { Badge, Button, Card, Feedback, SectionHeader, Spinner, cx, formatInteger } from "./ui";
import { askConfirm } from "./confirm-dialog";
const POLL_ACTIVE_MS = 5000;
const POLL_OFFLINE_MS = 10_000;
type Data = { status: ClipperStatus; clips: Clip[]; sessions: ClipperSession[]; channels: ClipperChannel[] };
type TabId = "cortes" | "sessoes" | "canais" | "jogos" | "juiz";
/** Troca de aba pela URL (o componente Tabs lê ?tab=). */
function goToTab(tab: TabId) {
const params = new URLSearchParams(window.location.search);
if (tab === "cortes") params.delete("tab");
else params.set("tab", tab);
const query = params.toString();
window.history.pushState(null, "", `${window.location.pathname}${query ? `?${query}` : ""}`);
window.scrollTo({ top: 0, behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" });
}
export function ClipperStudio({ channelAccounts }: { channelAccounts: ChannelAccounts }) {
const [data, setData] = useState<Data | null>(null);
const [judge, setJudge] = useState<JudgeConfig | null>(null);
const [offline, setOffline] = useState<string | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [loadedOnce, setLoadedOnce] = useState(false);
const [visible, setVisible] = useState(true);
const [sessionFilter, setSessionFilter] = useState<number | null>(null);
// Jogos pesquisados pela IA; null = serviço antigo, sem a rota /games.
const [games, setGames] = useState<Game[] | null>(null);
const [cutScope, setCutScope] = useState<CutScope | null>(null);
const refresh = useCallback(async (withJudge = false) => {
setRefreshing(true);
const [status, clips, sessions, channels, judgeResult, gamesResult] = await Promise.all([
clipperCall<ClipperStatus>("status"),
clipperCall<{ clips: Clip[] }>("clips?limit=500"),
clipperCall<{ sessions: ClipperSession[] }>("sessions?limit=50"),
clipperCall<{ channels: ClipperChannel[] }>("channels"),
withJudge ? clipperCall<JudgeConfig>("judge") : Promise.resolve(null),
clipperCall<{ games: Game[] }>("games"),
]);
setRefreshing(false);
setLoadedOnce(true);
if (!status.ok) {
if (isOfflineError(status.error)) { setOffline(status.error); setLoadError(null); }
else setLoadError(status.error);
return;
}
setOffline(null);
const firstError = [clips, sessions, channels].find((r) => !r.ok);
setLoadError(firstError && !firstError.ok ? firstError.error : null);
setData((prev) => ({
status: status.data,
clips: clips.ok ? clips.data.clips : prev?.clips ?? [],
sessions: sessions.ok ? sessions.data.sessions : prev?.sessions ?? [],
channels: channels.ok ? channels.data.channels : prev?.channels ?? [],
}));
if (judgeResult?.ok) setJudge(judgeResult.data);
setGames(gamesResult.ok ? gamesResult.data.games : null);
}, []);
useEffect(() => { void refresh(true); }, [refresh]);
useEffect(() => {
const onVisibility = () => {
const now = document.visibilityState === "visible";
setVisible(now);
if (now) void refresh();
};
document.addEventListener("visibilitychange", onVisibility);
return () => document.removeEventListener("visibilitychange", onVisibility);
}, [refresh]);
const active = Boolean(data && (data.sessions.some((s) => ACTIVE_SESSION.includes(s.status)) || data.clips.some((c) => ACTIVE_CLIP.includes(c.status))));
const interval = !visible ? null : offline ? POLL_OFFLINE_MS : active ? POLL_ACTIVE_MS : null;
useEffect(() => {
if (interval === null) return;
// Voltou do "fora do ar": recarrega também o juiz.
const timer = setInterval(() => void refresh(offline !== null), interval);
return () => clearInterval(timer);
}, [interval, offline, refresh]);
const reload = useCallback(() => void refresh(), [refresh]);
// Ao abrir a página, a fila já vem filtrada pela primeira sessão aberta (gravando agora), não por "Todas as
// sessões" (pedido do dono, 17/11/2026). Só na primeira carga: depois vale o que você escolher no filtro.
const autoPicked = useRef(false);
useEffect(() => {
if (autoPicked.current || !data) return;
autoPicked.current = true;
const open = data.sessions.find((s) => s.status === "recording" || s.status === "starting");
if (open) setSessionFilter((current) => current ?? open.id);
}, [data]);
if (!loadedOnce) {
return <div role="status" className="flex items-center gap-3 text-sm text-fg-muted"><Spinner />Consultando o Clipador…</div>;
}
if (offline || !data) {
return (
<div className="grid gap-4">
<div role="alert" className="grid gap-2 rounded-card border border-danger/30 bg-danger-soft px-5 py-4 text-sm">
<p className="flex items-start gap-2 font-semibold text-danger"><AlertIcon size={16} className="mt-0.5" />O Clipador está fora do ar.</p>
{(offline ?? loadError) && <p className="font-mono text-xs break-words text-danger/90">{offline ?? loadError}</p>}
<p className="text-fg-muted">
Rode <code>start.bat</code> (ou <code>pnpm dev</code>) para subir o painel com o Clipador (porta 4520). Se ainda não instalou,
rode <code>setup.bat</code> antes. Esta página tenta de novo a cada 10 s.
</p>
</div>
<div>
<Button variant="secondary" onClick={() => void refresh(true)} disabled={refreshing}>
{refreshing ? <Spinner /> : <RefreshIcon size={16} />}Tentar de novo
</Button>
</div>
</div>
);
}
const { status, clips, sessions, channels } = data;
const nameOfSession = (s: ClipperSession) => sourceName(s.channelId, s.url, channels);
const nameOfClip = (c: Clip) => sourceName(c.channelId, c.sessionUrl, channels);
const liveSessions = sessions.filter((s) => s.status === "recording" || s.status === "starting");
const readyCount = clips.filter((c) => c.status === "ready").length;
const refreshButton = (
<Button variant="ghost" size="sm" onClick={() => void refresh(true)} disabled={refreshing} aria-label="Atualizar os dados do Clipador">
{refreshing ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Atualizar
</Button>
);
return (
<div className="grid gap-6">
<Overview status={status} clips={clips} action={refreshButton} polling={interval !== null} />
{loadError && <Feedback ok={false}>Falha ao atualizar parte dos dados: {loadError}</Feedback>}
{liveSessions.length > 0 && (
<section aria-labelledby="ao-vivo" className="grid gap-2">
<h2 id="ao-vivo" className="sr-only">Gravando agora</h2>
{liveSessions.map((s) => <LiveBar key={s.id} session={s} name={nameOfSession(s)} onChanged={reload} />)}
</section>
)}
<Tabs<TabId> label="Seções do Clipador"
items={[
{ id: "cortes", label: "Fila de cortes", icon: <ScissorsIcon size={16} />, count: readyCount },
{ id: "sessoes", label: "Sessões", icon: <BroadcastIcon size={16} />, count: sessions.length },
{ id: "canais", label: "Fontes", icon: <ListIcon size={16} />, count: channels.length },
{ id: "jogos", label: "Jogos", icon: <BookIcon size={16} />, ...(games ? { count: games.length } : {}) },
{ id: "juiz", label: "Juiz (IA)", icon: <SparkIcon size={16} /> },
]}
panels={{
cortes: (
<ClipQueue clips={clips} sessions={sessions} sessionFilter={sessionFilter} onSessionFilter={setSessionFilter}
nameOf={nameOfClip} onChanged={reload} />
),
sessoes: <>
<RecordForm onChanged={reload} disabled={false} />
<section aria-labelledby="sessoes-titulo" className="grid gap-4">
<SectionHeader id="sessoes-titulo" title="Sessões"
description="Cada live gravada ou VOD processado, da mais nova para a mais antiga. Apagar uma sessão apaga a gravação e todos os cortes dela."
actions={sessions.length > 0 && (
<span className="flex items-center gap-3 text-xs text-fg-subtle tabular-nums">
{liveSessions.length > 0 && <Badge tone="danger" pulse>{liveSessions.length} gravando</Badge>}
<span>{sessions.length} sess{sessions.length === 1 ? "ão" : "ões"}</span>
</span>
)} />
<SessionList sessions={sessions} clips={clips} games={games ?? []} nameOf={nameOfSession} onChanged={reload}
onShowClips={(id) => { setSessionFilter(id); goToTab("cortes"); }}
onConfigure={(s) => setCutScope({ kind: "session", session: s, name: nameOfSession(s) })}
onGamesChanged={setGames} />
</section>
</>,
canais: <>
<ChannelAddForm onChanged={reload} disabled={false} />
<section aria-labelledby="canais-titulo" className="grid gap-4">
<SectionHeader id="canais-titulo" title="Fontes"
description={<>As lives de onde saem os cortes. Para publicar os cortes de uma fonte, ligue-a a um canal em <Link href="/accounts" className="text-fg underline underline-offset-2 hover:text-accent">Canais de publicação</Link>.</>} />
<ChannelList channels={channels} accounts={channelAccounts} onChanged={reload} showEmotes={games !== null}
onConfigure={(c) => setCutScope({
kind: "channel", channel: c,
// Sessões vêm da mais nova para a mais antiga: a primeira do canal dá o quadro de referência.
session: sessions.find((s) => s.channelId === c.id) ?? null,
})} />
</section>
</>,
jogos: (
<section aria-labelledby="jogos-titulo" className="grid gap-4">
<SectionHeader id="jogos-titulo" title="O que a IA sabe dos jogos"
description="Perfil pesquisado na web para cada jogo das lives: o que rende corte, o que evitar, gírias e novidades. A IA usa isso para entender o que está acontecendo na tela." />
<GamesPanel games={games ?? []} available={games !== null} onGamesChanged={setGames} />
</section>
),
juiz: judge
? <JudgeForm key={JSON.stringify([judge.provider, judge.model, judge.minScore, judge.available])} judge={judge} onSaved={setJudge} />
: (
<Card>
<div className="grid justify-items-start gap-3">
<Feedback ok={false}>Não foi possível ler a configuração do juiz.</Feedback>
<Button variant="secondary" size="sm" onClick={() => void refresh(true)}><RefreshIcon size={15} />Tentar de novo</Button>
</div>
</Card>
),
}} />
<CutSettingsDialog scope={cutScope} onClose={() => setCutScope(null)} onSaved={reload} />
</div>
);
}
/* ---------- Resumo do serviço ---------- */
function StatusItem({ icon, label, children }: { icon: ReactNode; label: string; children: ReactNode }) {
return (
<div className="grid content-start gap-1.5 rounded-control border border-line bg-surface px-4 py-3 shadow-card">
<dt className="flex items-center gap-1.5 text-eyebrow font-semibold uppercase text-fg-subtle">{icon}{label}</dt>
<dd className="grid gap-1 text-sm">{children}</dd>
</div>
);
}
function ToolState({ name, path }: { name: string; path: string | null }) {
return (
<span className="flex items-center gap-2 text-xs" title={path ?? undefined}>
<span className={cx("size-1.5 rounded-full", path ? "bg-success" : "bg-danger")} aria-hidden="true" />
<span className={path ? "text-fg-muted" : "text-danger"}>{name} {path ? "ok" : "não encontrado"}</span>
</span>
);
}
function Overview({ status, clips, action, polling }: { status: ClipperStatus; clips: Clip[]; action: ReactNode; polling: boolean }) {
const queued = clips.filter((c) => ACTIVE_CLIP.includes(c.status)).length;
const ready = clips.filter((c) => c.status === "ready").length;
const j = status.judge;
return (
<section aria-labelledby="clipador-resumo" className="grid gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 id="clipador-resumo" className="text-title text-fg">Resumo</h2>
<div className="flex items-center gap-3">
{polling && <span className="text-xs text-fg-subtle">atualizando a cada 5 s</span>}
{action}
</div>
</div>
<dl className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatusItem icon={<ServerIcon size={15} />} label="Serviço">
<span className="flex flex-wrap items-center gap-2"><Badge tone="success">online</Badge><span className="text-xs text-fg-subtle">v{status.version}</span></span>
<ToolState name="Streamlink" path={status.tools.streamlink} />
<ToolState name="FFmpeg" path={status.tools.ffmpeg} />
</StatusItem>
<StatusItem icon={<MicIcon size={15} />} label="Transcrição">
{!status.voice.configured ? <span className="text-fg-subtle">serviço de voz não configurado</span>
: status.voice.online ? <span className="text-success">serviço de voz online</span>
: <span className="text-warning">serviço de voz offline</span>}
<span className="text-xs text-fg-subtle">Whisper · {status.settings.language} · trechos de {status.settings.segmentS} s</span>
</StatusItem>
<StatusItem icon={<SparkIcon size={15} />} label="Juiz (IA)">
{j.provider === "off" ? <span className="text-fg">desligado <span className="text-xs text-fg-subtle">· só heurística</span></span> : (
<>
<span className="flex flex-wrap items-center gap-2">
<span className="text-fg">{PROVIDER_LABEL[j.provider]}</span>
{j.available ? <Badge tone="success">disponível</Badge> : <Badge tone="danger">indisponível</Badge>}
</span>
<span className="font-mono text-xs text-fg-subtle">{j.model} · nota mínima {formatScore(j.minScore)}</span>
</>
)}
</StatusItem>
<StatusItem icon={<ScissorsIcon size={15} />} label="Agora">
<span className="flex flex-wrap items-baseline gap-x-4 gap-y-1">
<Count n={status.recording} label="gravando" tone={status.recording > 0 ? "text-danger" : undefined} />
<Count n={queued} label="na fila" />
<Count n={ready} label="para aprovar" tone={ready > 0 ? "text-accent" : undefined} />
</span>
</StatusItem>
</dl>
</section>
);
}
function Count({ n, label, tone }: { n: number; label: string; tone?: string }) {
return (
<span>
<span className={cx("font-display text-xl font-semibold tabular-nums", tone ?? "text-fg")}>{formatInteger(n)}</span>{" "}
<span className="text-xs text-fg-subtle">{label}</span>
</span>
);
}
/* ---------- Live gravando agora ---------- */
function LiveBar({ session: s, name, onChanged }: { session: ClipperSession; name: string; onChanged: () => void }) {
const { pending, message, run } = useClipperAction(onChanged);
return (
<div className="grid gap-2 rounded-card border border-danger/30 bg-linear-to-r from-danger-soft/70 to-surface px-4 py-3 shadow-card">
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<span className="flex min-w-0 flex-1 basis-64 items-center gap-3">
<span className="relative grid size-9 shrink-0 place-items-center rounded-control border border-danger/35 bg-danger-soft text-danger">
<PlatformIcon platform={s.platform} size={18} />
</span>
<span className="grid min-w-0 gap-0.5">
<span className="flex flex-wrap items-center gap-2">
<span className="truncate font-semibold text-fg">{name}</span>
<Badge tone="danger" pulse>{s.status === "starting" ? "iniciando" : "ao vivo · gravando"}</Badge>
</span>
<span className="text-xs text-fg-muted tabular-nums">
{formatClock(s.durationS)} gravados · {formatInteger(s.chatMessages)} mensagens no chat · sessão #{s.id}
</span>
</span>
</span>
<span className="flex flex-wrap items-center gap-2">
{s.kind === "live" && <CutNow sessionId={s.id} pending={pending} run={run} />}
<Button variant="ghost" size="sm" disabled={pending !== null}
onClick={async () => {
if (!(await askConfirm({ title: `Parar a gravação de ${name}?`,
message: "O que já foi gravado continua sendo analisado.", confirmLabel: "Parar" }))) return;
void run("stop", () => clipperCall(`sessions/${s.id}/stop`, "POST"), "Gravação parada.");
}}>
{pending === "stop" ? <Spinner className="size-3.5" /> : <StopIcon size={15} />}Parar
</Button>
</span>
</div>
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
</div>
);
}
+49 -5
View File
@@ -10,12 +10,20 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState, type ComponentType } from "react";
import { CLIPPER_SECTIONS, activeSection } from "./clipper-shell";
import { ChartIcon, CubeIcon, FilmIcon, MicIcon, PublishIcon, ScissorsIcon, SettingsIcon, SparkIcon, TerminalIcon, UsersIcon } from "./icons";
import { LogoMark, Wordmark } from "./logo";
import { getSummary } from "./publishing-client";
import { cx } from "./ui";
type NavItem = { href: string; label: string; hint: string; icon: ComponentType<{ size?: number }> };
type SubItem = { href: string; label: string; icon?: ComponentType<{ size?: number }> };
type NavItem = {
href: string; label: string; hint: string; icon: ComponentType<{ size?: number }>;
/** Subpáginas: aparecem abaixo do item, só com a barra expandida e o item ativo (regra .rail-sub em globals.css). */
children?: SubItem[];
/** Qual subitem está ativo para um caminho (padrão: o próprio href). */
activeChild?: (pathname: string) => string | null;
};
/** Contador de "aguardando aprovação" no menu: relê a cada 30 s (só com a aba visível) e ao trocar de página. */
const SUMMARY_POLL_MS = 30_000;
@@ -23,7 +31,11 @@ const SUMMARY_POLL_MS = 30_000;
const NAV: NavItem[] = [
{ href: "/dashboard", label: "Dashboard", hint: "O que funciona e o que não", icon: ChartIcon },
{ href: "/", label: "Histórias", hint: "Episódios e votação", icon: FilmIcon },
{ href: "/clipper", label: "Clipador", hint: "Cortes de live", icon: ScissorsIcon },
{
href: "/clipper", label: "Clipador", hint: "Cortes de live", icon: ScissorsIcon,
children: CLIPPER_SECTIONS.map((s) => ({ href: s.href, label: s.label, icon: s.icon })),
activeChild: (pathname) => activeSection(pathname)?.href ?? null,
},
{ href: "/characters", label: "Personagens", hint: "Elenco reaproveitável", icon: UsersIcon },
{ href: "/assets", label: "Assets", hint: "Biblioteca e envios", icon: CubeIcon },
{ href: "/voices", label: "Vozes", hint: "Narração e legenda", icon: MicIcon },
@@ -108,14 +120,18 @@ export function Sidebar() {
);
}
function NavLink({ item: { href, label, hint, icon: Icon }, active, count = null, countLabel }: {
function NavLink({ item, active, count = null, countLabel }: {
item: NavItem; active: boolean;
/** Número ao lado do ícone (some quando é 0 ou desconhecido). */
count?: number | null; countLabel?: string;
}) {
const { href, label, hint, icon: Icon, children } = item;
const pathname = usePathname();
const showCount = count !== null && count > 0;
return (
<Link href={href} aria-current={active ? "page" : undefined}
// Com subpáginas: o item principal marca a seção; o subitem marca a página (aria-current fica no subitem).
const activeChild = active && children ? item.activeChild?.(pathname) ?? null : null;
const link = (
<Link href={href} aria-current={active && !children ? "page" : undefined}
className={cx(
"relative flex h-12 min-w-0 shrink-0 items-center gap-3 overflow-hidden rounded-control px-3.5 transition-colors",
active ? "bg-raised text-fg" : "text-fg-muted hover:bg-raised/70 hover:text-fg",
@@ -139,4 +155,32 @@ function NavLink({ item: { href, label, hint, icon: Icon }, active, count = null
{showCount && <span className="sr-only">: {count} {countLabel}</span>}
</Link>
);
if (!children || !active) return link;
return (
<div className="grid">
{link}
{/* Subpáginas: abrem com a barra (altura animada por grid-template-rows); recolhida, não ocupam espaço. */}
<div className="rail-sub">
<ul className="min-h-0 overflow-hidden" aria-label={`Seções de ${label}`}>
{children.map((c) => {
const on = activeChild === c.href;
const SubIcon = c.icon;
return (
<li key={c.href}>
<Link href={c.href} aria-current={on ? "page" : undefined}
className={cx("relative flex h-8 items-center gap-2.5 rounded-control py-1 pr-3 pl-[2.75rem] text-[0.8125rem] whitespace-nowrap transition-colors",
on ? "bg-raised/60 font-semibold text-fg" : "text-fg-subtle hover:bg-raised/40 hover:text-fg")}>
{/* Mesmo ícone da sub-navegação do topo do Clipador; sem ícone, um ponto. */}
{SubIcon
? <span aria-hidden="true" className={cx("flex shrink-0", on ? "text-accent" : "text-fg-subtle")}><SubIcon size={15} /></span>
: <span aria-hidden="true" className={cx("size-1.5 shrink-0 rounded-full", on ? "bg-accent" : "bg-line-strong")} />}
<span className="rail-label">{c.label}</span>
</Link>
</li>
);
})}
</ul>
</div>
</div>
);
}
+16 -7
View File
@@ -6,6 +6,7 @@
// escolhidos pelo usuário: API oficial ou sessão logada. O estado do perfil (`Profile` do Publicador) é espelhado
// em account_networks; tokens e sessões ficam só no Publicador (nunca neste banco nem no navegador).
import { all, get, now, run } from "./db";
import { DEFAULT_LANGUAGE, isAccountLanguage } from "./languages";
import { SLUG_RE, slugify } from "./paths";
import {
checkSession, connectProfile, deleteProfile, getProfile, openSession, pasteToken, profileIdFor, tiktokCreatorInfo,
@@ -48,30 +49,38 @@ function view(account: Account): AccountView {
};
}
export function createAccount(input: { name: string; niche?: string; notes?: string }): AccountView {
export function createAccount(input: { name: string; niche?: string; notes?: string; language?: unknown }): AccountView {
const name = input.name.trim();
if (name.length < 2 || name.length > 60) throw new UserError("Nome do canal precisa ter entre 2 e 60 caracteres.");
const language = mustLanguage(input.language ?? DEFAULT_LANGUAGE);
const base = slugify(name);
if (!SLUG_RE.test(base)) throw new UserError("Nome precisa ter letras ou números.");
let id = base;
for (let n = 2; get("SELECT 1 FROM accounts WHERE id = ?", id); n++) id = `${base.slice(0, 44)}-${n}`;
const ts = now();
run("INSERT INTO accounts (id, name, niche, notes, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)",
id, name, (input.niche ?? "").trim().slice(0, 60), (input.notes ?? "").trim().slice(0, 500), ts, ts);
run("INSERT INTO accounts (id, name, niche, notes, language, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
id, name, (input.niche ?? "").trim().slice(0, 60), (input.notes ?? "").trim().slice(0, 500), language, ts, ts);
return getAccount(id)!;
}
/** Idioma válido (pt-BR, en-US, es-419) ou erro legível. */
function mustLanguage(value: unknown): string {
if (!isAccountLanguage(value)) throw new UserError("Idioma inválido: use pt-BR, en-US ou es-419.");
return value;
}
const APPROVAL_MODES: ApprovalMode[] = ["manual", "auto"];
const TIMINGS: PublishTiming[] = ["now", "best_slot"];
const AI_LABELS: AiLabel[] = ["auto", "always", "never"];
/** Edita nome, nicho, notas e as regras de publicação (aprovação, quando publicar, rótulo de IA). */
/** Edita nome, nicho, notas, idioma e as regras de publicação (aprovação, quando publicar, rótulo de IA). */
export function updateAccount(id: string, input: {
name?: string; niche?: string; notes?: string; approvalMode?: unknown; timing?: unknown; aiLabel?: unknown;
name?: string; niche?: string; notes?: string; language?: unknown; approvalMode?: unknown; timing?: unknown; aiLabel?: unknown;
}): AccountView {
const account = mustGet(id);
const name = (input.name ?? account.name).trim();
if (name.length < 2 || name.length > 60) throw new UserError("Nome do canal precisa ter entre 2 e 60 caracteres.");
const language = mustLanguage(input.language ?? account.language);
const approvalMode = (input.approvalMode ?? account.approval_mode) as ApprovalMode;
if (!APPROVAL_MODES.includes(approvalMode)) throw new UserError("Aprovação inválida: use manual ou auto.");
const timing = (input.timing ?? account.timing) as PublishTiming;
@@ -80,10 +89,10 @@ export function updateAccount(id: string, input: {
if (!AI_LABELS.includes(aiLabel)) throw new UserError("Rótulo de IA inválido: use auto, always ou never.");
// Ligar o automático vale daqui para a frente: cortes que já estavam prontos continuam esperando você.
const autoSince = approvalMode === "auto" ? (account.approval_mode === "auto" ? account.auto_since : now()) : null;
run(`UPDATE accounts SET name = ?, niche = ?, notes = ?, approval_mode = ?, timing = ?, ai_label = ?, auto_since = ?, updated_at = ?
run(`UPDATE accounts SET name = ?, niche = ?, notes = ?, language = ?, approval_mode = ?, timing = ?, ai_label = ?, auto_since = ?, updated_at = ?
WHERE id = ?`,
name, (input.niche ?? account.niche).trim().slice(0, 60), (input.notes ?? account.notes).trim().slice(0, 500),
approvalMode, timing, aiLabel, autoSince, now(), id);
language, approvalMode, timing, aiLabel, autoSince, now(), id);
return getAccount(id)!;
}
+9 -2
View File
@@ -27,17 +27,20 @@ function serviceUrl(pathname: string): { url: string; key: string } {
/**
* Caminhos que o navegador pode pedir (sempre sob /v1/). Qualquer outro é recusado aqui, antes do serviço.
* status · judge · emotes · games[/id[/research|refine|notes/n]] · channels[/id[/check|settings]]
* status · judge · emotes · games[/id[/research|refine|translate|notes/n]] (POST games = cadastrar; PUT/DELETE games/id) · channels[/id[/check|settings]]
* sessions[/id[/timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face[/reset]]] · clips[/id[/render|rejudge]]
* editor de cortes: clips/id/(edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest)
* apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS
*/
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest))?))?)$/;
const ALLOWED = /^(status|judge|emotes|games(\/[a-z0-9-]{1,60}(\/(research|refine|translate|notes\/\d{1,3}))?)?|channels(\/(twitch|youtube|kick)-[a-z0-9._-]{2,60}(\/(check|settings))?)?|sessions(\/\d{1,9}(\/(timeline|stop|resume|finish|clips|settings|frame|preview|detect-cam|game|face(\/reset)?))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest))?))?)$/;
/** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */
const METHODS: [RegExp, string[]][] = [
[/^clips\/delete$/, ["POST"]],
[/^clips\/\d{1,9}$/, ["GET", "PATCH", "DELETE"]],
// Jogos: listar e cadastrar; gravar a edição (PUT ?lang=pt|en) e apagar (doc/clipador/JOGOS.md).
[/^games$/, ["GET", "POST"]],
[/^games\/[a-z0-9-]{1,60}$/, ["PUT", "DELETE"]],
];
export async function clipperFetch(pathname: string, init: RequestInit = {}, timeoutMs = 30_000): Promise<Response> {
@@ -63,7 +66,11 @@ export async function proxy(request: Request, segments: string[]): Promise<Respo
// Rotas que chamam a IA pela CLI ou o Streamlink demoram: pesquisa de jogo na web até 8 min (o serviço corta em 7);
// achar câmera/prévia/checar live até 3 min (a câmera local baixa o modelo na 1ª vez); editor (proxy de até 10 min
// de vídeo, prévia real, Whisper, TTS, IA) até 5 min; série do rosto (só leitura do banco) e reset, 30 s; o resto, 2 min.
// Tradução do perfil (pt ↔ en, sem busca) e gravar a edição (traduz junto) até 5 min; cadastrar jogo responde na
// hora (a pesquisa roda em segundo plano no serviço).
const timeoutMs = /^games\/[^/]+\/(research|refine)$/.test(sub) ? 480_000
: /^games\/[^/]+\/translate$/.test(sub) || (/^games\/[^/]+$/.test(sub) && method === "PUT") ? 300_000
: sub === "games" && method === "POST" ? 30_000
: /^clips\/\d+\/(proxy|preview-render|retranscribe|tts|suggest|waveform)$/.test(sub) ? 300_000
: /\/(detect-cam|preview|check)$/.test(sub) ? 180_000
: /^sessions\/\d+\/face(\/reset)?$/.test(sub) ? 30_000 : 120_000;
+5
View File
@@ -396,6 +396,11 @@ export const MIGRATIONS: string[] = [
PRIMARY KEY (account_id, platform)
);
`,
// v9: idioma e público do canal de publicação (pt-BR = Brasil; en-US = público em inglês; es-419 = América
// Latina). Prepara canais gringos ao lado dos canais em português; as regras ficam em lib/languages.ts.
`
ALTER TABLE accounts ADD COLUMN language TEXT NOT NULL DEFAULT 'pt-BR';
`,
];
const g = globalThis as unknown as { __cenaforgeDb?: DatabaseSync };
+25
View File
@@ -0,0 +1,25 @@
// Idiomas e públicos dos canais de publicação. Sem imports de servidor: o navegador usa também
// (formulários do canal, diálogo "Publicar" do corte). O 1º é o padrão (canais em português, Brasil).
export type AccountLanguage = { id: string; label: string; short: string; audience: string };
export const ACCOUNT_LANGUAGES: AccountLanguage[] = [
{ id: "pt-BR", label: "Português (Brasil)", short: "PT", audience: "Brasil e falantes de português" },
{ id: "en-US", label: "English (US)", short: "EN", audience: "Estados Unidos e público em inglês" },
{ id: "es-419", label: "Español (Latinoamérica)", short: "ES", audience: "América Latina em espanhol" },
];
export const DEFAULT_LANGUAGE = ACCOUNT_LANGUAGES[0].id;
export function isAccountLanguage(code: unknown): code is string {
return typeof code === "string" && ACCOUNT_LANGUAGES.some((l) => l.id === code);
}
/** Nome legível ("English (US)"); código desconhecido volta como está. */
export function languageLabel(code: string | null | undefined): string {
return ACCOUNT_LANGUAGES.find((l) => l.id === code)?.label ?? (code || "—");
}
/** Sigla curta ("EN"); código desconhecido vira a parte antes do hífen em maiúsculas. */
export function languageShort(code: string | null | undefined): string {
return ACCOUNT_LANGUAGES.find((l) => l.id === code)?.short ?? (code ? code.split("-")[0].toUpperCase() : "—");
}
+11 -1
View File
@@ -61,7 +61,7 @@ describe("migração v5", () => {
it("migra com backup, preserva ids e não quebra chaves estrangeiras", () => {
const version = dbm.get<{ user_version: number }>("PRAGMA user_version")!.user_version;
assert.equal(version, dbm.MIGRATIONS.length);
assert.equal(version, 8);
assert.equal(version, 9);
assert.equal(fs.readdirSync(path.join(ROOT, "data", "backups")).filter((f) => f.startsWith("cenaforge-v4-")).length, 1);
assert.deepEqual(dbm.all("PRAGMA foreign_key_check"), []);
});
@@ -110,6 +110,16 @@ describe("canal: regras e ajustes da rede", () => {
assert.throws(() => accounts.updateAccount("canal", { timing: "amanhã" }), /Quando publicar/);
});
it("idioma e público: canal antigo é pt-BR, aceita en-US/es-419 e recusa o resto", () => {
assert.equal(accounts.getAccount("canal")!.language, "pt-BR");
assert.equal(accounts.updateAccount("canal", { language: "en-US" }).language, "en-US");
assert.throws(() => accounts.updateAccount("canal", { language: "klingon" }), /Idioma inválido/);
assert.equal(accounts.updateAccount("canal", { language: "pt-BR" }).language, "pt-BR");
const gringo = accounts.createAccount({ name: "Canal gringo", language: "es-419" });
assert.equal(gringo.language, "es-419");
accounts.deleteAccount(gringo.id);
});
it("ajustes por rede validados (privacidade por rede, limite 1–20)", () => {
const n = accounts.updateNetworkSettings("canal", "tiktok", { dailyLimit: 5, privacy: "private", tiktokMode: "draft" });
assert.deepEqual([n.status, n.daily_limit, n.privacy, n.tiktok_mode], ["disconnected", 5, "private", "draft"]);
+2
View File
@@ -181,6 +181,8 @@ export type Account = {
ai_label: AiLabel;
/** Quando a aprovação automática foi ligada (cortes mais antigos não são aprovados sozinhos). */
auto_since: string | null;
/** Idioma e público do canal (pt-BR, en-US, es-419 — lib/languages.ts). */
language: string;
created_at: string;
updated_at: string;
};