Merge branch 'clipper/roles' into clipper/integ
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
"use client";
|
||||
// Equipe de IA do Clipador (doc/clipador/EQUIPE-IA.md): um cartão por papel — varredura, analista, editor e juiz —
|
||||
// com provedor, modelo (lista do provedor escolhido), raciocínio (só Codex), imagens, liga/desliga (o editor não
|
||||
// desliga), as instruções padrão (só leitura) e as instruções do administrador (somadas às padrão). E o relatório
|
||||
// de medição: chamadas e tokens por papel, decisões do juiz e a concordância dele com você.
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
CHECK_LABEL, PROVIDER_LABEL, ROLE_INFO, ROLE_ORDER, clipperCall, formatScore,
|
||||
type AiEffort, type AiImages, type AiReport, type AiRole, type AiRoleId, type AiRoleProvider, type AiRoles,
|
||||
type ContextCheckId, type JudgeConfig,
|
||||
} from "./clipper-client";
|
||||
import { DescribedSelect } from "./forms";
|
||||
import { AlertIcon, RefreshIcon, SparkIcon } from "./icons";
|
||||
import { Badge, Button, Card, Select, Spinner, Switch, Textarea, cx } from "./ui";
|
||||
|
||||
const EXTRA_MAX = 2000;
|
||||
const EFFORT_LABEL: Record<AiEffort, string> = { "": "padrão (baixo)", low: "baixo", medium: "médio", high: "alto" };
|
||||
const IMAGES_LABEL: Record<AiImages, { label: string; description: string }> = {
|
||||
mosaic: { label: "Mosaico (1 imagem com 8 quadros)", description: "Os quadros numa grade 4×2: a IA vê a sequência pagando por 1 imagem (4–8× menos que quadros soltos)." },
|
||||
frames: { label: "Quadros soltos (antigo)", description: "Cada quadro em uma imagem, em 768 px. Mais detalhe, bem mais caro." },
|
||||
none: { label: "Nenhuma", description: "Só texto (fala, chat, rosto e o que a varredura já descreveu da tela)." },
|
||||
};
|
||||
const ALL_CHECKS = Object.keys(CHECK_LABEL) as ContextCheckId[];
|
||||
|
||||
/** Provedores que dá para escolher: Codex e Claude sempre; Gemini só se estiver ligado em Configurações → IA. */
|
||||
function providerOptions(judge: JudgeConfig, current: AiRoleProvider): AiRoleProvider[] {
|
||||
const list: AiRoleProvider[] = ["codex", "claude"];
|
||||
if (judge.providers?.gemini?.enabled || current === "gemini") list.push("gemini");
|
||||
return list;
|
||||
}
|
||||
|
||||
export function AiTeam({ judge, roles, onChange, disabled }: {
|
||||
judge: JudgeConfig; roles: AiRoles; onChange: (next: AiRoles) => void; disabled: boolean;
|
||||
}) {
|
||||
const set = (id: AiRoleId, values: Partial<AiRole>) => onChange({ ...roles, [id]: { ...roles[id], ...values } });
|
||||
return (
|
||||
<section aria-labelledby="equipe-ia" className="grid gap-4">
|
||||
<div className="grid gap-1">
|
||||
<h3 id="equipe-ia" className="text-sm font-semibold text-fg">Equipe de IA</h3>
|
||||
<p className="max-w-[85ch] text-[0.8125rem] leading-relaxed text-fg-muted">
|
||||
Cada papel roda na IA que você escolher. A <strong className="text-fg">varredura</strong> e o <strong className="text-fg">analista</strong> veem a tela;
|
||||
o <strong className="text-fg">editor</strong> decide se vira corte; o <strong className="text-fg">juiz</strong> confere se o corte faz sentido para quem nunca viu a live.
|
||||
Se a IA de um papel cair, a reserva de Configurações → IA assume para aquele papel.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
{ROLE_ORDER.map((id) => (
|
||||
<RoleCard key={id} id={id} role={roles[id]} judge={judge} disabled={disabled} onChange={(values) => set(id, values)} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RoleCard({ id, role, judge, disabled, onChange }: {
|
||||
id: AiRoleId; role: AiRole; judge: JudgeConfig; disabled: boolean; onChange: (values: Partial<AiRole>) => void;
|
||||
}) {
|
||||
const info = ROLE_INFO[id];
|
||||
const models = judge.models[role.provider] ?? [];
|
||||
const fallback = judge.models.defaults[role.provider] ?? "";
|
||||
const model = models.some((m) => m.id === role.model) ? role.model : "";
|
||||
const status = judge.providers?.[role.provider];
|
||||
const off = !role.enabled;
|
||||
const headingId = `papel-${id}`;
|
||||
return (
|
||||
<article aria-labelledby={headingId}
|
||||
className={cx("grid content-start gap-4 rounded-card border bg-sunken/30 p-5 transition-opacity", off ? "border-line opacity-70" : "border-line-strong")}>
|
||||
<header className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="grid min-w-0 gap-1">
|
||||
<h4 id={headingId} className="flex flex-wrap items-center gap-2 text-sm font-semibold text-fg">
|
||||
{info.label}
|
||||
{id === "judge" && <Badge tone="violet" dot={false}>novo</Badge>}
|
||||
{status && !status.ready && <Badge tone="warning">{PROVIDER_LABEL[role.provider]}: {status.reason ?? "indisponível"}</Badge>}
|
||||
</h4>
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">{info.does}</p>
|
||||
</div>
|
||||
{id === "editor"
|
||||
? <span className="text-xs text-fg-subtle">sempre ligado</span>
|
||||
: <Switch label={role.enabled ? "Ligado" : "Desligado"} checked={role.enabled} disabled={disabled} onChange={(enabled) => onChange({ enabled })} />}
|
||||
</header>
|
||||
|
||||
<fieldset disabled={disabled || off} className="grid gap-4 sm:grid-cols-2 disabled:opacity-60">
|
||||
<label className="grid content-start gap-2">
|
||||
<span className="text-[0.8125rem] font-medium text-fg-muted">Provedor</span>
|
||||
<Select value={role.provider} onChange={(e) => onChange({ provider: e.target.value as AiRoleProvider, model: "", effort: "" })}>
|
||||
{providerOptions(judge, role.provider).map((p) => <option key={p} value={p}>{PROVIDER_LABEL[p]}</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
<DescribedSelect name={`${id}-model`} label="Modelo" value={model} onChange={(value) => onChange({ model: value })}
|
||||
options={[
|
||||
{ value: "", label: `Padrão do provedor (${fallback})`, description: "Usa o modelo recomendado; troca sozinho se o padrão mudar." },
|
||||
...models.map((m) => ({ value: m.id, label: m.label, description: m.description })),
|
||||
]} />
|
||||
{role.provider === "codex" && (
|
||||
<label className="grid content-start gap-2">
|
||||
<span className="text-[0.8125rem] font-medium text-fg-muted">Raciocínio</span>
|
||||
<Select value={role.effort} onChange={(e) => onChange({ effort: e.target.value as AiEffort })}>
|
||||
{(Object.keys(EFFORT_LABEL) as AiEffort[]).map((e) => <option key={e} value={e}>{EFFORT_LABEL[e]}</option>)}
|
||||
</Select>
|
||||
<span className="text-xs leading-relaxed text-fg-subtle">Mais raciocínio = resposta mais cuidadosa, mais lenta e mais cara.</span>
|
||||
</label>
|
||||
)}
|
||||
{(id === "scan" || id === "analyst") && (
|
||||
<DescribedSelect<AiImages> name={`${id}-images`} label="Imagens da tela" value={role.images ?? "mosaic"}
|
||||
onChange={(images) => onChange({ images })}
|
||||
options={(Object.keys(IMAGES_LABEL) as AiImages[]).map((v) => ({ value: v, ...IMAGES_LABEL[v] }))} />
|
||||
)}
|
||||
</fieldset>
|
||||
|
||||
{id === "judge" && <JudgeRules role={role} disabled={disabled || off} onChange={onChange} />}
|
||||
|
||||
<Instructions id={id} role={role} judge={judge} disabled={disabled} onChange={(extra) => onChange({ extra })} />
|
||||
{role.chain && role.chain.length > 1 && !off && (
|
||||
<p className="text-xs text-fg-subtle">Ordem de tentativa: {role.chain.map((p) => PROVIDER_LABEL[p]).join(" → ")}</p>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
/** Regras do juiz: quais checagens são críticas e o que ele pode fazer além de descartar. */
|
||||
function JudgeRules({ role, disabled, onChange }: { role: AiRole; disabled: boolean; onChange: (values: Partial<AiRole>) => void }) {
|
||||
const critical = role.critical ?? ["setup", "payoff", "standalone"];
|
||||
const toggle = (check: ContextCheckId) => onChange({
|
||||
critical: critical.includes(check) ? critical.filter((c) => c !== check) : ALL_CHECKS.filter((c) => c === check || critical.includes(c)),
|
||||
});
|
||||
const penalty = role.penalty ?? 0.5;
|
||||
return (
|
||||
<fieldset disabled={disabled} className="grid gap-3 disabled:opacity-60">
|
||||
<legend className="mb-1 text-[0.8125rem] font-medium text-fg-muted">Checagens críticas</legend>
|
||||
<div className="flex flex-wrap gap-1.5" role="group" aria-label="Checagens críticas">
|
||||
{ALL_CHECKS.map((check) => {
|
||||
const on = critical.includes(check);
|
||||
return (
|
||||
<button key={check} type="button" aria-pressed={on} onClick={() => toggle(check)}
|
||||
className={cx("rounded-full border px-2.5 py-1 text-xs font-medium transition-colors",
|
||||
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
|
||||
on ? "border-violet/50 bg-violet-soft text-violet" : "border-line-strong text-fg-muted hover:text-fg")}>
|
||||
{CHECK_LABEL[check]}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-xs leading-relaxed text-fg-subtle">
|
||||
Crítica que falha descarta o corte (ou ajusta o trecho, se der); as outras tiram {formatScore(penalty)} da nota cada.
|
||||
</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<Switch label="Pode ajustar o trecho" checked={role.allowFix ?? true} onChange={(allowFix) => onChange({ allowFix })}
|
||||
hint="Recua o início para pegar o começo ou estica o fim até o desfecho, dentro da duração do corte, e confere uma vez de novo." />
|
||||
<Switch label="Pode pôr frase de contexto" checked={role.allowContextLine ?? true} onChange={(allowContextLine) => onChange({ allowContextLine })}
|
||||
hint="Uma frase curta na tela nos primeiros segundos (no lugar do gancho) quando falta contexto para quem chega agora." />
|
||||
</div>
|
||||
<label className="flex flex-wrap items-center gap-3 text-[0.8125rem] text-fg-muted">
|
||||
Desconto por checagem não crítica
|
||||
<Select className="h-9 w-28" value={String(penalty)} onChange={(e) => onChange({ penalty: Number(e.target.value) })}>
|
||||
{[0, 0.25, 0.5, 1].map((v) => <option key={v} value={String(v)}>{v === 0 ? "nenhum" : `−${formatScore(v)}`}</option>)}
|
||||
</Select>
|
||||
</label>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
/** Instruções padrão (só leitura, nos dois idiomas) e as do administrador (editáveis, somadas às padrão). */
|
||||
function Instructions({ id, role, judge, disabled, onChange }: {
|
||||
id: AiRoleId; role: AiRole; judge: JudgeConfig; disabled: boolean; onChange: (extra: string) => void;
|
||||
}) {
|
||||
const [lang, setLang] = useState<"pt" | "en">("pt");
|
||||
const defaults = judge.roleDefaults?.[id];
|
||||
return (
|
||||
<div className="grid gap-3">
|
||||
{defaults && (
|
||||
<details className="group rounded-control border border-line bg-surface/60 px-3 py-2">
|
||||
<summary className="cursor-pointer text-xs font-medium text-fg-muted select-none hover:text-fg">Instruções padrão (só leitura)</summary>
|
||||
<div className="mt-2 grid gap-2">
|
||||
<div className="flex gap-1" role="group" aria-label="Idioma das instruções padrão">
|
||||
{(["pt", "en"] as const).map((l) => (
|
||||
<button key={l} type="button" aria-pressed={lang === l} onClick={() => setLang(l)}
|
||||
className={cx("rounded-md px-2 py-0.5 text-[0.6875rem] font-semibold", lang === l ? "bg-overlay text-fg" : "text-fg-subtle hover:text-fg")}>
|
||||
{l === "pt" ? "Fonte em português" : "Fonte em inglês"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<pre className="max-h-64 overflow-auto rounded-md bg-sunken/60 p-3 font-mono text-[0.6875rem] leading-relaxed whitespace-pre-wrap text-fg-muted">{defaults[lang]}</pre>
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
<label className="grid gap-1.5">
|
||||
<span className="flex items-baseline justify-between gap-3 text-[0.8125rem] font-medium text-fg-muted">
|
||||
Instruções do administrador
|
||||
<span className="font-mono text-[0.6875rem] text-fg-subtle tabular-nums">{role.extra.length}/{EXTRA_MAX}</span>
|
||||
</span>
|
||||
<Textarea rows={3} maxLength={EXTRA_MAX} disabled={disabled} value={role.extra} onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={id === "judge" ? "Ex.: não aprove corte que termina antes do resultado da treta." : "Ex.: lag conta como jogada engraçada neste canal."} />
|
||||
<span className="text-xs leading-relaxed text-fg-subtle">Vão depois das padrão, em todas as chamadas deste papel. Pode escrever em português, mesmo com a fonte em inglês.</span>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Medição ---------- */
|
||||
|
||||
const ROLE_NAME: Record<string, string> = { scan: "Varredura", analyst: "Analista", editor: "Editor", judge: "Juiz" };
|
||||
const percent = (v: number | null | undefined) => (v === null || v === undefined ? "—" : `${Math.round(v * 100)}%`);
|
||||
const thousands = (v: number | null | undefined) => (v === null || v === undefined ? "—" : v >= 1000 ? `${(v / 1000).toFixed(v >= 10_000 ? 0 : 1)} mil` : String(v));
|
||||
|
||||
/** Relatório (GET /judge/report): para comparar custo por hora e ver se o juiz concorda com você. */
|
||||
export function AiTeamReport() {
|
||||
const [days, setDays] = useState(7);
|
||||
const [report, setReport] = useState<AiReport | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
const r = await clipperCall<AiReport>(`judge/report?days=${days}`);
|
||||
setLoading(false);
|
||||
if (r.ok) { setReport(r.data); setError(null); } else setError(r.error);
|
||||
}, [days]);
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
const roles = report ? Object.entries(report.perHour) : [];
|
||||
const agreement = report?.agreement.judge;
|
||||
return (
|
||||
<Card eyebrow={<><SparkIcon size={13} />Medição</>} title="Quanto a equipe gasta e se o juiz acerta"
|
||||
description="Chamadas e tokens por papel por hora de live gravada; o que o juiz decidiu; e a concordância dele com as suas decisões (aprovar, rejeitar e “sem contexto”)."
|
||||
actions={<>
|
||||
<Select className="h-9 w-32" aria-label="Período" value={String(days)} onChange={(e) => setDays(Number(e.target.value))}>
|
||||
{[1, 7, 30].map((d) => <option key={d} value={String(d)}>{d === 1 ? "últimas 24 h" : `últimos ${d} dias`}</option>)}
|
||||
</Select>
|
||||
<Button variant="ghost" size="sm" onClick={() => void load()} disabled={loading}>
|
||||
{loading ? <Spinner className="size-3.5" /> : <RefreshIcon size={15} />}Atualizar
|
||||
</Button>
|
||||
</>}>
|
||||
{error && <p className="flex items-start gap-2 text-sm text-danger"><AlertIcon size={14} className="mt-0.5" />{error}</p>}
|
||||
{!report && !error && <p className="flex items-center gap-2 text-sm text-fg-subtle"><Spinner className="size-3.5" />Lendo a medição…</p>}
|
||||
{report && (
|
||||
<div className="grid gap-6">
|
||||
<dl className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
<Metric label="Horas de live" value={report.window.liveHours.toLocaleString("pt-BR")} />
|
||||
<Metric label="Aprovados por você" value={percent(report.clips.approvalRate)} hint={`${report.clips.labeled} avaliados`} />
|
||||
<Metric label="Descartados pelo juiz" value={String(report.judge.discard)} hint={`${report.judge.adjust} ajustados · ${report.judge.contextLine} com frase`} />
|
||||
<Metric label="Juiz concorda com você" value={percent(agreement?.rate)}
|
||||
hint={agreement && agreement.pairs ? `${agreement.pairs} cortes · κ ${agreement.kappa ?? "—"}` : "avalie cortes para medir"} />
|
||||
</dl>
|
||||
{roles.length > 0 ? (
|
||||
<div className="overflow-x-auto rounded-control border border-line">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="bg-raised/60 text-[0.6875rem] tracking-[0.12em] text-fg-subtle uppercase">
|
||||
<tr><th className="px-4 py-2.5">Papel</th><th className="px-4 py-2.5">Chamadas/h</th><th className="px-4 py-2.5">Tokens de entrada/h</th><th className="px-4 py-2.5">Saída/h</th><th className="px-4 py-2.5">IA · modo</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{roles.map(([role, h]) => {
|
||||
const rows = report.calls.filter((c) => c.role === role);
|
||||
const failures = rows.reduce((n, c) => n + c.failures, 0);
|
||||
return (
|
||||
<tr key={role} className="border-t border-line">
|
||||
<td className="px-4 py-2.5 font-medium text-fg">{ROLE_NAME[role] ?? role}{failures > 0 && <span className="ml-2 text-xs text-warning">{failures} falha{failures === 1 ? "" : "s"}</span>}</td>
|
||||
<td className="px-4 py-2.5 tabular-nums">{h.calls ?? "—"}</td>
|
||||
<td className="px-4 py-2.5 tabular-nums" title={h.tokensIn === null ? "Estimado pelo tamanho do texto (a CLI não informou o uso)" : undefined}>
|
||||
{h.tokensIn !== null ? thousands(h.tokensIn) : <span className="text-fg-subtle">≈ {thousands(h.estTokensIn)}</span>}
|
||||
</td>
|
||||
<td className="px-4 py-2.5 tabular-nums">{thousands(h.tokensOut)}</td>
|
||||
<td className="px-4 py-2.5 font-mono text-[0.6875rem] text-fg-subtle">
|
||||
{[...new Set(rows.map((c) => `${c.provider}:${c.model}${c.mode ? ` · ${c.mode}` : ""}`))].join(", ")}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : <p className="text-sm text-fg-subtle">Nenhuma chamada de IA registrada no período.</p>}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function Metric({ label, value, hint }: { label: string; value: string; hint?: string }) {
|
||||
return (
|
||||
<div className="grid content-start gap-1">
|
||||
<dt className="text-eyebrow font-semibold text-fg-subtle uppercase">{label}</dt>
|
||||
<dd className="font-display text-2xl leading-none font-semibold text-fg tabular-nums">{value}</dd>
|
||||
{hint && <dd className="text-xs text-fg-subtle">{hint}</dd>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,8 +18,40 @@ export type ClipperStatus = {
|
||||
};
|
||||
|
||||
export type JudgeModel = { id: string; label: string; description?: string };
|
||||
/** `faceTrack` é opcional: o serviço antigo (antes do rastreio de reação) não manda. */
|
||||
export type JudgeOptions = { scanEnabled: boolean; scanIntervalS: number; vision: boolean; camDetect: boolean; faceTrack?: boolean };
|
||||
/** `faceTrack` e `timelineJson` são opcionais: o serviço antigo não manda. `timelineJson` = a IA lê o vídeo como
|
||||
* linha do tempo JSON curta (novo); false = transcrição + chat + frames soltos (antigo, para comparar). */
|
||||
export type JudgeOptions = {
|
||||
scanEnabled: boolean; scanIntervalS: number; vision: boolean; camDetect: boolean; faceTrack?: boolean; timelineJson?: boolean;
|
||||
};
|
||||
|
||||
/** Equipe de IA (doc/clipador/EQUIPE-IA.md): quatro papéis, cada um com a sua IA. */
|
||||
export type AiRoleId = "scan" | "analyst" | "editor" | "judge";
|
||||
export type AiRoleProvider = Exclude<JudgeProvider, "off">;
|
||||
export type AiEffort = "" | "low" | "medium" | "high";
|
||||
export type AiImages = "mosaic" | "frames" | "none";
|
||||
export type ContextCheckId = "setup" | "payoff" | "who_what" | "standalone" | "intelligible" | "faithful" | "strong_open";
|
||||
export type AiRole = {
|
||||
enabled: boolean;
|
||||
provider: AiRoleProvider;
|
||||
/** "" = padrão do provedor. */
|
||||
model: string;
|
||||
/** Raciocínio (só Codex); "" = padrão (baixo). */
|
||||
effort: AiEffort;
|
||||
/** Instruções do administrador, somadas às padrão (podem ser em português). */
|
||||
extra: string;
|
||||
/** Só varredura e analista. */
|
||||
images?: AiImages;
|
||||
// Só o juiz: checagens críticas, se pode ajustar o trecho e pôr frase de contexto, e quanto cada checagem
|
||||
// não crítica tira da nota.
|
||||
critical?: ContextCheckId[];
|
||||
allowFix?: boolean;
|
||||
allowContextLine?: boolean;
|
||||
penalty?: number;
|
||||
/** Só leitura (o serviço calcula): modelo efetivo e a ordem de tentativa (reserva) deste papel. */
|
||||
resolvedModel?: string;
|
||||
chain?: AiRoleProvider[];
|
||||
};
|
||||
export type AiRoles = Record<AiRoleId, AiRole>;
|
||||
export type JudgeConfig = {
|
||||
provider: JudgeProvider;
|
||||
/** Modelo do EDITOR (2º juiz). null com o juiz desligado. */
|
||||
@@ -41,8 +73,37 @@ export type JudgeConfig = {
|
||||
fallback?: { enabled: boolean; cooldownMin: number; chain: Exclude<JudgeProvider, "off">[] };
|
||||
/** IAs em pausa depois de falha de indisponibilidade (`until` em ISO, UTC). */
|
||||
pauses?: JudgePause[];
|
||||
/** Equipe de IA (serviço novo): cada papel com a sua IA. Ausente = serviço antigo (um provedor só). */
|
||||
roles?: AiRoles;
|
||||
/** Instruções padrão de cada papel nos dois idiomas (só leitura). Só em GET/PUT /judge. */
|
||||
roleDefaults?: Record<AiRoleId, { pt: string; en: string }>;
|
||||
/** Checagens do juiz de contexto (id + nome em português). */
|
||||
checks?: { id: ContextCheckId; label: string }[];
|
||||
/** Situação de cada IA (Configurações → IA): ligada, pronta e por que não. */
|
||||
providers?: Partial<Record<AiRoleProvider, { ready: boolean; reason: string | null; enabled: boolean }>>;
|
||||
};
|
||||
|
||||
/** GET /judge/report: medição da Equipe de IA (F0) — chamadas e tokens por papel, decisões do juiz e concordância com você. */
|
||||
export type AiReport = {
|
||||
window: { days: number; since: string | null; sessionId: number | null; liveHours: number };
|
||||
calls: {
|
||||
role: string; purpose: string; provider: string; model: string; mode: string; calls: number; failures: number;
|
||||
avgChars: number; avgImages: number; imageKB: number; tokensIn: number | null; tokensOut: number | null;
|
||||
tokensCached: number | null; withUsage: number; avgMs: number;
|
||||
}[];
|
||||
perHour: Record<string, { calls: number | null; tokensIn: number | null; tokensOut: number | null; estTokensIn: number | null }>;
|
||||
clips: { total: number; byStatus: Partial<Record<ClipStatus, number>>; approvalRate: number | null; labeled: number; noContext: number };
|
||||
judge: { approve: number; adjust: number; discard: number; warn: number; error: number; contextLine: number };
|
||||
agreement: Record<"judge" | "editor", AiAgreement>;
|
||||
};
|
||||
export type AiAgreement = {
|
||||
pairs: number; agree: number; rate: number | null; kappa: number | null;
|
||||
matrix: Record<"keep" | "discard", Record<OwnerLabel, number>>;
|
||||
};
|
||||
|
||||
/** Sua avaliação do corte (conjunto de avaliação do juiz). */
|
||||
export type OwnerLabel = "good" | "bad" | "no_context";
|
||||
|
||||
export type JudgePause = { provider: Exclude<JudgeProvider, "off">; until: string; reason: string };
|
||||
|
||||
export type ClipperChannel = {
|
||||
@@ -173,9 +234,42 @@ export type ClipJudge = null
|
||||
model: string; keep: boolean; score: number; reason: string; analysis?: ClipAnalysis | null; analystModel?: string;
|
||||
/** Fonte em inglês: título, legenda e motivo em português (só para ler; o post sai em inglês). */
|
||||
pt?: { title?: string; caption?: string; reason?: string };
|
||||
/** Juiz de contexto (EQUIPE-IA.md). Ausente = juiz desligado, editor descartou ou corte de antes. */
|
||||
context?: ClipContext;
|
||||
/** "context" = quem descartou foi o juiz de contexto (dá para forçar o render). */
|
||||
discardedBy?: "context";
|
||||
}
|
||||
| { error: string };
|
||||
|
||||
export type ContextCheck = { ok: boolean; t: number | null; why: string };
|
||||
export type ClipContext =
|
||||
| { error: string }
|
||||
| {
|
||||
model: string;
|
||||
/** O que um espectador que nunca viu a live entende (escrito antes das checagens). */
|
||||
viewerSummary: string;
|
||||
checks: Partial<Record<ContextCheckId, ContextCheck>>;
|
||||
fix: { start_s: number | null; end_s: number | null; context_line: string };
|
||||
confidence: number;
|
||||
reason: string;
|
||||
/** Fonte em inglês: resumo, motivo, frase e o porquê de cada checagem em português. */
|
||||
pt?: { viewer_summary?: string; reason?: string; context_line?: string; checks?: Partial<Record<ContextCheckId, string>> };
|
||||
/** O que o código decidiu pelas respostas. */
|
||||
decision: "approve" | "adjust" | "discard" | "warn";
|
||||
failed: ContextCheckId[];
|
||||
failedCritical: ContextCheckId[];
|
||||
solvedByLine: ContextCheckId[];
|
||||
/** Frase de contexto que vai na tela no começo do corte ("" = nenhuma). */
|
||||
contextLine: string;
|
||||
scoreAfter: number | null;
|
||||
/** Motivo da decisão, em português (montado pelo código). */
|
||||
reasonPt: string;
|
||||
/** Trecho novo quando o juiz ajustou. */
|
||||
window?: [number, number];
|
||||
/** 1ª rodada, quando houve ajuste (o juiz conferiu de novo). */
|
||||
first?: { viewerSummary: string; checks: Partial<Record<ContextCheckId, ContextCheck>>; failedCritical: ContextCheckId[]; reasonPt: string };
|
||||
};
|
||||
|
||||
export type ClipTags = { risada?: number; susto?: number; hype?: number; clip?: number };
|
||||
|
||||
export type Clip = {
|
||||
@@ -227,6 +321,9 @@ export type Clip = {
|
||||
final?: ClipFinal | null;
|
||||
/** O único arquivo que vai para as redes: o final pronto. null = ainda não (a publicação espera). */
|
||||
publishFile?: string | null;
|
||||
/** Sua avaliação (bom / ruim / sem contexto) para medir o juiz. Opcional: o serviço antigo não manda. */
|
||||
ownerLabel?: OwnerLabel | null;
|
||||
ownerNote?: string | null;
|
||||
};
|
||||
|
||||
export type ClipFinal = {
|
||||
@@ -525,6 +622,26 @@ export const TAG_LABEL: Record<keyof ClipTags, string> = { risada: "risada", sus
|
||||
|
||||
export const PROVIDER_LABEL: Record<JudgeProvider, string> = { codex: "Codex (GPT)", claude: "Claude", gemini: "Gemini", off: "Desligado" };
|
||||
|
||||
/** Equipe de IA: nome e o que cada papel faz (cartões da configuração). */
|
||||
export const ROLE_INFO: Record<AiRoleId, { label: string; does: string }> = {
|
||||
scan: { label: "Varredura", does: "Assiste a live por janelas e propõe momentos mesmo sem pico de chat; descreve a tela para a linha do tempo." },
|
||||
analyst: { label: "Analista", does: "Olha tela, fala e chat do trecho e diz o que aconteceu (lag, jogada, treta…). Não decide." },
|
||||
editor: { label: "Editor", does: "Decide se vira corte, escolhe o trecho e escreve título, legenda e hashtags." },
|
||||
judge: { label: "Juiz", does: "Só texto: vê o que vai no corte e confere se quem nunca viu a live entende — começo, desfecho, funciona sozinho." },
|
||||
};
|
||||
export const ROLE_ORDER: AiRoleId[] = ["scan", "analyst", "editor", "judge"];
|
||||
export const CHECK_LABEL: Record<ContextCheckId, string> = {
|
||||
setup: "começo (setup)", payoff: "desfecho", who_what: "quem/o quê", standalone: "funciona sozinho",
|
||||
intelligible: "fala clara", faithful: "título fiel", strong_open: "abertura forte",
|
||||
};
|
||||
export const OWNER_LABEL: Record<OwnerLabel, { label: string; tone: Tone }> = {
|
||||
good: { label: "Bom", tone: "success" }, bad: { label: "Ruim", tone: "danger" }, no_context: { label: "Sem contexto", tone: "warning" },
|
||||
};
|
||||
export const CONTEXT_DECISION: Record<"approve" | "adjust" | "discard" | "warn", { label: string; tone: Tone }> = {
|
||||
approve: { label: "aprovou", tone: "success" }, adjust: { label: "ajustou o trecho", tone: "info" },
|
||||
discard: { label: "descartou", tone: "danger" }, warn: { label: "avisou", tone: "warning" },
|
||||
};
|
||||
|
||||
/** Sessões que ainda mudam sozinhas (vale consultar de novo). */
|
||||
export const ACTIVE_SESSION: SessionStatus[] = ["starting", "recording", "processing"];
|
||||
/** Cortes que ainda mudam sozinhos (IA ou render). */
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
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, ClipVideoState, DeleteControl, FaceSignal, JudgeVerdict, TrimControl, situationLabel, type DeleteClip,
|
||||
ChatSignals, ClipActions, ClipMedia, ClipVideoState, DeleteControl, FaceSignal, JudgeVerdict, OwnerLabelControl, TrimControl, situationLabel,
|
||||
type DeleteClip,
|
||||
} from "./clipper-clip-parts";
|
||||
import { isOther, speakerLabel } from "./clip-editor-model";
|
||||
import { Dialog } from "./dialog";
|
||||
@@ -119,6 +120,7 @@ function ClipBody({ clip, onChanged, publishJobs }: { clip: Clip; onChanged: ()
|
||||
|
||||
<section aria-label="Veredito da IA" className="grid gap-3">
|
||||
<JudgeVerdict clip={clip} />
|
||||
<OwnerLabelControl clip={clip} pending={pending} run={run} />
|
||||
</section>
|
||||
|
||||
{clip.status === "error" && clip.error && (
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
// 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, DEV_LAYER_LABEL, FACE_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf, clipperCall, formatClock, formatDuration, formatScore,
|
||||
reviewHasDevLayers,
|
||||
type Clip, type ClipAnalysis, type ClipTags, type Situation, type useClipperAction,
|
||||
ACTIVE_CLIP, CHECK_LABEL, CLIP_STATUS, CONTEXT_DECISION, DEV_LAYER_LABEL, FACE_LABEL, OWNER_LABEL, SITUATION_LABEL, TAG_LABEL, UNDELETABLE_CLIP, aspectOf,
|
||||
clipperCall, formatClock, formatDuration, formatScore, reviewHasDevLayers,
|
||||
type Clip, type ClipAnalysis, type ClipContext, type ClipTags, type ContextCheckId, type OwnerLabel, type Situation, type useClipperAction,
|
||||
} from "./clipper-client";
|
||||
import { ClipPublishButton } from "./clip-publish";
|
||||
import { AlertIcon, CheckIcon, EyeIcon, RefreshIcon, ScissorsIcon, SparkIcon, TrashIcon, UndoIcon, XIcon } from "./icons";
|
||||
@@ -250,10 +250,107 @@ export function JudgeVerdict({ clip }: { clip: Clip }) {
|
||||
</p>
|
||||
{(judge.pt?.reason || judge.reason) && <p className="text-[0.8125rem] leading-relaxed text-fg-muted">{judge.pt?.reason || judge.reason}</p>}
|
||||
</div>
|
||||
{judge.context && <ContextVerdict context={judge.context} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** O JUIZ de contexto (EQUIPE-IA.md): o que um espectador frio entende, as checagens e o que o código decidiu. */
|
||||
export function ContextVerdict({ context }: { context: ClipContext }) {
|
||||
if ("error" in context) {
|
||||
return (
|
||||
<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>O juiz não conseguiu conferir o contexto (ficou a decisão do editor): <span className="break-words">{context.error}</span></span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
const decision = CONTEXT_DECISION[context.decision];
|
||||
const pt = context.pt ?? {};
|
||||
const failed = new Set(context.failed);
|
||||
const checks = Object.entries(context.checks) as [ContextCheckId, { ok: boolean; t: number | null; why: string }][];
|
||||
const summary = pt.viewer_summary || context.viewerSummary;
|
||||
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="inline-flex items-center gap-1.5 font-semibold text-fg"><EyeIcon size={13} />Juiz de contexto</span>
|
||||
<Badge tone={decision.tone} dot={false}>{decision.label}</Badge>
|
||||
{context.window && <span className="text-fg-subtle tabular-nums">trecho {formatClock(context.window[0])}–{formatClock(context.window[1])}</span>}
|
||||
{context.scoreAfter !== null && context.scoreAfter !== undefined && <span className="text-fg-subtle tabular-nums">nota após checagens {formatScore(context.scoreAfter)}</span>}
|
||||
<span className="font-mono text-[0.6875rem] text-fg-subtle">{context.model}</span>
|
||||
</p>
|
||||
{context.reasonPt && <p className="text-[0.8125rem] leading-relaxed text-fg">{context.reasonPt}</p>}
|
||||
{summary && (
|
||||
<p className="text-[0.8125rem] leading-relaxed text-fg-muted">
|
||||
<span className="font-medium text-fg-subtle">Quem nunca viu a live entende: </span>{summary}
|
||||
</p>
|
||||
)}
|
||||
{context.contextLine && (
|
||||
<p className="text-xs text-fg-muted">
|
||||
<span className="font-medium text-fg-subtle">Frase de contexto na tela: </span>“{context.contextLine}”
|
||||
{pt.context_line && pt.context_line !== context.contextLine && <span className="text-fg-subtle"> ({pt.context_line})</span>}
|
||||
</p>
|
||||
)}
|
||||
<details className="text-xs" open={context.decision !== "approve"}>
|
||||
<summary className="cursor-pointer text-fg-subtle select-none hover:text-fg">Checagens ({checks.length - failed.size} de {checks.length} ok)</summary>
|
||||
<ul className="mt-2 grid gap-1.5">
|
||||
{checks.map(([id, check]) => {
|
||||
const critical = context.failedCritical.includes(id);
|
||||
const solved = context.solvedByLine.includes(id);
|
||||
const why = pt.checks?.[id] || check.why;
|
||||
return (
|
||||
<li key={id} className="grid grid-cols-[1rem_minmax(0,1fr)] gap-2">
|
||||
<span aria-hidden="true" className={check.ok ? "text-success" : critical ? "text-danger" : "text-warning"}>
|
||||
{check.ok ? <CheckIcon size={13} /> : <XIcon size={13} />}
|
||||
</span>
|
||||
<span className="leading-relaxed text-fg-muted">
|
||||
<span className="sr-only">{check.ok ? "ok: " : "falhou: "}</span>
|
||||
<span className="font-medium text-fg">{CHECK_LABEL[id] ?? id}</span>
|
||||
{critical && <span className="text-danger"> · crítica</span>}
|
||||
{solved && <span className="text-info"> · resolvida pela frase</span>}
|
||||
{check.t !== null && <span className="text-fg-subtle tabular-nums"> · {formatClock(check.t)}</span>}
|
||||
{why && <> — {why}</>}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
{context.first && (
|
||||
<p className="mt-2 text-fg-subtle">1ª conferência: {context.first.reasonPt}</p>
|
||||
)}
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Sua avaliação do corte (bom / ruim / sem contexto): forma o conjunto que mede o juiz. Não muda o estado do corte. */
|
||||
export function OwnerLabelControl({ clip, pending, run }: { clip: Clip; pending: string | null; run: Run }) {
|
||||
if (clip.ownerLabel === undefined || ACTIVE_CLIP.includes(clip.status)) return null;
|
||||
const set = (label: OwnerLabel | "") => run(`label-${label || "none"}`, () => clipperCall<Clip>(`clips/${clip.id}`, "PATCH", { label }),
|
||||
label ? `Avaliado como “${OWNER_LABEL[label].label}”.` : "Avaliação apagada.");
|
||||
return (
|
||||
<fieldset className="grid gap-1.5">
|
||||
<legend className="text-eyebrow font-semibold text-fg-subtle uppercase">Sua avaliação</legend>
|
||||
<div className="flex flex-wrap items-center gap-1.5" role="group" aria-label="Sua avaliação do corte">
|
||||
{(Object.keys(OWNER_LABEL) as OwnerLabel[]).map((label) => {
|
||||
const on = clip.ownerLabel === label;
|
||||
return (
|
||||
<button key={label} type="button" aria-pressed={on} disabled={pending !== null}
|
||||
onClick={() => void set(on ? "" : label)}
|
||||
className={cx("rounded-full border px-2.5 py-1 text-xs font-medium transition-colors disabled:opacity-60",
|
||||
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-accent",
|
||||
on ? (label === "good" ? "border-success/50 bg-success-soft text-success" : label === "bad" ? "border-danger/50 bg-danger-soft text-danger" : "border-warning/50 bg-warning-soft text-warning")
|
||||
: "border-line-strong text-fg-muted hover:text-fg")}>
|
||||
{pending === `label-${label}` ? <Spinner className="mr-1 inline size-3" /> : null}{OWNER_LABEL[label].label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<p className="text-xs text-fg-subtle">Vale para qualquer corte, inclusive antigos; mede se o juiz concorda com você (Ajustes → Juiz → Medição).</p>
|
||||
</fieldset>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 ?? {};
|
||||
@@ -448,8 +545,8 @@ export function ClipActions({ clip, pending, run, publish, onDecided, className
|
||||
}) {
|
||||
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);
|
||||
const setStatus = async (key: string, status: "approved" | "rejected" | "ready", text: string, label?: OwnerLabel) => {
|
||||
const done = await run(key, () => clipperCall<Clip>(base, "PATCH", { status, ...(label ? { label } : {}) }), text);
|
||||
if (done && status !== "ready") onDecided?.();
|
||||
return done;
|
||||
};
|
||||
@@ -473,6 +570,11 @@ export function ClipActions({ clip, pending, run, publish, onDecided, className
|
||||
<Button variant="secondary" size="sm" disabled={disabled} onClick={() => void setStatus("reject", "rejected", "Corte rejeitado.")}>
|
||||
{icon("reject", <XIcon size={15} />)}Rejeitar
|
||||
</Button>
|
||||
{/* Rejeitar porque não dá para entender sem ter visto a live: o sinal que treina e mede o juiz de contexto. */}
|
||||
<Button variant="ghost" size="sm" disabled={disabled} title="Rejeita e marca “sem contexto” (quem não viu a live não entende)"
|
||||
onClick={() => void setStatus("no-context", "rejected", "Corte rejeitado: sem contexto.", "no_context")}>
|
||||
{icon("no-context", <XIcon size={15} />)}Sem contexto
|
||||
</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>
|
||||
|
||||
@@ -77,6 +77,8 @@ function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, o
|
||||
const language = session?.language;
|
||||
const score = judgeScore(clip);
|
||||
const kept = clip.judge && "keep" in clip.judge ? clip.judge.keep : null;
|
||||
// Descartado pelo juiz de contexto (EQUIPE-IA.md): o editor manteve, o juiz achou que não faz sentido sozinho.
|
||||
const byContextJudge = clip.status === "discarded" && !!clip.judge && "keep" in clip.judge && clip.judge.discardedBy === "context";
|
||||
const situation = situationLabel(clip);
|
||||
const jobs = publishing?.get(String(clip.id)) ?? null;
|
||||
const horizontal = clip.aspect === "horizontal";
|
||||
@@ -154,7 +156,9 @@ function ClipRow({ clip, sessions, stage, nameOf, defaultLanguage, publishing, o
|
||||
<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>}
|
||||
: byContextJudge
|
||||
? <Badge tone="danger" dot={false}>descartado pelo juiz</Badge>
|
||||
: <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">
|
||||
|
||||
@@ -1,162 +1,140 @@
|
||||
"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 do PC; login, chave de API e IA
|
||||
// reserva ficam em Configurações → IA (/settings/ai, contrato em doc/ia.md).
|
||||
// IA do Clipador: liga/desliga, a Equipe de IA (varredura, analista, editor e juiz — cada papel com a sua IA,
|
||||
// clipper-ai-team.tsx), nota mínima e o que a IA faz sozinha (varredura, visão, câmera, linha do tempo). 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 { AiTeam, AiTeamReport } from "./clipper-ai-team";
|
||||
import {
|
||||
PROVIDER_LABEL, clipperCall, formatScore, useClipperAction, type JudgeConfig, type JudgeOptions, type JudgeProvider,
|
||||
PROVIDER_LABEL, clipperCall, formatScore, useClipperAction, type AiRoles, type JudgeConfig, type JudgeOptions,
|
||||
} from "./clipper-client";
|
||||
import { DescribedSelect } from "./forms";
|
||||
import { AlertIcon, EyeIcon, SparkIcon } from "./icons";
|
||||
import { Badge, Button, Card, ChoiceGroup, Feedback, RangeField, Spinner, Switch } from "./ui";
|
||||
import { Badge, Button, Card, Feedback, RangeField, Spinner, Switch } from "./ui";
|
||||
|
||||
const OPTION_DEFAULTS: JudgeOptions = { scanEnabled: true, scanIntervalS: 180, vision: true, camDetect: true, faceTrack: true };
|
||||
|
||||
export function JudgeForm({ judge, onSaved }: { judge: JudgeConfig; onSaved: (next: JudgeConfig) => void }) {
|
||||
const savedOptions = judge.options ?? OPTION_DEFAULTS;
|
||||
const [provider, setProvider] = useState<JudgeProvider>(judge.provider);
|
||||
const [model, setModel] = useState(judge.model ?? "");
|
||||
// O serviço devolve o analista resolvido: igual ao editor = "" (segue o editor).
|
||||
const savedAnalyst = judge.analystModel && judge.analystModel !== judge.model ? judge.analystModel : "";
|
||||
const [analyst, setAnalyst] = useState(savedAnalyst);
|
||||
const [enabled, setEnabled] = useState(judge.provider !== "off");
|
||||
const [roles, setRoles] = useState<AiRoles | null>(judge.roles ?? null);
|
||||
const [minScore, setMinScore] = useState(judge.minScore);
|
||||
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] ?? "";
|
||||
// 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 : "";
|
||||
const savedModel = models.some((m) => m.id === judge.model) ? judge.model ?? "" : "";
|
||||
const analystChanged = provider !== judge.provider || currentAnalyst !== (models.some((m) => m.id === savedAnalyst) ? savedAnalyst : "");
|
||||
const dirty = provider !== judge.provider || (provider !== "off" && (currentModel !== savedModel || analystChanged))
|
||||
const off = !enabled;
|
||||
// O cartão da varredura liga/desliga a varredura (é a mesma opção `scanEnabled`).
|
||||
const scanOn = roles ? roles.scan.enabled : options.scanEnabled;
|
||||
const dirty = enabled !== (judge.provider !== "off") || JSON.stringify(roles) !== JSON.stringify(judge.roles ?? null)
|
||||
|| minScore !== judge.minScore || JSON.stringify(options) !== JSON.stringify(savedOptions);
|
||||
const off = provider === "off";
|
||||
const setOption = (values: Partial<JudgeOptions>) => setOptions((o) => ({ ...o, ...values }));
|
||||
const scansPerHour = Math.round(3600 / options.scanIntervalS);
|
||||
|
||||
async function save() {
|
||||
// O serviço antigo só entende um provedor: vai o do editor (a IA "principal"); o novo usa `roles`.
|
||||
const provider = off ? "off" : roles?.editor.provider ?? (judge.provider === "off" ? "codex" : judge.provider);
|
||||
const next = await run("save", () => clipperCall<JudgeConfig>("judge", "PUT", {
|
||||
provider, model: currentModel, minScore,
|
||||
...(off ? {} : { analystModel: currentAnalyst }),
|
||||
...(judge.options ? options : {}),
|
||||
}), (j) => j.provider === "off" ? "Juiz desligado: só a heurística do chat decide." : `Juiz salvo: ${PROVIDER_LABEL[j.provider]} · ${j.model}.`);
|
||||
provider, model: roles?.editor.model ?? judge.model ?? "", minScore,
|
||||
...(roles ? { roles } : {}),
|
||||
...(judge.options ? { ...options, scanEnabled: scanOn } : {}),
|
||||
}), (j) => j.provider === "off" ? "IA desligada: só a heurística do chat decide." : "Equipe de IA salva.");
|
||||
if (next) onSaved(next);
|
||||
}
|
||||
|
||||
const modelOptions = [
|
||||
{ value: "", label: `Padrão do provedor (${fallback})`, description: "Usa o modelo recomendado; troca sozinho se o padrão mudar." },
|
||||
...models.map((m) => ({ value: m.id, label: m.label, description: m.description })),
|
||||
];
|
||||
|
||||
return (
|
||||
<Card eyebrow={<><SparkIcon size={13} />Juiz (IA)</>}
|
||||
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="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 pela CLI do Codex ou do Claude
|
||||
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: "off", label: "Desligado", hint: "só heurística" },
|
||||
]} />
|
||||
<div className="grid gap-6">
|
||||
<Card eyebrow={<><SparkIcon size={13} />IA do Clipador</>}
|
||||
title={<span className="flex flex-wrap items-center gap-3">
|
||||
Quem decide o que vira corte
|
||||
{judge.provider === "off" ? <Badge>desligada</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={<>Uma equipe de IAs confirma o momento, escreve título e legenda e confere se o corte faz sentido sozinho. Roda pela CLI
|
||||
do Codex ou do Claude 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(); }}>
|
||||
<Switch label="Usar IA" checked={enabled} onChange={setEnabled}
|
||||
hint={enabled ? "A equipe abaixo avalia cada momento." : "Sem IA, todo pico do chat acima do limiar vira corte, com título tirado da transcrição. Mais rápido, mas sem filtro de qualidade, sem varredura e sem visão."} />
|
||||
|
||||
{off ? (
|
||||
<p className="text-sm leading-relaxed text-fg-muted">
|
||||
Sem juiz, todo pico do chat acima do limiar vira corte, com título tirado da transcrição. Mais rápido, mas sem filtro de qualidade, sem varredura e sem visão.
|
||||
</p>
|
||||
) : (
|
||||
<section aria-labelledby="dois-juizes" className="grid gap-4">
|
||||
<div className="grid gap-1">
|
||||
<h3 id="dois-juizes" className="text-sm font-semibold text-fg">Dois juízes</h3>
|
||||
<p className="max-w-[80ch] text-[0.8125rem] leading-relaxed text-fg-muted">
|
||||
O <strong className="text-fg">analista</strong> vê os frames da tela, a fala e o chat e descreve o que aconteceu (lag, jogada, treta…).
|
||||
O <strong className="text-fg">editor</strong> decide se vira corte e escreve título e legenda a partir disso.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<DescribedSelect name="analystModel" label="Analista (1º juiz, vê a tela)" value={currentAnalyst} onChange={setAnalyst}
|
||||
options={[{ value: "", label: "Igual ao editor", description: "Usa o mesmo modelo do editor." }, ...modelOptions.slice(1)]} />
|
||||
<DescribedSelect name="model" label="Editor (2º juiz, decide e escreve)" value={currentModel} onChange={setModel} options={modelOptions} />
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{roles ? (
|
||||
<AiTeam judge={judge} roles={roles} disabled={off} onChange={setRoles} />
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-xs text-fg-subtle"><EyeIcon size={14} />A Equipe de IA (uma IA por papel) aparece quando o Clipador for reiniciado com a versão nova.</p>
|
||||
)}
|
||||
|
||||
<RangeField label="Nota mínima para virar corte" min={0} max={10} step={0.5} value={minScore} onChange={setMinScore}
|
||||
disabled={off} format={(v) => `${formatScore(v)} / 10`} className="max-w-xl"
|
||||
hint="Momentos com nota abaixo disso vão para “Descartados pela IA” (dá para forçar o render de lá)." />
|
||||
<RangeField label="Nota mínima para virar corte" min={0} max={10} step={0.5} value={minScore} onChange={setMinScore}
|
||||
disabled={off} format={(v) => `${formatScore(v)} / 10`} className="max-w-xl"
|
||||
hint="Momentos com nota abaixo disso vão para “Descartados pela IA” (dá para forçar o render de lá)." />
|
||||
|
||||
{judge.options ? (
|
||||
<fieldset disabled={off} className="grid gap-5 rounded-card border border-line bg-sunken/30 p-5 disabled:opacity-50">
|
||||
<legend className="px-1 text-sm font-semibold text-fg">O que a IA faz sozinha</legend>
|
||||
<div className="grid gap-5 lg:grid-cols-2">
|
||||
<div className="grid content-start gap-3">
|
||||
<Switch label="Varredura" checked={options.scanEnabled} onChange={(scanEnabled) => setOption({ scanEnabled })}
|
||||
hint="A cada N segundos de gravação a IA assiste a janela (tela + fala + chat) e propõe momentos mesmo sem pico de chat. Essencial em live pequena." />
|
||||
<RangeField label="Intervalo da varredura" min={60} max={900} step={30} value={options.scanIntervalS}
|
||||
onChange={(scanIntervalS) => setOption({ scanIntervalS })} disabled={!options.scanEnabled}
|
||||
format={(v) => (v % 60 === 0 ? `${v / 60} min` : `${Math.floor(v / 60)} min ${v % 60} s`)}
|
||||
hint={`Cerca de ${scansPerHour} chamada${scansPerHour === 1 ? "" : "s"} à IA por hora de live.`} />
|
||||
{judge.options ? (
|
||||
<fieldset disabled={off} className="grid gap-5 rounded-card border border-line bg-sunken/30 p-5 disabled:opacity-50">
|
||||
<legend className="px-1 text-sm font-semibold text-fg">O que a IA faz sozinha</legend>
|
||||
<div className="grid gap-5 lg:grid-cols-2">
|
||||
<div className="grid content-start gap-3">
|
||||
{!roles && (
|
||||
<Switch label="Varredura" checked={options.scanEnabled} onChange={(scanEnabled) => setOption({ scanEnabled })}
|
||||
hint="A cada N segundos de gravação a IA assiste a janela (tela + fala + chat) e propõe momentos mesmo sem pico de chat. Essencial em live pequena." />
|
||||
)}
|
||||
<RangeField label="Intervalo da varredura" min={60} max={900} step={30} value={options.scanIntervalS}
|
||||
onChange={(scanIntervalS) => setOption({ scanIntervalS })} disabled={!scanOn}
|
||||
format={(v) => (v % 60 === 0 ? `${v / 60} min` : `${Math.floor(v / 60)} min ${v % 60} s`)}
|
||||
hint={`Cerca de ${scansPerHour} chamada${scansPerHour === 1 ? "" : "s"} à IA por hora de live.`} />
|
||||
{options.timelineJson !== undefined && (
|
||||
<Switch label="Linha do tempo em JSON (novo)" checked={options.timelineJson} onChange={(timelineJson) => setOption({ timelineJson })}
|
||||
hint="A IA lê o vídeo como uma linha curta por instante (fala, chat, rosto, volume e o que está na tela) e vê o mosaico. Desligado = o formato antigo (transcrição + chat + quadros soltos), para comparar." />
|
||||
)}
|
||||
</div>
|
||||
<div className="grid content-start gap-4">
|
||||
<Switch label="Visão" checked={options.vision} onChange={(vision) => setOption({ vision })}
|
||||
hint="Manda a tela para a IA (mosaico ou quadros, como escolhido em cada papel). Sem visão, ela julga só pela fala e pelo chat." />
|
||||
<Switch label="Achar a câmera automaticamente" checked={options.camDetect} onChange={(camDetect) => setOption({ camDetect })}
|
||||
hint="No início de cada sessão o Clipador procura o rosto do streamer no quadro (sem gastar IA) e monta o layout com câmera em cima. A IA só olha se ele não achar." />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid content-start gap-4">
|
||||
<Switch label="Visão" checked={options.vision} onChange={(vision) => setOption({ vision })}
|
||||
hint="Manda frames da tela para a IA. Sem visão, ela julga só pela fala e pelo chat." />
|
||||
<Switch label="Achar a câmera automaticamente" checked={options.camDetect} onChange={(camDetect) => setOption({ camDetect })}
|
||||
hint="No início de cada sessão o Clipador procura o rosto do streamer no quadro (sem gastar IA) e monta o layout com câmera em cima. A IA só olha se ele não achar." />
|
||||
</div>
|
||||
</div>
|
||||
{judge.lastScanError && (
|
||||
<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>Última varredura falhou: <span className="break-words">{judge.lastScanError}</span></span>
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-xs text-fg-subtle"><EyeIcon size={14} />Varredura, visão e câmera automática aparecem quando o Clipador for reiniciado com a versão nova.</p>
|
||||
)}
|
||||
{judge.lastScanError && (
|
||||
<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>Última varredura falhou: <span className="break-words">{judge.lastScanError}</span></span>
|
||||
</p>
|
||||
)}
|
||||
</fieldset>
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-xs text-fg-subtle"><EyeIcon size={14} />Varredura, visão e câmera automática aparecem quando o Clipador for reiniciado com a versão nova.</p>
|
||||
)}
|
||||
|
||||
{/* Rastreio de reação roda no PC (MediaPipe), sem IA: vale mesmo com o juiz desligado. */}
|
||||
{judge.options && options.faceTrack !== undefined && (
|
||||
<div className="max-w-xl">
|
||||
<Switch label="Rastrear a reação do streamer" checked={options.faceTrack} onChange={(faceTrack) => setOption({ faceTrack })}
|
||||
hint="Segue o rosto na webcam (risada, grito, susto, confusão) no próprio PC, sem gastar IA. Reforça os cortes do chat, cria corte quando o rosto reage junto com o áudio ou o chat e conta ao analista o que o streamer fez." />
|
||||
{/* Rastreio de reação roda no PC (MediaPipe), sem IA: vale mesmo com a IA desligada. */}
|
||||
{judge.options && options.faceTrack !== undefined && (
|
||||
<div className="max-w-xl">
|
||||
<Switch label="Rastrear a reação do streamer" checked={options.faceTrack} onChange={(faceTrack) => setOption({ faceTrack })}
|
||||
hint="Segue o rosto na webcam (risada, grito, susto, confusão) no próprio PC, sem gastar IA. Reforça os cortes do chat, cria corte quando o rosto reage junto com o áudio ou o chat e conta à IA o que o streamer fez." />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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 para o editor.
|
||||
</Feedback>
|
||||
)}
|
||||
{judge.provider !== "off" && judge.available && judge.unavailableReason && (
|
||||
<Feedback ok={false}>
|
||||
{PROVIDER_LABEL[judge.provider]} (editor): {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} />}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Button type="submit" disabled={pending !== null || !dirty}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar"}</Button>
|
||||
{!dirty && <span className="text-xs text-fg-subtle">Nada mudou.</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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.
|
||||
</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">
|
||||
<Button type="submit" disabled={pending !== null || !dirty}>{pending === "save" ? <><Spinner />Salvando…</> : "Salvar juiz"}</Button>
|
||||
{!dirty && <span className="text-xs text-fg-subtle">Nada mudou.</span>}
|
||||
</div>
|
||||
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||||
</form>
|
||||
</Card>
|
||||
<div aria-live="polite" className="empty:hidden">{message && <Feedback ok={message.ok}>{message.text}</Feedback>}</div>
|
||||
</form>
|
||||
</Card>
|
||||
{judge.roles && <AiTeamReport />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Linha discreta com a cadeia de reserva efetiva e as IAs em pausa (só aparece se o serviço mandar). */
|
||||
/** Linha discreta com as IAs em pausa e a reserva (a ordem de cada papel aparece no cartão dele). */
|
||||
function FallbackLine({ judge }: { judge: JudgeConfig }) {
|
||||
const fb = judge.fallback;
|
||||
const pauses = judge.pauses ?? [];
|
||||
@@ -167,8 +145,8 @@ function FallbackLine({ judge }: { judge: JudgeConfig }) {
|
||||
{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.</>}
|
||||
? <>IA reserva ligada · pausa de {fb.cooldownMin} min depois de falha.</>
|
||||
: <>IA reserva desligada: cada papel usa só a IA escolhida.</>}
|
||||
</p>
|
||||
)}
|
||||
{pauses.map((p) => (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"use client";
|
||||
// Ajustes do Clipador (/clipper/settings), em abas: Juiz (IA) — provedor, modelos e o que a IA faz sozinha;
|
||||
// Ajustes do Clipador (/clipper/settings), em abas: Juiz (IA) — Equipe de IA (uma IA por papel), medição 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";
|
||||
@@ -39,7 +39,7 @@ function JudgeTab() {
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
return <JudgeForm key={JSON.stringify([judge.provider, judge.model, judge.minScore, judge.available])} judge={judge} onSaved={setJudge} />;
|
||||
return <JudgeForm key={JSON.stringify([judge.provider, judge.model, judge.minScore, judge.available, judge.roles, judge.options])} judge={judge} onSaved={setJudge} />;
|
||||
}
|
||||
|
||||
/* ---------- Serviço ---------- */
|
||||
|
||||
@@ -33,8 +33,9 @@ function serviceUrl(pathname: string): { url: string; key: string } {
|
||||
* vídeo final (doc/clipador/REVISAO.md): POST clips/id/final · tradução da fala (IDIOMAS.md): POST clips/id/translate
|
||||
* vozes da sessão (FALANTES.md): GET sessions/id/speakers
|
||||
* apagar cortes: DELETE clips/id · POST clips/delete (lote) — o método é conferido em METHODS
|
||||
* medição da Equipe de IA (EQUIPE-IA.md): GET judge/report
|
||||
*/
|
||||
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)?|speakers))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest|final|translate))?))?)$/;
|
||||
const ALLOWED = /^(status|judge(\/report)?|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)?|speakers))?)?|clips(\/(delete|\d{1,9}(\/(render|rejudge|edit|proxy|waveform|export|preview-render|retranscribe|tts|suggest|final|translate))?))?)$/;
|
||||
|
||||
/** Métodos aceitos nos caminhos de apagar corte (os demais caminhos seguem só pela regex acima). */
|
||||
const METHODS: [RegExp, string[]][] = [
|
||||
@@ -43,6 +44,7 @@ const METHODS: [RegExp, string[]][] = [
|
||||
[/^clips\/\d{1,9}\/final$/, ["POST"]],
|
||||
[/^clips\/\d{1,9}\/translate$/, ["POST"]],
|
||||
[/^sessions\/\d{1,9}\/speakers$/, ["GET"]],
|
||||
[/^judge\/report$/, ["GET"]],
|
||||
// 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"]],
|
||||
|
||||
Reference in New Issue
Block a user