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:
+40
-6
@@ -2,7 +2,7 @@
|
||||
|
||||
Serviço local do CenaForge (`127.0.0.1:4520`, faixa 4500–4599) que assiste lives da **Twitch, YouTube e Kick**,
|
||||
lê o **chat em tempo real**, transcreve a fala com o **Whisper** (serviço de voz, 4510), pede a uma **IA pela CLI**
|
||||
(Codex/GPT por padrão, ou Claude) que confirme o momento e gera **cortes com legenda queimada**: verticais 1080×1920
|
||||
(Codex/GPT por padrão, Claude ou Gemini) que confirme o momento e gera **cortes com legenda queimada**: verticais 1080×1920
|
||||
(Shorts/Reels/TikTok, padrão) ou horizontais 1920×1080 (YouTube "tela grande", mostrando o próprio jogo).
|
||||
O painel (`/clipper`) mostra a fila para aprovar. As contas que recebem os cortes de cada canal são ligadas na
|
||||
página **Contas**, como as histórias.
|
||||
@@ -60,6 +60,16 @@ chegar (`wall_end`), então a pausa do Streamlink ao filtrar anúncio da Twitch
|
||||
teto de 45 s além dele (passou disso, mostra "aguardando o bloco"); "Agora na live" mostra a contagem para o próximo
|
||||
resumo da varredura, com o intervalo vindo de `GET /v1/status` → `judge.options.scanIntervalS`.
|
||||
|
||||
**Parar é parar (18/11/2026).** `POST /v1/sessions/{id}/stop` à mão pausa o monitor da fonte
|
||||
(`channels.monitor_paused_at` + `monitor_paused_session`): o monitor não abre sessão nova enquanto a live continuar
|
||||
no ar. Religa com `PATCH /v1/channels/{id}` `{monitor: true}`, gravando pelo link (`POST /v1/sessions`) ou retomando
|
||||
a sessão pelo painel. `{"pauseMonitor": false}` no corpo do stop mantém o monitor ligado. Queda de live (captura cai
|
||||
sozinha) continua retomando **na mesma sessão** (`keep_live`), sem passar pela pausa.
|
||||
|
||||
**Idioma por fonte e por sessão.** `language` em `channels` e `sessions` (`pt-BR`, `en-US`, `es-419`; vazio = `CLIPPER_LANGUAGE`).
|
||||
A sessão herda o da fonte; a transcrição manda esse idioma ao Whisper e, fora de pt-BR, o contexto do editor e da
|
||||
varredura ganha a linha "Idioma de saída: …" (título, legenda e hashtags no idioma do público).
|
||||
|
||||
## Contexto do jogo
|
||||
|
||||
- Categoria da plataforma (Streamlink `--json`, `metadata.category`) no início e a cada 10 min (troca registrada em
|
||||
@@ -68,6 +78,17 @@ resumo da varredura, com o intervalo vindo de `GET /v1/status` → `judge.option
|
||||
- **Perfil do jogo** pesquisado na web pela CLI (`codex --search`), guardado por jogo (tabela `games`): resumo,
|
||||
mecânicas, o que rende corte, o que não rende, gírias, novidades, fontes. Medido: ~15–35 s por jogo.
|
||||
- Correção manual: `PUT /v1/sessions/{id}/game` (trava a troca automática).
|
||||
- **Dois idiomas** (v12, `doc/clipador/JOGOS.md`): a pesquisa é feita e guardada **em inglês** (`profile_ai_json`,
|
||||
é o que vai nos prompts) e traduzida para **português** (`profile_json`, o que o painel mostra). Editar à mão
|
||||
(`PUT /v1/games/{id}?lang=pt|en`) ou pedir à IA (`refine`, resposta em português) atualiza um e traduz o outro;
|
||||
jogo antigo ganha a versão em inglês com `POST /v1/games/{id}/translate`.
|
||||
- O perfil tem **missões** (só se a lista for pública; nunca inventadas) com **gatilhos de fim** e sinais gerais de
|
||||
fim de missão (`end_triggers`). O contexto leva até 25 missões (~1500 caracteres) e manda terminar o corte de
|
||||
missão logo depois do gatilho. **Outros nomes** (`aliases`): categoria "Grand Theft Auto VI" e tela "GTA 6" caem
|
||||
no mesmo perfil.
|
||||
- Cadastrar pelo painel: `POST /v1/games {name, notes?}` (pesquisa em segundo plano; 409 se já existe, inclusive por
|
||||
outro nome) · apagar: `DELETE /v1/games/{id}`. **Sementes** em `app/seeds/games/*.json` (ex.: GTA VI) entram na
|
||||
subida só se o jogo ainda não existe; nunca sobrescrevem a sua edição.
|
||||
|
||||
## Configuração do corte (layout, câmera, legenda)
|
||||
|
||||
@@ -348,14 +369,15 @@ Validação forte (`editor.validate_project`): limites de duração (3–180 s)
|
||||
tentativa em 5 min.
|
||||
- **API**: `GET /v1/sessions/{id}/face?from=&to=` (série, `signal`, picos, câmera, progresso) e `POST …/face/reset`.
|
||||
|
||||
## Juiz de IA (pela CLI, sem chave de API)
|
||||
## Juiz de IA (pela CLI)
|
||||
|
||||
Usa as CLIs já logadas no PC — as mesmas da página Agente:
|
||||
Usa as CLIs do PC — as mesmas da página Agente:
|
||||
|
||||
| Provedor | Comando | Modelo padrão | Lista de modelos |
|
||||
|---|---|---|---|
|
||||
| `codex` (padrão) | `codex exec --ephemeral --sandbox read-only --output-schema … -o … -` | `gpt-6-luna` (rápido e barato) | `~/.codex/models_cache.json` (só `visibility: list`) |
|
||||
| `claude` | `claude -p --json-schema … --no-session-persistence` (imagens pela ferramenta Read; web por WebSearch) | `haiku` | `haiku`, `sonnet`, `opus` |
|
||||
| `gemini` | `gemini -p … -o json --approval-mode plan --skip-trust -m …` (schema no prompt; imagens por `@arquivo`) | `gemini-3.5-flash` | `gemini-3.5-flash`, `gemini-3.1-flash-lite`, `gemini-2.5-pro` |
|
||||
| `off` | — | — | só a heurística |
|
||||
|
||||
Codex: imagens com `-i` (uma por flag, antes de `-`), busca na web com `--search` (opção global, antes de `exec`).
|
||||
@@ -364,6 +386,18 @@ Provedor, modelo do editor, **modelo do analista** (`analystModel`, vazio = o me
|
||||
reiniciar. O `.env` só dá os valores iniciais. Medido (16/11/2026): `gpt-6-luna` respondeu em ~7 s por candidato.
|
||||
Falha do juiz não perde o momento: o corte segue pela heurística e o erro fica em `judge.error`.
|
||||
|
||||
**Gemini, login/chave e IA reserva (18/11/2026)** — contrato em [`doc/ia.md`](../doc/ia.md). O painel
|
||||
(Configurações → IA) grava `data/ai/settings.json` (IAs ligadas, `authMode` `oauth`/`apiKey`, `order`, `fallback`) e
|
||||
`data/ai/vault.bin` (chaves, DPAPI do usuário); o Clipador só lê (`app/ai_settings.py`, relê pelo mtime) e monta o
|
||||
`env` de cada chamada (a chave só vale para aquela chamada). Se a IA escolhida falhar por **indisponibilidade**
|
||||
(cota, 429/529/503, login/chave, rede, CLI ausente, tempo esgotado — `judge.is_availability_error`), a próxima da
|
||||
`order` ligada, com CLI e com chave tenta com o **modelo padrão dela**, e a que caiu fica em pausa `cooldownMin` (em
|
||||
memória). Erro de conteúdo (JSON inválido, campo faltando) não troca. `judge.model` do corte = quem de fato
|
||||
respondeu; `GET /v1/judge` traz `fallback.chain`, `pauses` e `unavailableReason`. Gemini: sem `--output-schema`, o
|
||||
JSON é extraído da resposta; o corpo vai pelo stdin e o `-p` leva só a instrução curta e os `@frame-NN.jpg`; roda
|
||||
numa pasta temporária FORA do repo (o `@arquivo` respeita o .gitignore, que ignora `data/`), com as imagens copiadas.
|
||||
OAuth do Gemini para conta pessoal foi encerrado pelo Google: use chave de API do AI Studio.
|
||||
|
||||
## Instalação e subida
|
||||
|
||||
- `setup.bat` cria `clipper/.venv` (Python 3.12 via uv), instala `requirements.txt` (Streamlink 8.6.3) e gera
|
||||
@@ -386,7 +420,7 @@ Precisa do FFmpeg com `libass` (legenda) — o build `essentials` do gyan.dev te
|
||||
| `CLIPPER_SEGMENT_S` | 30 | tamanho do bloco gravado |
|
||||
| `CLIPPER_POLL_S` | 60 | intervalo para checar se um canal monitorado entrou ao vivo |
|
||||
| `CLIPPER_KEEP_HOURS` | 6 | apaga blocos mais velhos que isto se nenhum corte pendente precisar (0 = nunca) |
|
||||
| `CLIPPER_LANGUAGE` | `pt-BR` | idioma da transcrição |
|
||||
| `CLIPPER_LANGUAGE` | `pt-BR` | idioma padrão da transcrição e dos textos da IA (cada fonte/sessão pode ter o seu: `language`) |
|
||||
| `CLIPPER_ENCODER` | `auto` | `auto` (NVENC se houver) · `libx264` · `h264_nvenc` |
|
||||
| `CLIPPER_JUDGE_PROVIDER` / `_MODEL` / `_MIN_SCORE` | `codex` / (padrão) / 6 | valores iniciais do juiz |
|
||||
| `CLIPPER_DATA_DIR` | `data/clipper` | banco, blocos gravados, modelos do rastreio e arquivos do juiz; para isolar uma instância de teste (relativo ao repo ou absoluto, **dentro** do repo) |
|
||||
@@ -410,8 +444,8 @@ chave `clipper-<sessão>-<bloco>`; num banco novo as sessões recomeçam do 1 e
|
||||
| `GET /v1/sessions/{id}/face?from=&to=` · `POST …/face/reset` | série por segundo do rosto (cx/cy/size no quadro inteiro, expressões, `signal`) e picos; refazer o rastreio |
|
||||
| `PUT /v1/sessions/{id}/game` · `GET /v1/games` · `POST /v1/games/{id}/research` · `PUT /v1/games/{id}` · `POST /v1/games/{id}/refine` · `DELETE /v1/games/{id}/notes/{n}` | jogo da sessão, perfis pesquisados, edição à mão e pedidos à IA |
|
||||
| `GET /v1/emotes?channel=twitch-<login>` | emotes do canal, usos e peso aprendido |
|
||||
| `GET/POST /v1/channels` · `PATCH/DELETE /v1/channels/{id}` · `POST /v1/channels/{id}/check` | canais (`monitor` grava sozinho ao entrar ao vivo; `authorized` = streamer autorizou) |
|
||||
| `GET/POST /v1/sessions` · `GET/DELETE /v1/sessions/{id}` · `POST …/stop` | gravar live ou processar VOD pelo link; cada sessão traz `capture` (resolução, qps, codec e taxa gravados de fato; `null` = sessão antiga) |
|
||||
| `GET/POST /v1/channels` · `PATCH/DELETE /v1/channels/{id}` · `POST /v1/channels/{id}/check` | canais (`monitor` grava sozinho ao entrar ao vivo; `authorized` = streamer autorizou; `language`; `monitorPausedAt`/`monitorPausedBySession` = monitor pausado porque você parou uma sessão; `PATCH {monitor: true}` religa) |
|
||||
| `GET/POST /v1/sessions` · `GET/DELETE /v1/sessions/{id}` · `POST …/stop` `{pauseMonitor?: true}` | gravar live ou processar VOD pelo link (`language` opcional; herda o da fonte); parar à mão pausa o monitor da fonte; cada sessão traz `language` e `capture` (resolução, qps, codec e taxa gravados de fato; `null` = sessão antiga) |
|
||||
| `GET /v1/sessions/{id}/timeline` | mensagens/s, razão do chat e volume por segundo |
|
||||
| `POST /v1/sessions/{id}/clips` | **cortar agora**: `{lastS}` ou `{startS,endS}`; corte manual nunca é descartado pela IA |
|
||||
| `GET /v1/clips?status=&session=` · `GET/PATCH /v1/clips/{id}` · `POST …/render` · `POST …/rejudge` | fila de cortes; cada corte traz `aspect` (`vertical` ou `horizontal`) = formato em que o arquivo foi renderizado |
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Configuração das IAs (Claude, Codex, Gemini) compartilhada com o painel — contrato em `doc/ia.md`.
|
||||
|
||||
O painel (Configurações → IA) escreve dois arquivos em `data/ai/`; o Clipador só LÊ:
|
||||
- `settings.json` (sem segredo): quais IAs estão ligadas, modo de login (`oauth`/`apiKey`), ordem da reserva e
|
||||
pausa depois de uma falha de indisponibilidade. Relido quando o `mtime` muda; ausente/inválido = padrão.
|
||||
- `vault.bin`: as chaves de API, JSON cifrado com a DPAPI do Windows (usuário atual, entropia própria).
|
||||
|
||||
Daqui sai o ambiente (`env`) de cada chamada de CLI: no modo chave, a variável da chave só vale para a chamada;
|
||||
no modo login, a variável é removida para a CLI usar a sessão já logada. O login global de cada CLI não muda.
|
||||
|
||||
Nos testes, a pasta e o cifrador são injetados (`AiConfig(folder, cipher=...)`); a DPAPI real só existe no Windows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Protocol
|
||||
|
||||
from .config import REPO_ROOT
|
||||
|
||||
log = logging.getLogger("cenaforge_clipper.ai_settings")
|
||||
|
||||
AI_PROVIDERS = ("claude", "codex", "gemini")
|
||||
# Pasta padrão dos arquivos do painel. Os testes trocam (conftest) para não ler o data/ai real.
|
||||
DEFAULT_AI_DIR = REPO_ROOT / "data" / "ai"
|
||||
AUTH_MODES = ("oauth", "apiKey")
|
||||
DEFAULT_COOLDOWN_MIN = 15.0
|
||||
DEFAULT_SETTINGS: dict = {
|
||||
"version": 1,
|
||||
"providers": {
|
||||
"claude": {"enabled": True, "authMode": "oauth"},
|
||||
"codex": {"enabled": True, "authMode": "oauth"},
|
||||
"gemini": {"enabled": False, "authMode": "apiKey"},
|
||||
},
|
||||
"order": ["claude", "codex", "gemini"],
|
||||
"fallback": {"enabled": True, "cooldownMin": DEFAULT_COOLDOWN_MIN},
|
||||
}
|
||||
# Variável de ambiente da chave de API de cada CLI (tabela "Ambiente de cada chamada" do doc/ia.md).
|
||||
API_KEY_ENV = {"claude": "ANTHROPIC_API_KEY", "codex": "CODEX_API_KEY", "gemini": "GEMINI_API_KEY"}
|
||||
GEMINI_OAUTH_ENV = "GOOGLE_GENAI_USE_GCA"
|
||||
|
||||
# Entropia do cofre de IA (a mesma que o painel usa ao cifrar). Não é senha: só separa este cofre dos outros.
|
||||
_VAULT_ENTROPY = b"CenaForge.AI.vault.v1"
|
||||
|
||||
|
||||
class AiVaultError(RuntimeError):
|
||||
"""O cofre de IA não abriu (outro usuário/máquina, corrompido, ou DPAPI indisponível)."""
|
||||
|
||||
|
||||
class Cipher(Protocol):
|
||||
def unprotect(self, data: bytes) -> bytes: ...
|
||||
|
||||
|
||||
class DpapiCipher:
|
||||
"""DPAPI via ctypes (crypt32.dll), só a decifragem — quem cifra é o painel. Mesmo padrão de
|
||||
`publisher/app/vault.py` (pacotes separados: o código é copiado, não importado)."""
|
||||
|
||||
CRYPTPROTECT_UI_FORBIDDEN = 0x01
|
||||
|
||||
def __init__(self, entropy: bytes = _VAULT_ENTROPY) -> None:
|
||||
if sys.platform != "win32":
|
||||
raise AiVaultError("O cofre de IA usa a DPAPI do Windows; este sistema não tem.")
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
class DataBlob(ctypes.Structure):
|
||||
_fields_ = [("cbData", wintypes.DWORD), ("pbData", ctypes.POINTER(ctypes.c_char))]
|
||||
|
||||
self._entropy = entropy
|
||||
self._ctypes = ctypes
|
||||
self._blob = DataBlob
|
||||
self._crypt32 = ctypes.WinDLL("crypt32", use_last_error=True)
|
||||
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self._kernel32.LocalFree.argtypes = [ctypes.c_void_p]
|
||||
self._kernel32.LocalFree.restype = ctypes.c_void_p
|
||||
fn = self._crypt32.CryptUnprotectData
|
||||
fn.argtypes = [ctypes.POINTER(DataBlob), ctypes.c_void_p, ctypes.POINTER(DataBlob), ctypes.c_void_p,
|
||||
ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(DataBlob)]
|
||||
fn.restype = wintypes.BOOL
|
||||
|
||||
def _to_blob(self, data: bytes):
|
||||
buffer = self._ctypes.create_string_buffer(data, len(data))
|
||||
blob = self._blob(len(data), self._ctypes.cast(buffer, self._ctypes.POINTER(self._ctypes.c_char)))
|
||||
return blob, buffer # o buffer precisa continuar vivo enquanto o blob for usado
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
ctypes = self._ctypes
|
||||
in_blob, _keep_in = self._to_blob(data)
|
||||
entropy, _keep_entropy = self._to_blob(self._entropy)
|
||||
out_blob = self._blob()
|
||||
ok = self._crypt32.CryptUnprotectData(ctypes.byref(in_blob), None, ctypes.byref(entropy), None, None,
|
||||
self.CRYPTPROTECT_UI_FORBIDDEN, ctypes.byref(out_blob))
|
||||
if not ok:
|
||||
raise AiVaultError(f"A DPAPI do Windows não conseguiu abrir o cofre de IA (erro {ctypes.get_last_error()}). "
|
||||
"O arquivo pode ser de outro usuário ou de outro computador.")
|
||||
try:
|
||||
return ctypes.string_at(out_blob.pbData, out_blob.cbData)
|
||||
finally:
|
||||
self._kernel32.LocalFree(out_blob.pbData)
|
||||
|
||||
|
||||
def normalize_settings(raw: object) -> dict:
|
||||
"""Valida o settings.json do painel campo a campo. O que faltar ou vier errado fica no padrão do doc."""
|
||||
settings = copy.deepcopy(DEFAULT_SETTINGS)
|
||||
if not isinstance(raw, dict):
|
||||
return settings
|
||||
providers = raw.get("providers")
|
||||
if isinstance(providers, dict):
|
||||
for name in AI_PROVIDERS:
|
||||
item = providers.get(name)
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if isinstance(item.get("enabled"), bool):
|
||||
settings["providers"][name]["enabled"] = item["enabled"]
|
||||
if item.get("authMode") in AUTH_MODES:
|
||||
settings["providers"][name]["authMode"] = item["authMode"]
|
||||
order = raw.get("order")
|
||||
if isinstance(order, list):
|
||||
known = [p for p in dict.fromkeys(order) if p in AI_PROVIDERS]
|
||||
# Quem ficou de fora da lista vai para o fim, na ordem padrão (a lista sempre tem as três).
|
||||
settings["order"] = known + [p for p in AI_PROVIDERS if p not in known]
|
||||
fallback = raw.get("fallback")
|
||||
if isinstance(fallback, dict):
|
||||
if isinstance(fallback.get("enabled"), bool):
|
||||
settings["fallback"]["enabled"] = fallback["enabled"]
|
||||
cooldown = fallback.get("cooldownMin")
|
||||
if isinstance(cooldown, (int, float)) and not isinstance(cooldown, bool) and cooldown >= 0:
|
||||
settings["fallback"]["cooldownMin"] = float(cooldown)
|
||||
return settings
|
||||
|
||||
|
||||
def _mtime(path: Path) -> int | None:
|
||||
try:
|
||||
return path.stat().st_mtime_ns
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
class AiConfig:
|
||||
"""Leitura (com cache por mtime) do settings.json e do vault.bin do painel."""
|
||||
|
||||
def __init__(self, folder: Path | None = None, cipher: Cipher | None = None,
|
||||
environ: dict[str, str] | None = None):
|
||||
self.folder = Path(folder) if folder is not None else DEFAULT_AI_DIR
|
||||
self._cipher = cipher
|
||||
self._environ = environ # None = os.environ do momento da chamada
|
||||
self._lock = threading.RLock()
|
||||
self._settings_cache: tuple[int | None, dict] | None = None
|
||||
self._keys_cache: tuple[int | None, dict[str, str]] | None = None
|
||||
self.vault_error: str | None = None
|
||||
|
||||
@property
|
||||
def settings_path(self) -> Path:
|
||||
return self.folder / "settings.json"
|
||||
|
||||
@property
|
||||
def vault_path(self) -> Path:
|
||||
return self.folder / "vault.bin"
|
||||
|
||||
def settings(self) -> dict:
|
||||
"""Configuração atual (cópia). Relê o arquivo só quando o mtime muda."""
|
||||
with self._lock:
|
||||
stamp = _mtime(self.settings_path)
|
||||
if self._settings_cache is None or self._settings_cache[0] != stamp:
|
||||
raw: object = None
|
||||
if stamp is not None:
|
||||
try:
|
||||
raw = json.loads(self.settings_path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError) as exc:
|
||||
log.warning("data/ai/settings.json inválido (%s); usando o padrão", exc)
|
||||
self._settings_cache = (stamp, normalize_settings(raw))
|
||||
return copy.deepcopy(self._settings_cache[1])
|
||||
|
||||
def provider(self, name: str) -> dict:
|
||||
return self.settings()["providers"].get(name, {"enabled": False, "authMode": "oauth"})
|
||||
|
||||
def api_keys(self) -> dict[str, str]:
|
||||
"""Chaves do cofre (só as que existem). Cofre ausente = {}; cofre que não abre = {} e `vault_error`."""
|
||||
with self._lock:
|
||||
stamp = _mtime(self.vault_path)
|
||||
if self._keys_cache is None or self._keys_cache[0] != stamp:
|
||||
self._keys_cache = (stamp, self._read_vault() if stamp is not None else {})
|
||||
if stamp is None:
|
||||
self.vault_error = None
|
||||
return dict(self._keys_cache[1])
|
||||
|
||||
def _read_vault(self) -> dict[str, str]:
|
||||
try:
|
||||
raw = self.vault_path.read_bytes()
|
||||
if not raw:
|
||||
self.vault_error = None
|
||||
return {}
|
||||
cipher = self._cipher or DpapiCipher()
|
||||
data = json.loads(cipher.unprotect(raw).decode("utf-8"))
|
||||
except Exception as exc: # noqa: BLE001 - cofre ilegível não derruba o juiz: segue sem chaves
|
||||
self.vault_error = str(exc)[:200] or "cofre de IA ilegível"
|
||||
log.warning("não abri data/ai/vault.bin: %s", self.vault_error)
|
||||
return {}
|
||||
self.vault_error = None
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
return {k: v.strip() for k, v in data.items() if k in AI_PROVIDERS and isinstance(v, str) and v.strip()}
|
||||
|
||||
def has_key(self, provider: str) -> bool:
|
||||
return bool(self.api_keys().get(provider))
|
||||
|
||||
def provider_env(self, provider: str) -> dict[str, str]:
|
||||
"""Ambiente da chamada da CLI de `provider`, conforme o modo de login (tabela do doc/ia.md)."""
|
||||
env = dict(os.environ if self._environ is None else self._environ)
|
||||
key_var = API_KEY_ENV.get(provider)
|
||||
if not key_var:
|
||||
return env
|
||||
mode = self.provider(provider).get("authMode", "oauth")
|
||||
if mode == "apiKey":
|
||||
key = self.api_keys().get(provider)
|
||||
if key:
|
||||
env[key_var] = key
|
||||
else:
|
||||
env.pop(key_var, None)
|
||||
if provider == "gemini":
|
||||
env.pop(GEMINI_OAUTH_ENV, None)
|
||||
else:
|
||||
env.pop(key_var, None)
|
||||
if provider == "gemini":
|
||||
env[GEMINI_OAUTH_ENV] = "true"
|
||||
return env
|
||||
@@ -119,8 +119,8 @@ class Settings:
|
||||
judge_model=env.get("CLIPPER_JUDGE_MODEL", ""),
|
||||
judge_min_score=num("CLIPPER_JUDGE_MIN_SCORE", 6, 0),
|
||||
)
|
||||
if settings.judge_provider not in ("codex", "claude", "off"):
|
||||
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude ou off")
|
||||
if settings.judge_provider not in ("codex", "claude", "gemini", "off"):
|
||||
raise ConfigError("CLIPPER_JUDGE_PROVIDER precisa ser codex, claude, gemini ou off")
|
||||
if settings.encoder not in ("auto", "libx264", "h264_nvenc"):
|
||||
raise ConfigError("CLIPPER_ENCODER precisa ser auto, libx264 ou h264_nvenc")
|
||||
if overrides:
|
||||
|
||||
@@ -190,6 +190,23 @@ SCHEMA = [
|
||||
);
|
||||
CREATE INDEX deleted_clips_session ON deleted_clips (session_id);
|
||||
""",
|
||||
# v11: (a) parar uma sessão à mão pausa o monitor da fonte (`monitor_paused_at` + a sessão que motivou): o monitor
|
||||
# não abre sessão nova enquanto a pausa existir; religar (PATCH monitor=true, gravar pelo link ou retomar) limpa.
|
||||
# (b) idioma falado na live, por fonte e por sessão ('' = CLIPPER_LANGUAGE): transcrição e textos da IA.
|
||||
"""
|
||||
ALTER TABLE channels ADD COLUMN monitor_paused_at TEXT;
|
||||
ALTER TABLE channels ADD COLUMN monitor_paused_session INTEGER;
|
||||
ALTER TABLE channels ADD COLUMN language TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE sessions ADD COLUMN language TEXT NOT NULL DEFAULT '';
|
||||
""",
|
||||
# v12: perfil do jogo em dois idiomas (doc/clipador/JOGOS.md). `profile_json` continua sendo o português (o que o
|
||||
# painel mostra); `profile_ai_json` é o inglês, que vai nos prompts; `translated_at` = quando uma versão foi gerada
|
||||
# da outra; `aliases_json` = outros nomes do jogo (categoria "Grand Theft Auto VI" e tela "GTA 6" → mesmo perfil).
|
||||
"""
|
||||
ALTER TABLE games ADD COLUMN profile_ai_json TEXT;
|
||||
ALTER TABLE games ADD COLUMN translated_at TEXT;
|
||||
ALTER TABLE games ADD COLUMN aliases_json TEXT NOT NULL DEFAULT '[]';
|
||||
""",
|
||||
]
|
||||
|
||||
|
||||
|
||||
+229
-43
@@ -23,7 +23,7 @@ from .db import loads, now
|
||||
from .emotes import EmoteCatalog, extract, learn_delta, message_bonus
|
||||
from .face import FaceError, FaceUnavailable
|
||||
from .hashtags import fold, to_tag
|
||||
from .judge import JudgeError, build_scan_prompt, game_context
|
||||
from .judge import JudgeError, build_scan_prompt, game_context, output_language_note
|
||||
from .scoring import fit_window
|
||||
from .sources import parse_source
|
||||
|
||||
@@ -52,31 +52,79 @@ def game_id(name: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:60] or "desconhecido"
|
||||
|
||||
|
||||
PROFILE_LISTS = ("mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources")
|
||||
PROFILE_LISTS = ("mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources", "aliases", "end_triggers")
|
||||
# Teto de cada lista (o resto: 20). Missões ficam à parte (objetos, até 120).
|
||||
LIST_LIMITS = {"aliases": 10, "end_triggers": 12}
|
||||
MAX_MISSIONS = 120
|
||||
MAX_MISSION_TRIGGERS = 8
|
||||
|
||||
# Sementes: perfis prontos que vêm com o repositório (ex.: GTA VI). Importados na subida só se o jogo não existe.
|
||||
SEEDS_DIR = Path(__file__).resolve().parent / "seeds" / "games"
|
||||
|
||||
|
||||
def clean_profile(raw: dict) -> dict:
|
||||
"""Normaliza um perfil de jogo (vindo da IA ou da edição à mão): textos aparados, listas sem vazios/duplicados.
|
||||
Hashtags viram tag de verdade ("rob run" → "#RobRun"; sem letra some), comparadas sem acento/maiúscula."""
|
||||
raw = raw if isinstance(raw, dict) else {}
|
||||
out: dict = {k: str(raw.get(k) or "").strip()[:limit] for k, limit in (("name", 120), ("summary", 1500), ("genre", 120))}
|
||||
for key in PROFILE_LISTS:
|
||||
def _clean_text_list(values, limit: int, item_chars: int = 300) -> list[str]:
|
||||
items, seen = [], set()
|
||||
for item in raw.get(key) or []:
|
||||
text = str(item or "").strip()[:300]
|
||||
if key == "hashtags":
|
||||
text = to_tag(text) or ""
|
||||
if text and fold(text) not in seen:
|
||||
seen.add(fold(text))
|
||||
items.append(text)
|
||||
continue
|
||||
for item in values or []:
|
||||
text = str(item or "").strip()[:item_chars]
|
||||
if text and text.lower() not in seen:
|
||||
seen.add(text.lower())
|
||||
items.append(text)
|
||||
out[key] = items[:20]
|
||||
return items[:limit]
|
||||
|
||||
|
||||
def clean_missions(values) -> list[dict]:
|
||||
"""Missões: nome obrigatório (sem repetir), capítulo, resumo e até 8 gatilhos de fim (até 200 caracteres cada)."""
|
||||
out, seen = [], set()
|
||||
for raw in values or []:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
name = str(raw.get("name") or "").strip()[:160]
|
||||
if not name or name.lower() in seen:
|
||||
continue
|
||||
seen.add(name.lower())
|
||||
out.append({
|
||||
"name": name,
|
||||
"chapter": str(raw.get("chapter") or "").strip()[:120],
|
||||
"summary": str(raw.get("summary") or "").strip()[:500],
|
||||
"completion_triggers": _clean_text_list(raw.get("completion_triggers"), MAX_MISSION_TRIGGERS, 200),
|
||||
})
|
||||
if len(out) >= MAX_MISSIONS:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def clean_profile(raw: dict) -> dict:
|
||||
"""Normaliza um perfil de jogo (vindo da IA, da tradução ou da edição à mão): textos aparados, listas sem
|
||||
vazios/duplicados, missões validadas. Hashtags viram tag de verdade ("rob run" → "#RobRun"; sem letra some),
|
||||
comparadas sem acento/maiúscula."""
|
||||
raw = raw if isinstance(raw, dict) else {}
|
||||
out: dict = {k: str(raw.get(k) or "").strip()[:limit] for k, limit in (("name", 120), ("summary", 1500), ("genre", 120))}
|
||||
for key in PROFILE_LISTS:
|
||||
if key == "hashtags":
|
||||
items, seen = [], set()
|
||||
for item in raw.get(key) or []:
|
||||
text = to_tag(str(item or "").strip()[:300]) or ""
|
||||
if text and fold(text) not in seen:
|
||||
seen.add(fold(text))
|
||||
items.append(text)
|
||||
out[key] = items[:20]
|
||||
else:
|
||||
out[key] = _clean_text_list(raw.get(key), LIST_LIMITS.get(key, 20))
|
||||
out["missions"] = clean_missions(raw.get("missions"))
|
||||
return out
|
||||
|
||||
|
||||
def alias_ids(*profiles: dict | None) -> list[str]:
|
||||
"""Ids normalizados dos outros nomes do jogo (das duas versões do perfil), sem repetir."""
|
||||
ids: list[str] = []
|
||||
for profile in profiles:
|
||||
for alias in (profile or {}).get("aliases") or []:
|
||||
gid = game_id(str(alias))
|
||||
if gid != "desconhecido" and gid not in ids:
|
||||
ids.append(gid)
|
||||
return ids
|
||||
|
||||
|
||||
class Intel:
|
||||
def __init__(self, engine: "Engine"):
|
||||
self.e = engine
|
||||
@@ -91,6 +139,37 @@ class Intel:
|
||||
for key in OPTION_DEFAULTS:
|
||||
if f"opt_{key}" in saved:
|
||||
self.opts[key] = json.loads(saved[f"opt_{key}"])
|
||||
self.import_seeds()
|
||||
|
||||
# ---------------------------------------------------------------- sementes de jogos
|
||||
def import_seeds(self, folder: Path | None = None) -> list[str]:
|
||||
"""Importa os perfis de `seeds/games/*.json` ({name, aliases, researchedAt, sources, profileAi, profile}) que
|
||||
ainda não existem no banco (por id ou alias). Nunca sobrescreve: o que você editou fica. Devolve os ids novos."""
|
||||
added: list[str] = []
|
||||
for path in sorted((folder or SEEDS_DIR).glob("*.json")):
|
||||
try:
|
||||
seed = json.loads(path.read_text(encoding="utf-8"))
|
||||
name = str(seed.get("name") or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
ai = clean_profile({**(seed.get("profileAi") or {}), "name": name})
|
||||
pt = clean_profile({**(seed.get("profile") or seed.get("profileAi") or {}), "name": name})
|
||||
for profile in (ai, pt):
|
||||
profile["aliases"] = profile["aliases"] or list(seed.get("aliases") or [])
|
||||
profile["sources"] = profile["sources"] or list(seed.get("sources") or [])
|
||||
gid = game_id(name)
|
||||
if self.find_game(name) or any(self.find_game(a) for a in ai["aliases"]):
|
||||
continue
|
||||
self.e.db.run(
|
||||
"INSERT INTO games (id, name, status, profile_json, profile_ai_json, aliases_json, model, researched_at,"
|
||||
" translated_at) VALUES (?, ?, 'ready', ?, ?, ?, 'seed', ?, ?)",
|
||||
gid, name[:120], json.dumps(pt, ensure_ascii=False), json.dumps(ai, ensure_ascii=False),
|
||||
json.dumps(alias_ids(ai, pt)), seed.get("researchedAt") or now(), seed.get("researchedAt") or now())
|
||||
added.append(gid)
|
||||
log.info("jogo importado da semente %s: %s", path.name, name)
|
||||
except (OSError, ValueError) as exc:
|
||||
log.warning("semente de jogo %s inválida: %s", path.name, exc)
|
||||
return added
|
||||
|
||||
# ---------------------------------------------------------------- opções (painel)
|
||||
def set_options(self, values: dict) -> dict:
|
||||
@@ -202,7 +281,7 @@ class Intel:
|
||||
self.e.db.run("UPDATE sessions SET game = ?, game_source = ?, games_json = ? WHERE id = ?",
|
||||
name[:120], source, json.dumps(history[-20:], ensure_ascii=False), session_id)
|
||||
gid = game_id(name)
|
||||
if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid):
|
||||
if not self.find_game(name):
|
||||
self.e.db.run("INSERT INTO games (id, name, status) VALUES (?, ?, 'pending')", gid, name[:120])
|
||||
|
||||
def research_pending(self) -> None:
|
||||
@@ -212,53 +291,142 @@ class Intel:
|
||||
self.research(game["id"])
|
||||
|
||||
def research(self, gid: str) -> dict:
|
||||
"""Pesquisa na web EM INGLÊS (missões e gatilhos inclusos) → versão da IA; depois traduz para português (a que
|
||||
o painel mostra). Tradução falhou: as duas ficam em inglês e `error` explica (o jogo continua utilizável)."""
|
||||
game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if not game:
|
||||
raise JudgeError("jogo não encontrado")
|
||||
if not self.e.judge.enabled:
|
||||
raise JudgeError("IA desligada: ligue o Codex ou o Claude para pesquisar o jogo")
|
||||
raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para pesquisar o jogo")
|
||||
title = (self.e.db.get("SELECT title FROM sessions WHERE game = ? ORDER BY id DESC LIMIT 1", game["name"]) or {}).get("title", "")
|
||||
notes = [n.get("text", "") for n in loads(game.get("notes_json"), []) if n.get("text")]
|
||||
try:
|
||||
profile = self.e.judge.research_game(game["name"], title, notes)
|
||||
ai = clean_profile(self.e.judge.research_game(game["name"], title, notes))
|
||||
model = self.e.judge.responder() # quem DE FATO respondeu (pode ter sido a IA reserva)
|
||||
except (JudgeError, json.JSONDecodeError) as exc:
|
||||
self.e.db.run("UPDATE games SET status = 'error', error = ? WHERE id = ?", str(exc)[:300], gid)
|
||||
raise JudgeError(str(exc)) from exc
|
||||
self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, model = ?, researched_at = ? WHERE id = ?",
|
||||
json.dumps(profile, ensure_ascii=False), f"{self.e.judge.provider}:{self.e.judge.model}", now(), gid)
|
||||
return profile
|
||||
self.e.db.run("UPDATE games SET profile_ai_json = ?, model = ?, researched_at = ? WHERE id = ?",
|
||||
json.dumps(ai, ensure_ascii=False), model, now(), gid)
|
||||
pt, error = self._translated(ai, "pt-BR")
|
||||
self._store(gid, pt=pt, ai=ai, translated=error is None, error=error)
|
||||
return ai
|
||||
|
||||
def save_profile(self, gid: str, profile: dict) -> dict:
|
||||
"""Grava o perfil editado à mão no painel. Vale na hora para a IA (status 'ready')."""
|
||||
def _translated(self, profile: dict, target: str) -> tuple[dict, str | None]:
|
||||
"""(perfil traduzido, None) ou (o próprio perfil, motivo) se a IA está desligada ou a tradução falhou."""
|
||||
if not self.e.judge.enabled:
|
||||
return profile, "IA desligada: a outra versão do perfil não foi atualizada"
|
||||
try:
|
||||
out = clean_profile(self.e.judge.translate_game(profile, target))
|
||||
except (JudgeError, json.JSONDecodeError) as exc:
|
||||
return profile, f"tradução falhou: {exc}"[:300]
|
||||
# A tradução nunca mexe em nome, hashtags, fontes e outros nomes (a IA às vezes "traduz" o que não devia).
|
||||
for key in ("name", "hashtags", "sources", "aliases"):
|
||||
out[key] = profile.get(key) or out.get(key)
|
||||
if len(out.get("missions") or []) != len(profile.get("missions") or []):
|
||||
return profile, "tradução perdeu missões: a outra versão ficou igual à original"
|
||||
return out, None
|
||||
|
||||
def _store(self, gid: str, *, pt: dict | None = None, ai: dict | None = None, translated: bool = False,
|
||||
error: str | None = None, edited: bool = False, extra_sql: str = "", extra: tuple = ()) -> None:
|
||||
"""Grava as versões que vieram (None = não mexe), os outros nomes (união das duas) e o estado."""
|
||||
game = self.e.db.get("SELECT profile_json, profile_ai_json FROM games WHERE id = ?", gid) or {}
|
||||
pt_now = pt if pt is not None else loads(game.get("profile_json"), None)
|
||||
ai_now = ai if ai is not None else loads(game.get("profile_ai_json"), None)
|
||||
self.e.db.run(
|
||||
"UPDATE games SET status = 'ready', profile_json = ?, profile_ai_json = ?, aliases_json = ?, error = ?,"
|
||||
" translated_at = CASE WHEN ? THEN ? ELSE translated_at END,"
|
||||
" edited_at = CASE WHEN ? THEN ? ELSE edited_at END" + extra_sql + " WHERE id = ?",
|
||||
json.dumps(pt_now, ensure_ascii=False) if pt_now is not None else None,
|
||||
json.dumps(ai_now, ensure_ascii=False) if ai_now is not None else None,
|
||||
json.dumps(alias_ids(ai_now, pt_now)), error, int(translated), now(), int(edited), now(), *extra, gid)
|
||||
|
||||
def save_profile(self, gid: str, profile: dict, lang: str = "pt") -> dict:
|
||||
"""Grava a edição à mão na versão `lang` ("pt" = a que você lê; "en" = a da IA) e traduz para a outra. Com a IA
|
||||
desligada, grava só essa e a outra fica como estava (`translatedAt` não muda: o painel avisa que está velha)."""
|
||||
if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid):
|
||||
raise JudgeError("jogo não encontrado")
|
||||
clean = clean_profile(profile)
|
||||
self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, edited_at = ? WHERE id = ?",
|
||||
json.dumps(clean, ensure_ascii=False), now(), gid)
|
||||
target = "en-US" if lang == "pt" else "pt-BR"
|
||||
other, error = self._translated(clean, target)
|
||||
translated = error is None
|
||||
if lang == "pt":
|
||||
self._store(gid, pt=clean, ai=other if translated else None, translated=translated, error=error, edited=True)
|
||||
else:
|
||||
self._store(gid, ai=clean, pt=other if translated else None, translated=translated, error=error, edited=True)
|
||||
return clean
|
||||
|
||||
def refine(self, gid: str, instruction: str, search: bool = True, section: str = "",
|
||||
history: list[dict] | None = None) -> tuple[dict, str]:
|
||||
"""Pede à IA para acrescentar/corrigir algo no perfil (opcionalmente numa seção). O pedido fica guardado e
|
||||
volta em toda pesquisa. Devolve (perfil, resposta curta da IA)."""
|
||||
def translate(self, gid: str) -> dict:
|
||||
"""Gera a versão da IA (inglês) a partir da portuguesa — para jogos de antes da v12."""
|
||||
game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if not game:
|
||||
raise JudgeError("jogo não encontrado")
|
||||
if not self.e.judge.enabled:
|
||||
raise JudgeError("IA desligada: ligue o Codex ou o Claude para editar o perfil pela IA")
|
||||
current = loads(game["profile_json"], None) or clean_profile({"name": game["name"]})
|
||||
raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para traduzir o perfil")
|
||||
pt = loads(game["profile_json"], None)
|
||||
if not pt:
|
||||
raise JudgeError("o jogo ainda não tem perfil para traduzir")
|
||||
ai, error = self._translated(clean_profile(pt), "en-US")
|
||||
if error:
|
||||
raise JudgeError(error)
|
||||
self._store(gid, ai=ai, translated=True)
|
||||
return ai
|
||||
|
||||
def refine(self, gid: str, instruction: str, search: bool = True, section: str = "",
|
||||
history: list[dict] | None = None) -> tuple[dict, str]:
|
||||
"""Pede à IA para acrescentar/corrigir algo no perfil (opcionalmente numa seção). Aplica na versão em inglês
|
||||
(a da IA; jogo antigo sem ela: na portuguesa) e traduz para português. O pedido fica guardado e volta em toda
|
||||
pesquisa. Devolve (perfil em português, resposta curta da IA em português)."""
|
||||
game = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if not game:
|
||||
raise JudgeError("jogo não encontrado")
|
||||
if not self.e.judge.enabled:
|
||||
raise JudgeError("IA desligada: escolha uma IA (Codex, Claude ou Gemini) para editar o perfil pela IA")
|
||||
current = (loads(game.get("profile_ai_json"), None) or loads(game["profile_json"], None)
|
||||
or clean_profile({"name": game["name"]}))
|
||||
try:
|
||||
data = self.e.judge.refine_game(game["name"], current, instruction, search, section, history)
|
||||
model = self.e.judge.responder() # antes da tradução, que também passa pelo juiz
|
||||
except json.JSONDecodeError as exc:
|
||||
raise JudgeError(f"a IA devolveu um perfil inválido: {exc}") from exc
|
||||
reply = str(data.get("reply") or "").strip()[:600]
|
||||
profile = clean_profile(data)
|
||||
ai = clean_profile(data)
|
||||
pt, error = self._translated(ai, "pt-BR")
|
||||
notes = loads(game.get("notes_json"), [])
|
||||
notes.append({"text": instruction, "at": now(), **({"section": section} if section else {})})
|
||||
self.e.db.run("UPDATE games SET status = 'ready', profile_json = ?, error = NULL, notes_json = ?, edited_at = ?,"
|
||||
" model = ? WHERE id = ?", json.dumps(profile, ensure_ascii=False),
|
||||
json.dumps(notes[-30:], ensure_ascii=False), now(), f"{self.e.judge.provider}:{self.e.judge.model}", gid)
|
||||
return profile, reply
|
||||
self._store(gid, ai=ai, pt=pt, translated=error is None, error=error, edited=True,
|
||||
extra_sql=", notes_json = ?, model = ?",
|
||||
extra=(json.dumps(notes[-30:], ensure_ascii=False), model))
|
||||
return pt, reply
|
||||
|
||||
def add_game(self, name: str, notes: str = "") -> str:
|
||||
"""Cadastra um jogo pelo painel (antes só nascia da categoria da live) e pesquisa em segundo plano.
|
||||
Já existe (pelo id ou por outro nome dele) → UserError 409."""
|
||||
name = name.strip()[:120]
|
||||
if not name:
|
||||
raise ValueError("Diga o nome do jogo.")
|
||||
existing = self.find_game(name)
|
||||
if existing:
|
||||
raise LookupError(f"“{existing['name']}” já está na lista.")
|
||||
gid = game_id(name)
|
||||
note_list = [{"text": notes.strip()[:1500], "at": now()}] if notes.strip() else []
|
||||
self.e.db.run("INSERT INTO games (id, name, status, notes_json) VALUES (?, ?, 'pending', ?)",
|
||||
gid, name, json.dumps(note_list, ensure_ascii=False))
|
||||
if self.e.judge.enabled:
|
||||
threading.Thread(target=self._research_quietly, args=(gid,), name=f"game-{gid}", daemon=True).start()
|
||||
return gid
|
||||
|
||||
def _research_quietly(self, gid: str) -> None:
|
||||
try:
|
||||
self.research(gid)
|
||||
except JudgeError as exc:
|
||||
log.warning("pesquisa do jogo %s falhou: %s", gid, exc)
|
||||
|
||||
def delete_game(self, gid: str) -> None:
|
||||
"""Apaga o jogo. Sessões não mudam; se o jogo voltar numa live, nasce de novo e é pesquisado."""
|
||||
if not self.e.db.get("SELECT 1 FROM games WHERE id = ?", gid):
|
||||
raise JudgeError("jogo não encontrado")
|
||||
self.e.db.run("DELETE FROM games WHERE id = ?", gid)
|
||||
|
||||
def delete_note(self, gid: str, index: int) -> None:
|
||||
"""Esquece um pedido (ele deixa de voltar nas próximas pesquisas; o perfil atual não muda)."""
|
||||
@@ -270,11 +438,26 @@ class Intel:
|
||||
notes.pop(index)
|
||||
self.e.db.run("UPDATE games SET notes_json = ? WHERE id = ?", json.dumps(notes, ensure_ascii=False), gid)
|
||||
|
||||
def profile(self, name: str) -> dict | None:
|
||||
if not name:
|
||||
def find_game(self, name: str) -> dict | None:
|
||||
"""Linha do jogo pelo nome: id normalizado ou, se não achar, um jogo que tem esse nome entre os outros nomes."""
|
||||
gid = game_id(name or "")
|
||||
if not name or gid == "desconhecido":
|
||||
return None
|
||||
row = self.e.db.get("SELECT profile_json FROM games WHERE id = ? AND status = 'ready'", game_id(name))
|
||||
return loads(row["profile_json"], None) if row else None
|
||||
row = self.e.db.get("SELECT * FROM games WHERE id = ?", gid)
|
||||
if row:
|
||||
return row
|
||||
# aliases_json é uma lista JSON de ids: procura o id entre aspas (LIKE barato, confere no Python).
|
||||
for row in self.e.db.all("SELECT * FROM games WHERE aliases_json LIKE ?", f'%"{gid}"%'):
|
||||
if gid in loads(row.get("aliases_json"), []):
|
||||
return row
|
||||
return None
|
||||
|
||||
def profile(self, name: str) -> dict | None:
|
||||
"""Perfil que vai para a IA: a versão em inglês; jogo antigo, sem ela, usa a portuguesa."""
|
||||
row = self.find_game(name)
|
||||
if not row or row["status"] != "ready":
|
||||
return None
|
||||
return loads(row.get("profile_ai_json"), None) or loads(row["profile_json"], None)
|
||||
|
||||
def session_game(self, session: dict) -> tuple[str, dict | None]:
|
||||
"""(nome do jogo, perfil) da sessão — o mesmo critério do contexto: jogo confirmado por você vale sozinho;
|
||||
@@ -291,8 +474,11 @@ class Intel:
|
||||
memory = loads(session.get("memory_json"), [])
|
||||
confirmed = session.get("game_source") == "user" and bool(session.get("game"))
|
||||
profile = self.profile(session.get("game", "")) or (None if confirmed else self.profile(session.get("screen_game", "")))
|
||||
return game_context(session.get("game", ""), session.get("screen_game", ""), profile, session.get("title", ""),
|
||||
text = game_context(session.get("game", ""), session.get("screen_game", ""), profile, session.get("title", ""),
|
||||
" | ".join(m["summary"] for m in memory[-3:] if m.get("summary")), confirmed=confirmed)
|
||||
# Sessão em outro idioma (fonte gringa): o editor e a varredura escrevem título/legenda nesse idioma.
|
||||
note = output_language_note(session.get("language") or self.e.settings.language)
|
||||
return f"{text}\n{note}" if note else text
|
||||
|
||||
# ---------------------------------------------------------------- frames
|
||||
def frames(self, session: dict, times: list[float], tag: str) -> list[tuple[float, Path]]:
|
||||
|
||||
+410
-71
@@ -9,8 +9,13 @@ Quatro usos, todos com saída JSON validada por schema:
|
||||
3. **pesquisa do jogo** (com busca na web): o que é o jogo, o que rende corte nele, gírias, novidades.
|
||||
4. **webcam**: onde está a câmera do streamer no quadro (retângulo normalizado), para o layout câmera-em-cima.
|
||||
|
||||
Provedores: `codex` (`codex exec`, imagens com `-i`, web com `--search`, `--output-schema`) ou `claude`
|
||||
(`claude -p --json-schema`; imagens pela ferramenta Read, web por WebSearch/WebFetch).
|
||||
Provedores: `codex` (`codex exec`, imagens com `-i`, web com `--search`, `--output-schema`), `claude`
|
||||
(`claude -p --json-schema`; imagens pela ferramenta Read, web por WebSearch/WebFetch) ou `gemini`
|
||||
(`gemini -p -o json --approval-mode plan`; schema no prompt, imagens por `@arquivo`, web por google_web_search).
|
||||
|
||||
Login, chave de API e IA reserva vêm de Configurações → IA no painel (`data/ai/`, contrato em `doc/ia.md`): se a
|
||||
IA escolhida falhar por indisponibilidade (cota, sobrecarga, login, rede, CLI ausente, tempo esgotado), a próxima
|
||||
da ordem tenta com o modelo padrão dela, e a que falhou fica em pausa por `cooldownMin`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,21 +28,32 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from . import layout
|
||||
from .ai_settings import AiConfig
|
||||
from .scoring import ChatMessage, Word, fit_window
|
||||
|
||||
log = logging.getLogger("cenaforge_clipper.judge")
|
||||
|
||||
PROVIDERS = ("codex", "claude", "off")
|
||||
DEFAULT_MODELS = {"codex": "gpt-6-luna", "claude": "haiku"}
|
||||
PROVIDERS = ("codex", "claude", "gemini", "off")
|
||||
AI_ENABLED = ("codex", "claude", "gemini")
|
||||
DEFAULT_MODELS = {"codex": "gpt-6-luna", "claude": "haiku", "gemini": "gemini-3.5-flash"}
|
||||
CLAUDE_MODELS = [
|
||||
{"id": "haiku", "label": "Haiku (mais barato)"},
|
||||
{"id": "sonnet", "label": "Sonnet (equilíbrio)"},
|
||||
{"id": "opus", "label": "Opus (mais capaz, mais caro)"},
|
||||
]
|
||||
# Lista estática (`gemini models -o json` existe, mas custa um processo Node a cada abertura do painel).
|
||||
GEMINI_MODELS = [
|
||||
{"id": "gemini-3.5-flash", "label": "3.5 Flash (rápido e barato)"},
|
||||
{"id": "gemini-3.1-flash-lite", "label": "3.1 Flash-Lite (mais barato)"},
|
||||
{"id": "gemini-2.5-pro", "label": "2.5 Pro (mais capaz, mais caro)"},
|
||||
]
|
||||
CONTEXT_AFTER_S = 15.0
|
||||
# Padrões de duração = os da configuração do corte (layout.DEFAULTS): mínimo 60 s, máximo 90 s, volta até 2 min.
|
||||
DEFAULT_MIN_S = float(layout.DEFAULTS["duration"]["minS"])
|
||||
@@ -172,10 +188,22 @@ SCAN_SCHEMA = {
|
||||
"required": ["screen_game", "has_webcam", "summary", "moments"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
_MISSION = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"chapter": {"type": "string"},
|
||||
"summary": {"type": "string"},
|
||||
"completion_triggers": {"type": "array", "items": {"type": "string"}},
|
||||
},
|
||||
"required": ["name", "chapter", "summary", "completion_triggers"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
PROFILE_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"aliases": {"type": "array", "items": {"type": "string"}},
|
||||
"summary": {"type": "string"},
|
||||
"genre": {"type": "string"},
|
||||
"mechanics": {"type": "array", "items": {"type": "string"}},
|
||||
@@ -185,8 +213,11 @@ PROFILE_SCHEMA = {
|
||||
"news": {"type": "array", "items": {"type": "string"}},
|
||||
"hashtags": {"type": "array", "items": {"type": "string"}},
|
||||
"sources": {"type": "array", "items": {"type": "string"}},
|
||||
"missions": {"type": "array", "items": _MISSION},
|
||||
"end_triggers": {"type": "array", "items": {"type": "string"}},
|
||||
},
|
||||
"required": ["name", "summary", "genre", "mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags", "sources"],
|
||||
"required": ["name", "aliases", "summary", "genre", "mechanics", "clip_worthy", "avoid", "jargon", "news", "hashtags",
|
||||
"sources", "missions", "end_triggers"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
CAM_SCHEMA = {
|
||||
@@ -242,37 +273,57 @@ moments=[] (é o normal na maior parte do tempo — não force). Não repita um
|
||||
- title/caption/reason como um editor faria (título ≤ 70 caracteres, verdadeiro; hashtags só do que há aqui).
|
||||
Não use ferramentas além do que foi entregue. Responda só com o JSON pedido."""
|
||||
|
||||
PROFILE_SYSTEM = """Você pesquisa jogos para um editor de cortes de live em português do Brasil. Use a busca na
|
||||
web para confirmar o que é o jogo (nome da categoria da Twitch pode ser abreviado ou ambíguo). Seja factual e
|
||||
cite as fontes (URLs). Responda só com o JSON pedido, textos em português do Brasil.
|
||||
- summary: 2–3 frases do que é o jogo e como se joga.
|
||||
- mechanics: até 8 mecânicas/sistemas que aparecem em gameplay.
|
||||
- clip_worthy: até 10 situações que rendem corte NESTE jogo (específicas, não genéricas).
|
||||
- avoid: até 6 situações que parecem momento mas não rendem (menus, farm, fila...).
|
||||
- jargon: até 12 termos/gírias que streamer e chat usam (para entender a transcrição).
|
||||
- news: até 6 novidades recentes com mês/ano (lançamento, atualização, polêmica) que tornam informação valiosa.
|
||||
- hashtags: 3 a 6 hashtags que o público usa para ESTE jogo no TikTok, Shorts e Reels (Brasil): o nome do jogo sem
|
||||
espaço, abreviação conhecida, o modo/gênero quando for buscado (ex.: GTARP). A primeira é a principal do jogo.
|
||||
Escreva com "#", sem inventar tag que ninguém usa.
|
||||
- sources: até 5 URLs usadas.
|
||||
Se vierem "pedidos do usuário", eles valem mais que a pesquisa: inclua o que ele pediu para acrescentar e respeite
|
||||
o que ele mandou tirar ou corrigir (ele conhece o canal e o jogo)."""
|
||||
# Perfil do jogo em INGLÊS (doc/clipador/JOGOS.md): é o que vai nos prompts; a tradução para português é só para o
|
||||
# dono ler no painel. Pesquisar em inglês também acha mais fonte (wikis, guias) — sobretudo lista de missões.
|
||||
PROFILE_SYSTEM = """You research video games for a live-stream clip editor. Use web search to confirm what the game
|
||||
is (a Twitch category name can be abbreviated or ambiguous). Be factual and cite sources (URLs). Answer only with the
|
||||
requested JSON, all text in ENGLISH.
|
||||
- aliases: up to 10 other names streamers, chat and stream categories use (abbreviations, numbers, local titles).
|
||||
- summary: 2-3 sentences on what the game is and how it plays.
|
||||
- mechanics: up to 8 systems/activities that show up in gameplay.
|
||||
- clip_worthy: up to 10 situations that make a good clip IN THIS GAME (specific, not generic).
|
||||
- avoid: up to 6 situations that look like a moment but are not (menus, grinding, queues...).
|
||||
- jargon: up to 12 terms/slang streamers and chat use (to understand the transcript), including Brazilian
|
||||
Portuguese slang when the game is popular in Brazil.
|
||||
- news: up to 6 recent news items with month/year (release, update, controversy) that make information valuable.
|
||||
- hashtags: 3 to 6 hashtags the audience uses for THIS game on TikTok, Shorts and Reels (international and Brazil):
|
||||
the game name without spaces, the known abbreviation, the mode/genre when people search it (e.g. GTARP). The
|
||||
first one is the main tag. Write them with "#" and never invent a tag nobody uses.
|
||||
- missions: the game's STORY missions exactly as reliable sources list them (official wiki, major guides), ONLY if
|
||||
that list is public; official mission names, in story order; up to 120. For each: name; chapter (act/chapter or
|
||||
""); summary (one sentence); completion_triggers (up to 4): what visibly or audibly marks the end of THAT mission
|
||||
(e.g. "MISSION PASSED" banner, result/score screen, final cutscene, a specific objective text or line). If the
|
||||
game is not released yet or the list is not public, return missions=[] - NEVER invent missions.
|
||||
- end_triggers: up to 10 general signs that a mission/objective just ended in this game (banner text, sound,
|
||||
result screen, money/reward popup, cutscene, failure screen like "MISSION FAILED"/"WASTED").
|
||||
- sources: up to 8 URLs you used.
|
||||
If "user requests" come along, they outweigh the research: add what the user asked to add and respect what they
|
||||
asked to remove or fix (they know the channel and the game). The requests may be written in Portuguese."""
|
||||
|
||||
REFINE_SYSTEM = """Você mantém o perfil de um jogo usado por um editor de cortes de live em português do Brasil.
|
||||
Recebe o perfil ATUAL (JSON) e um PEDIDO do usuário (acrescentar, corrigir, tirar ou detalhar algo). Devolva o
|
||||
perfil COMPLETO atualizado, no mesmo formato:
|
||||
- mantenha tudo o que o pedido não mexe, com o mesmo texto;
|
||||
- aplique o pedido no campo certo (situação que rende corte → clip_worthy; o que não rende → avoid; gíria → jargon;
|
||||
mecânica → mechanics; novidade → news com mês/ano; hashtag do jogo → hashtags, com "#", a principal primeiro),
|
||||
escrito no estilo dos itens que já estão lá;
|
||||
- os limites de tamanho das listas podem crescer até 15 itens quando o usuário pedir para acrescentar;
|
||||
- se precisar confirmar um fato, pode usar a busca na web e acrescentar a URL em sources;
|
||||
- o usuário conhece o canal e o jogo: o que ele afirma vale, mesmo que você não ache na web;
|
||||
- se vier uma SEÇÃO em foco, o pedido é sobre ela: mexa nela (outras só se o pedido disser);
|
||||
- pode transformar um pedido genérico em itens concretos e úteis para o editor (ex.: "reação do streamer conta"
|
||||
vira "Streamer grita, xinga ou ri alto logo depois de uma morte ou fuga");
|
||||
- reply: 1–2 frases para o usuário dizendo o que você mudou (ou, se o pedido for uma pergunta, a resposta).
|
||||
Textos em português do Brasil. Responda só com o JSON pedido."""
|
||||
REFINE_SYSTEM = """You maintain the profile of a game used by a live-stream clip editor. The profile is in ENGLISH.
|
||||
You receive the CURRENT profile (JSON) and a REQUEST from the user, usually written in Brazilian Portuguese (add,
|
||||
fix, remove or detail something). Return the COMPLETE updated profile, same format, all profile text in ENGLISH:
|
||||
- keep everything the request does not touch, with the same text;
|
||||
- apply the request to the right field (clip-worthy situation -> clip_worthy; what is not -> avoid; slang -> jargon;
|
||||
mechanic -> mechanics; news -> news with month/year; game hashtag -> hashtags with "#", main one first; story
|
||||
mission -> missions; general "mission is over" sign -> end_triggers; other name -> aliases), in the style of the
|
||||
existing items;
|
||||
- lists may grow up to 15 items when the user asks to add (missions up to 120);
|
||||
- to confirm a fact you may use web search and add the URL to sources; never invent missions;
|
||||
- the user knows the channel and the game: what they state is right, even if you cannot find it online;
|
||||
- if a SECTION in focus comes along, the request is about it (touch other sections only if the request says so);
|
||||
- you may turn a vague request into concrete, useful items for the editor;
|
||||
- reply: 1-2 sentences IN BRAZILIAN PORTUGUESE telling the user what you changed (or, if the request is a
|
||||
question, the answer, also in Portuguese).
|
||||
Answer only with the requested JSON."""
|
||||
|
||||
TRANSLATE_SYSTEM = """You translate the profile of a video game (JSON) between English and Brazilian Portuguese for a
|
||||
live-stream clip editor. Return the same JSON structure with the same number of items in every list and in the same
|
||||
order. Translate summaries and descriptions naturally. Keep AS IS: the game name, proper names (characters, places,
|
||||
gangs, vehicles), OFFICIAL mission names, on-screen texts quoted in triggers (e.g. "MISSION PASSED"), hashtags,
|
||||
aliases and URLs. Slang in jargon stays as players say it (you may add a short meaning). Answer only with the JSON."""
|
||||
|
||||
TRANSLATE_TARGETS = {"pt-BR": "Brazilian Portuguese (pt-BR)", "en-US": "English (en-US)"}
|
||||
|
||||
REFINE_SCHEMA = {
|
||||
"type": "object",
|
||||
@@ -281,8 +332,8 @@ REFINE_SCHEMA = {
|
||||
"additionalProperties": False,
|
||||
}
|
||||
PROFILE_SECTIONS = {"summary": "Resumo", "clip_worthy": "O que rende corte", "avoid": "Evitar", "mechanics": "Mecânicas",
|
||||
"hashtags": "Hashtags",
|
||||
"news": "Novidades", "jargon": "Gírias e termos", "sources": "Fontes"}
|
||||
"hashtags": "Hashtags", "news": "Novidades", "jargon": "Gírias e termos", "sources": "Fontes",
|
||||
"missions": "Missões", "end_triggers": "Gatilhos de fim de missão", "aliases": "Outros nomes"}
|
||||
|
||||
CAM_SYSTEM = """Você analisa frames de uma live. Diga se há uma webcam/câmera do streamer sobreposta ao jogo e,
|
||||
se houver, o retângulo DELA (só a câmera, sem bordas do overlay) em coordenadas normalizadas 0–1 do quadro:
|
||||
@@ -305,10 +356,98 @@ class Verdict:
|
||||
|
||||
|
||||
class JudgeError(RuntimeError):
|
||||
pass
|
||||
"""Falha da IA. `unavailable`: True = indisponibilidade (dispara a reserva), False = erro de conteúdo (não
|
||||
troca de IA), None = decidir pelo texto (`is_availability_error`)."""
|
||||
|
||||
def __init__(self, message: str, unavailable: bool | None = None):
|
||||
super().__init__(message)
|
||||
self.unavailable = unavailable
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reserva: o que é "indisponível" (doc/ia.md)
|
||||
# Falha que não é culpa do pedido: cota/limite, sobrecarga, login/chave, rede, CLI ausente e tempo esgotado.
|
||||
_AVAILABILITY_PATTERNS = re.compile(
|
||||
r"rate[\s_-]?limit|too many requests|\b429\b|quota|resource[\s_]exhausted|usage limit|credit balance"
|
||||
r"|overloaded|\b529\b|\b503\b|unavailable"
|
||||
r"|\b401\b|\b403\b|unauthori[sz]ed|not logged in|invalid[\s_-]?api[\s_-]?key|api key not valid|IneligibleTier"
|
||||
r"|\bECONN\w*|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|network"
|
||||
r"|timed? ?out|tempo esgotado|passou de \d+ s"
|
||||
r"|n[ãa]o encontrad[oa]|not found in path|n[ãa]o consegui rodar|command not found|is not recognized",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def is_availability_error(text: str) -> bool:
|
||||
"""True quando a mensagem de erro indica que a IA está indisponível (e vale tentar a reserva)."""
|
||||
return bool(text) and bool(_AVAILABILITY_PATTERNS.search(text))
|
||||
|
||||
|
||||
def extract_json_object(text: str, fences: bool = True) -> dict | None:
|
||||
"""Primeiro objeto JSON do texto (tolera cercas ```json e texto em volta). None se não houver.
|
||||
`fences=False` ignora cercas (para o envelope da CLI, cujo texto escapado pode conter uma)."""
|
||||
if not text:
|
||||
return None
|
||||
body = text.strip()
|
||||
fence = re.search(r"```(?:json)?\s*(.*?)```", body, re.S | re.I) if fences else None
|
||||
candidates = ([fence.group(1).strip()] if fence else []) + [body]
|
||||
decoder = json.JSONDecoder()
|
||||
for candidate in candidates:
|
||||
for match in re.finditer(r"\{", candidate):
|
||||
try:
|
||||
value, _end = decoder.raw_decode(candidate, match.start())
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(value, dict):
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- prompts
|
||||
# Idiomas que o serviço conhece (fonte/sessão `language`; o painel oferece os mesmos). Nome legível para o prompt.
|
||||
LANGUAGE_NAMES = {"pt-BR": "português do Brasil", "en-US": "English (US)", "es-419": "Español (Latinoamérica)"}
|
||||
DEFAULT_LANGUAGE = "pt-BR"
|
||||
|
||||
|
||||
def output_language_note(language: str | None) -> str:
|
||||
"""Linha que vai no contexto do EDITOR e da VARREDURA quando a saída não é em português: título, legenda e
|
||||
hashtags no idioma do público. Vazia para pt-BR (os prompts já são em português)."""
|
||||
code = (language or "").strip() or DEFAULT_LANGUAGE
|
||||
if code == DEFAULT_LANGUAGE:
|
||||
return ""
|
||||
name = LANGUAGE_NAMES.get(code, code)
|
||||
return (f"Idioma de saída: {name}. Título, legenda e hashtags em {name}, naturais para o público desse idioma "
|
||||
f"(a transcrição e o chat podem estar em outro idioma; não traduza literalmente, escreva como um editor nativo).")
|
||||
|
||||
|
||||
MISSIONS_IN_PROMPT = 25
|
||||
MISSIONS_PROMPT_CHARS = 1500
|
||||
|
||||
|
||||
def mission_lines(profile: dict) -> list[str]:
|
||||
"""Gatilhos de fim de missão e as missões (nome + gatilhos) para o prompt, com teto de tamanho: o perfil do GTA
|
||||
pode ter 100+ missões, e o contexto vai em todo julgamento."""
|
||||
lines: list[str] = []
|
||||
triggers = [str(t) for t in (profile.get("end_triggers") or [])[:10] if t]
|
||||
if triggers:
|
||||
lines.append("Sinais de fim de missão/objetivo neste jogo: " + "; ".join(triggers))
|
||||
missions = [m for m in (profile.get("missions") or []) if isinstance(m, dict) and m.get("name")]
|
||||
if missions:
|
||||
parts, used = [], 0
|
||||
for m in missions[:MISSIONS_IN_PROMPT]:
|
||||
ends = " / ".join(str(t) for t in (m.get("completion_triggers") or [])[:2] if t)
|
||||
item = f"{m['name']}" + (f" (fim: {ends})" if ends else "")
|
||||
if used + len(item) > MISSIONS_PROMPT_CHARS:
|
||||
break
|
||||
parts.append(item)
|
||||
used += len(item) + 2
|
||||
extra = len(missions) - len(parts)
|
||||
lines.append("Missões da história: " + "; ".join(parts) + (f"; …e mais {extra}" if extra > 0 else ""))
|
||||
if triggers or missions:
|
||||
lines.append("Se o trecho é o fim de uma missão, termine o corte logo depois do gatilho de fim "
|
||||
"(o momento de vitória/falha é o clímax).")
|
||||
return lines
|
||||
|
||||
|
||||
def game_context(game: str, screen_game: str, profile: dict | None, live_title: str, history: str = "",
|
||||
confirmed: bool = False) -> str:
|
||||
lines = [f"Título da live: {live_title or '(desconhecido)'}"]
|
||||
@@ -327,6 +466,7 @@ def game_context(game: str, screen_game: str, profile: dict | None, live_title:
|
||||
("jargon", "Gírias/termos"), ("news", "Novidades")):
|
||||
if profile.get(key):
|
||||
lines.append(f"{label}: " + "; ".join(profile[key][:10]))
|
||||
lines.extend(mission_lines(profile))
|
||||
if history:
|
||||
lines.append(f"O que aconteceu antes na live: {history}")
|
||||
return "\n".join(lines)
|
||||
@@ -453,6 +593,34 @@ def find_claude() -> list[str] | None:
|
||||
return [exe] if exe else None
|
||||
|
||||
|
||||
def find_gemini() -> list[str] | None:
|
||||
"""Comando do Gemini CLI. No Windows o npm instala `gemini.cmd` (mesmo problema do `codex.cmd`): rodamos o
|
||||
`bundle/gemini.js` do pacote direto pelo Node. `GEMINI_BIN` força um caminho (.js roda pelo Node)."""
|
||||
env = os.environ.get("GEMINI_BIN")
|
||||
if env:
|
||||
return [shutil.which("node") or "node", env] if env.endswith(".js") else [env]
|
||||
if sys.platform != "win32":
|
||||
exe = shutil.which("gemini")
|
||||
return [exe] if exe else None
|
||||
cmd = shutil.which("gemini.cmd") or shutil.which("gemini")
|
||||
node = shutil.which("node")
|
||||
if cmd and node:
|
||||
js = Path(cmd).parent / "node_modules" / "@google" / "gemini-cli" / "bundle" / "gemini.js"
|
||||
if js.is_file():
|
||||
return [node, str(js)]
|
||||
exe = shutil.which("gemini.exe")
|
||||
return [exe] if exe else None
|
||||
|
||||
|
||||
def find_cli(provider: str) -> list[str] | None:
|
||||
"""Comando da CLI do provedor (None = não instalada). Resolve na hora (os testes trocam as funções)."""
|
||||
finder = {"codex": find_codex, "claude": find_claude, "gemini": find_gemini}.get(provider)
|
||||
return finder() if finder else None
|
||||
|
||||
|
||||
PROVIDER_NAMES = {"codex": "Codex", "claude": "Claude", "gemini": "Gemini"}
|
||||
|
||||
|
||||
def codex_models(cache: Path | None = None) -> list[dict]:
|
||||
"""Modelos que o Codex lista para esta conta (cache que a própria CLI mantém)."""
|
||||
cache = cache or Path.home() / ".codex" / "models_cache.json"
|
||||
@@ -469,12 +637,21 @@ def codex_models(cache: Path | None = None) -> list[dict]:
|
||||
|
||||
# ---------------------------------------------------------------- IA
|
||||
class Judge:
|
||||
def __init__(self, provider: str, model: str, workdir: Path, analyst_model: str = ""):
|
||||
def __init__(self, provider: str, model: str, workdir: Path, analyst_model: str = "",
|
||||
ai: AiConfig | None = None, clock=time.time):
|
||||
self.provider = provider if provider in PROVIDERS else "codex"
|
||||
self.model = model or DEFAULT_MODELS.get(self.provider, "")
|
||||
# Modelo do ANALISTA (1º juiz, vê os frames). Vazio = o mesmo do editor.
|
||||
self.analyst_model = analyst_model
|
||||
self.workdir = workdir
|
||||
# Configurações → IA do painel (data/ai): login/chave por provedor e ordem da reserva.
|
||||
self.ai = ai or AiConfig()
|
||||
self._clock = clock
|
||||
# Pausas da reserva, em memória (cada processo tem as suas): provedor → (até, motivo).
|
||||
self._pauses: dict[str, tuple[float, str]] = {}
|
||||
self._pause_lock = threading.Lock()
|
||||
# Quem respondeu a última chamada DESTA thread ("provedor:modelo"): o juiz roda em várias threads.
|
||||
self._local = threading.local()
|
||||
|
||||
def configure(self, provider: str, model: str, analyst_model: str | None = None) -> None:
|
||||
if provider not in PROVIDERS:
|
||||
@@ -486,19 +663,75 @@ class Judge:
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self.provider in ("codex", "claude")
|
||||
return self.provider in AI_ENABLED
|
||||
|
||||
def command(self) -> list[str] | None:
|
||||
return find_codex() if self.provider == "codex" else find_claude() if self.provider == "claude" else None
|
||||
return find_cli(self.provider) if self.enabled else None
|
||||
|
||||
def responder(self) -> str:
|
||||
""""provedor:modelo" de quem respondeu a última chamada desta thread (a reserva pode ter respondido)."""
|
||||
return getattr(self._local, "responder", None) or f"{self.provider}:{self.model}"
|
||||
|
||||
# ---------- reserva
|
||||
def pauses(self) -> dict[str, tuple[float, str]]:
|
||||
"""Pausas ainda valendo (as vencidas saem)."""
|
||||
now = self._clock()
|
||||
with self._pause_lock:
|
||||
self._pauses = {p: v for p, v in self._pauses.items() if v[0] > now}
|
||||
return dict(self._pauses)
|
||||
|
||||
def pause(self, provider: str, reason: str, minutes: float | None = None) -> None:
|
||||
if minutes is None:
|
||||
minutes = float(self.ai.settings()["fallback"]["cooldownMin"])
|
||||
if minutes <= 0:
|
||||
return
|
||||
with self._pause_lock:
|
||||
self._pauses[provider] = (self._clock() + minutes * 60, reason[:200])
|
||||
|
||||
def _skip_reason(self, provider: str, settings: dict) -> str | None:
|
||||
"""Por que o provedor não entra na cadeia (None = pronto). Não olha a pausa."""
|
||||
conf = settings["providers"].get(provider) or {}
|
||||
if not conf.get("enabled"):
|
||||
return "desligada em Configurações → IA"
|
||||
if not find_cli(provider):
|
||||
return "CLI não encontrada"
|
||||
if conf.get("authMode") == "apiKey" and not self.ai.has_key(provider):
|
||||
return "modo chave de API sem chave no cofre"
|
||||
return None
|
||||
|
||||
def fallback_chain(self) -> list[str]:
|
||||
"""Ordem em que `ask` tenta as IAs: a escolhida no juiz primeiro, depois a `order` do painel, só as ligadas,
|
||||
com CLI e (no modo chave) com chave; as em pausa são puladas. Reserva desligada: só a escolhida.
|
||||
Se TODAS as prontas estiverem em pausa, elas voltam como último recurso (melhor tentar do que parar)."""
|
||||
if not self.enabled:
|
||||
return []
|
||||
settings = self.ai.settings()
|
||||
candidates = [self.provider]
|
||||
if settings["fallback"]["enabled"]:
|
||||
candidates += [p for p in settings["order"] if p != self.provider and p in AI_ENABLED]
|
||||
ready = [p for p in candidates if self._skip_reason(p, settings) is None]
|
||||
paused = self.pauses() if settings["fallback"]["enabled"] else {}
|
||||
active = [p for p in ready if p not in paused]
|
||||
return active or ready
|
||||
|
||||
def describe(self) -> dict:
|
||||
cmd = self.command() if self.enabled else None
|
||||
settings = self.ai.settings()
|
||||
primary_skip = self._skip_reason(self.provider, settings) if self.enabled else None
|
||||
return {"provider": self.provider, "model": self.model if self.enabled else None,
|
||||
"analystModel": (self.analyst_model or self.model) if self.enabled else None,
|
||||
"available": bool(cmd) if self.enabled else None, "path": cmd[-1] if cmd else None}
|
||||
"available": bool(cmd) if self.enabled else None, "path": cmd[-1] if cmd else None,
|
||||
# Por que a escolhida não roda (desligada no painel, sem CLI, sem chave); None = pronta.
|
||||
"unavailableReason": primary_skip,
|
||||
"authMode": settings["providers"].get(self.provider, {}).get("authMode") if self.enabled else None,
|
||||
"fallback": {"enabled": settings["fallback"]["enabled"],
|
||||
"cooldownMin": settings["fallback"]["cooldownMin"],
|
||||
"chain": self.fallback_chain()},
|
||||
"pauses": [{"provider": p, "until": datetime.fromtimestamp(until, timezone.utc).isoformat(timespec="seconds"),
|
||||
"reason": reason} for p, (until, reason) in sorted(self.pauses().items())]}
|
||||
|
||||
def models(self) -> dict:
|
||||
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "defaults": DEFAULT_MODELS}
|
||||
return {"codex": codex_models(), "claude": CLAUDE_MODELS, "gemini": GEMINI_MODELS, "defaults": DEFAULT_MODELS}
|
||||
|
||||
# ---------- usos
|
||||
def analyze(self, prompt: str, images: list[Path]) -> dict:
|
||||
@@ -514,7 +747,8 @@ class Judge:
|
||||
lo: float | None = None, hi: float | None = None, min_s: float = DEFAULT_MIN_S,
|
||||
max_s: float = DEFAULT_MAX_S) -> Verdict:
|
||||
data = self.ask(JUDGE_SYSTEM, prompt, VERDICT_SCHEMA, images or [])
|
||||
return _clean(data, start_s, end_s, f"{self.provider}:{self.model}", lo, hi, min_s, max_s)
|
||||
# Modelo de quem DE FATO respondeu (a reserva pode ter entrado no lugar da escolhida).
|
||||
return _clean(data, start_s, end_s, self.responder(), lo, hi, min_s, max_s)
|
||||
|
||||
def scan(self, prompt: str, images: list[Path]) -> dict:
|
||||
data = self.ask(SCAN_SYSTEM, prompt, SCAN_SCHEMA, images)
|
||||
@@ -523,57 +757,105 @@ class Judge:
|
||||
return data
|
||||
|
||||
def research_game(self, name: str, live_title: str = "", notes: list[str] | None = None) -> dict:
|
||||
prompt = f"Categoria/jogo da live: {name}\nTítulo da live (pista extra): {live_title or '(nenhum)'}\n"
|
||||
prompt = f"Stream category / game: {name}\nStream title (extra hint): {live_title or '(none)'}\n"
|
||||
if notes:
|
||||
prompt += "Pedidos do usuário (respeite):\n" + "\n".join(f"- {n}" for n in notes) + "\n"
|
||||
prompt += "Pesquise e devolva o perfil do jogo."
|
||||
prompt += "User requests (respect them; may be in Portuguese):\n" + "\n".join(f"- {n}" for n in notes) + "\n"
|
||||
prompt += "Research and return the game profile in English."
|
||||
return self.ask(PROFILE_SYSTEM, prompt, PROFILE_SCHEMA, [], search=True, timeout=RESEARCH_TIMEOUT_S)
|
||||
|
||||
def refine_game(self, name: str, profile: dict, instruction: str, search: bool = True, section: str = "",
|
||||
history: list[dict] | None = None) -> dict:
|
||||
"""Aplica um pedido do usuário ao perfil do jogo (acrescentar/corrigir/tirar) e devolve o perfil inteiro
|
||||
mais `reply` (o que a IA fez, em 1–2 frases). `section` = campo em foco; `history` = conversa anterior."""
|
||||
prompt = f"Jogo: {name}\nPerfil ATUAL:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
|
||||
prompt = f"Game: {name}\nCURRENT profile:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
|
||||
if section in PROFILE_SECTIONS:
|
||||
prompt += f"SEÇÃO em foco: {section} ({PROFILE_SECTIONS[section]})\n"
|
||||
prompt += f"SECTION in focus: {section}\n"
|
||||
if history:
|
||||
prompt += "Conversa até aqui:\n" + "\n".join(
|
||||
f"{'Usuário' if h.get('role') == 'user' else 'IA'}: {str(h.get('text', ''))[:400]}" for h in history[-8:]) + "\n"
|
||||
prompt += f"PEDIDO do usuário:\n{instruction}\n\nDevolva o perfil completo atualizado e o reply."
|
||||
prompt += "Conversation so far:\n" + "\n".join(
|
||||
f"{'User' if h.get('role') == 'user' else 'AI'}: {str(h.get('text', ''))[:400]}" for h in history[-8:]) + "\n"
|
||||
prompt += f"User REQUEST:\n{instruction}\n\nReturn the complete updated profile (English) and the reply (Portuguese)."
|
||||
return self.ask(REFINE_SYSTEM, prompt, REFINE_SCHEMA, [], search=search,
|
||||
timeout=RESEARCH_TIMEOUT_S if search else TIMEOUT_S)
|
||||
|
||||
def translate_game(self, profile: dict, target: str) -> dict:
|
||||
"""Traduz o perfil inteiro (pt-BR <-> en-US), mesmo formato, sem busca. Nomes oficiais e hashtags ficam."""
|
||||
language = TRANSLATE_TARGETS.get(target, target)
|
||||
prompt = (f"Target language: {language}\nProfile JSON:\n{json.dumps(profile, ensure_ascii=False, indent=1)}\n\n"
|
||||
"Return the translated profile.")
|
||||
return self.ask(TRANSLATE_SYSTEM, prompt, PROFILE_SCHEMA, [], timeout=RESEARCH_TIMEOUT_S)
|
||||
|
||||
def detect_cam(self, images: list[Path]) -> dict:
|
||||
return self.ask(CAM_SYSTEM, "Analise os frames anexados (mesma live, instantes diferentes).", CAM_SCHEMA, images)
|
||||
|
||||
# ---------- execução
|
||||
def ask(self, system: str, prompt: str, schema: dict, images: list[Path], *, search: bool = False,
|
||||
timeout: int = TIMEOUT_S, model: str | None = None) -> dict:
|
||||
model = model or self.model
|
||||
if self.provider == "codex":
|
||||
return self._codex(system, prompt, schema, images, search, timeout, model)
|
||||
if self.provider == "claude":
|
||||
return self._claude(system, prompt, schema, images, search, timeout, model)
|
||||
raise JudgeError("IA desligada")
|
||||
"""Chama a IA escolhida; se ela falhar por indisponibilidade, a próxima da cadeia de reserva (com o modelo
|
||||
padrão DELA) e a que falhou fica em pausa. Erro de conteúdo (JSON inválido, campos faltando) não troca."""
|
||||
if not self.enabled:
|
||||
raise JudgeError("IA desligada", unavailable=False)
|
||||
chain = self.fallback_chain()
|
||||
if not chain:
|
||||
why = self._skip_reason(self.provider, self.ai.settings()) or "nenhuma IA pronta"
|
||||
raise JudgeError(f"{PROVIDER_NAMES[self.provider]} indisponível: {why} (veja Configurações → IA)",
|
||||
unavailable=True)
|
||||
fallback_on = self.ai.settings()["fallback"]["enabled"]
|
||||
attempts: list[str] = []
|
||||
for provider in chain:
|
||||
use_model = (model or self.model) if provider == self.provider else DEFAULT_MODELS[provider]
|
||||
try:
|
||||
data = self._call(provider, system, prompt, schema, images, search, timeout, use_model)
|
||||
except JudgeError as exc:
|
||||
text = str(exc)
|
||||
unavailable = exc.unavailable if exc.unavailable is not None else is_availability_error(text)
|
||||
attempts.append(f"{provider}:{use_model}: {text}")
|
||||
if not unavailable:
|
||||
# Erro de conteúdo: a IA respondeu, o pedido é que não deu certo. Não troca de IA.
|
||||
raise JudgeError(" · ".join(attempts) if len(attempts) > 1 else text, unavailable=False) from exc
|
||||
if fallback_on:
|
||||
self.pause(provider, text)
|
||||
log.warning("IA %s indisponível (%s); tentando a reserva", provider, text[:160])
|
||||
continue
|
||||
raise JudgeError(text, unavailable=True) from exc
|
||||
self._local.responder = f"{provider}:{use_model}"
|
||||
if provider != self.provider:
|
||||
log.info("respondido pela reserva %s:%s", provider, use_model)
|
||||
return data
|
||||
raise JudgeError("nenhuma IA respondeu — " + " · ".join(attempts)[:900], unavailable=True)
|
||||
|
||||
def _run(self, args: list[str], stdin: str, cwd: Path, timeout: int) -> subprocess.CompletedProcess:
|
||||
def _call(self, provider: str, system: str, prompt: str, schema: dict, images: list[Path], search: bool,
|
||||
timeout: int, model: str) -> dict:
|
||||
if provider == "codex":
|
||||
return self._codex(system, prompt, schema, images, search, timeout, model)
|
||||
if provider == "claude":
|
||||
return self._claude(system, prompt, schema, images, search, timeout, model)
|
||||
if provider == "gemini":
|
||||
return self._gemini(system, prompt, schema, images, search, timeout, model)
|
||||
raise JudgeError("IA desligada", unavailable=False)
|
||||
|
||||
def _run(self, args: list[str], stdin: str, cwd: Path, timeout: int, provider: str) -> subprocess.CompletedProcess:
|
||||
# `env` por provedor: modo chave de API (só nesta chamada) ou sessão logada (doc/ia.md).
|
||||
try:
|
||||
result = subprocess.run(args, input=stdin.encode("utf-8"), capture_output=True, timeout=timeout, cwd=cwd,
|
||||
creationflags=NO_WINDOW)
|
||||
creationflags=NO_WINDOW, env=self.ai.provider_env(provider))
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise JudgeError(f"a CLI passou de {timeout} s") from exc
|
||||
raise JudgeError(f"a CLI passou de {timeout} s (tempo esgotado)", unavailable=True) from exc
|
||||
except OSError as exc:
|
||||
raise JudgeError(f"não consegui rodar a CLI: {exc}") from exc
|
||||
raise JudgeError(f"não consegui rodar a CLI: {exc}", unavailable=True) from exc
|
||||
if result.returncode != 0:
|
||||
tail = result.stderr.decode("utf-8", errors="replace").strip().splitlines()[-2:]
|
||||
raise JudgeError(f"a CLI saiu com código {result.returncode}: {' | '.join(tail)[:300]}")
|
||||
err = result.stderr.decode("utf-8", errors="replace").strip()
|
||||
out = result.stdout.decode("utf-8", errors="replace").strip()
|
||||
tail = (err or out).splitlines()[-2:]
|
||||
message = f"a CLI saiu com código {result.returncode}: {' | '.join(tail)[:300]}"
|
||||
# Classifica pelo texto inteiro (o motivo pode estar antes das 2 últimas linhas, ou só no stdout).
|
||||
raise JudgeError(message, unavailable=is_availability_error(err + "\n" + out))
|
||||
return result
|
||||
|
||||
def _codex(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
|
||||
model: str) -> dict:
|
||||
cmd = find_codex()
|
||||
if not cmd:
|
||||
raise JudgeError("Codex CLI não encontrado (npm install -g @openai/codex; codex login)")
|
||||
raise JudgeError("Codex CLI não encontrado (npm install -g @openai/codex; codex login)", unavailable=True)
|
||||
self.workdir.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(dir=self.workdir) as tmp:
|
||||
schema_file, out = Path(tmp) / "schema.json", Path(tmp) / "answer.json"
|
||||
@@ -594,17 +876,17 @@ class Judge:
|
||||
args = [*cmd, *(["--search"] if search else []), "exec", "--skip-git-repo-check", "--ephemeral",
|
||||
"--sandbox", "read-only", "-c", 'model_reasoning_effort="low"', *lean, "-m", model, *image_args,
|
||||
"--output-schema", str(schema_file), "-o", str(out), "-C", tmp, "-"]
|
||||
self._run(args, stdin, Path(tmp), timeout)
|
||||
self._run(args, stdin, Path(tmp), timeout, "codex")
|
||||
try:
|
||||
return json.loads(out.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError) as exc:
|
||||
raise JudgeError("o Codex não devolveu o JSON pedido") from exc
|
||||
raise JudgeError("o Codex não devolveu o JSON pedido", unavailable=False) from exc
|
||||
|
||||
def _claude(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
|
||||
model: str) -> dict:
|
||||
cmd = find_claude()
|
||||
if not cmd:
|
||||
raise JudgeError("Claude Code CLI não encontrado")
|
||||
raise JudgeError("Claude Code CLI não encontrado", unavailable=True)
|
||||
self.workdir.mkdir(parents=True, exist_ok=True)
|
||||
tools = (["Read"] if images else []) + (["WebSearch", "WebFetch"] if search else [])
|
||||
extra: list[str] = []
|
||||
@@ -619,19 +901,76 @@ class Judge:
|
||||
# --setting-sources: sem plugins e hooks do usuário (medido: 3,7 → 2,6 mil tokens fixos, 5,5 → 2,8 s).
|
||||
"--no-session-persistence", "--strict-mcp-config", "--setting-sources", "project,local",
|
||||
"--system-prompt", system]
|
||||
result = self._run(args, prompt, self.workdir, timeout)
|
||||
result = self._run(args, prompt, self.workdir, timeout, "claude")
|
||||
try:
|
||||
envelope = json.loads(result.stdout.decode("utf-8", errors="replace"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise JudgeError("o Claude não devolveu JSON") from exc
|
||||
raise JudgeError("o Claude não devolveu JSON", unavailable=False) from exc
|
||||
if envelope.get("is_error"):
|
||||
# Pode ser cota/login ("Credit balance is too low", "Not logged in"): o texto decide (unavailable=None).
|
||||
raise JudgeError(f"o Claude terminou com erro: {str(envelope.get('result'))[:200]}")
|
||||
data = envelope.get("structured_output")
|
||||
if not isinstance(data, dict):
|
||||
try:
|
||||
data = json.loads(envelope.get("result") or "")
|
||||
except json.JSONDecodeError as exc:
|
||||
raise JudgeError("o Claude não devolveu o JSON pedido") from exc
|
||||
raise JudgeError("o Claude não devolveu o JSON pedido", unavailable=False) from exc
|
||||
return data
|
||||
|
||||
def _gemini(self, system: str, prompt: str, schema: dict, images: list[Path], search: bool, timeout: int,
|
||||
model: str) -> dict:
|
||||
"""Gemini CLI headless (`-o json` → `{"response": "<texto>", "stats": …}`). Não há `--output-schema`: o
|
||||
schema vai no texto e o JSON é extraído da resposta. `--approval-mode plan` = só leitura (a busca
|
||||
google_web_search continua liberada). O corpo grande vai pela entrada padrão (o Gemini junta o `-p` ao
|
||||
stdin), para não estourar o limite de linha de comando do Windows; no `-p` só a instrução curta e os
|
||||
`@arquivo` das imagens.
|
||||
|
||||
Pasta de trabalho FORA do repositório (temp do sistema): o `@arquivo` respeita o .gitignore e `data/` é
|
||||
ignorado no CenaForge; fora do repo o Gemini também não carrega GEMINI.md do projeto (menos tokens fixos).
|
||||
As imagens são copiadas para lá com nomes curtos e referenciadas por caminho relativo."""
|
||||
cmd = find_gemini()
|
||||
if not cmd:
|
||||
raise JudgeError("Gemini CLI não encontrado (npm install -g @google/gemini-cli; chave em Configurações → IA)",
|
||||
unavailable=True)
|
||||
with tempfile.TemporaryDirectory(prefix="cenaforge-gemini-") as tmp:
|
||||
refs: list[str] = []
|
||||
for i, img in enumerate(images):
|
||||
src = Path(img)
|
||||
name = f"frame-{i + 1:02d}{src.suffix.lower() or '.jpg'}"
|
||||
try:
|
||||
shutil.copyfile(src, Path(tmp) / name)
|
||||
except OSError as exc:
|
||||
raise JudgeError(f"não consegui preparar a imagem {src.name}: {exc}", unavailable=False) from exc
|
||||
refs.append(f"@{name}")
|
||||
stdin = (system + "\n\n---\n\n" + prompt
|
||||
+ "\n\n---\n\nResponda SÓ com um objeto JSON válido (sem texto antes ou depois, sem cercas ```), "
|
||||
"que siga exatamente este JSON Schema:\n" + json.dumps(schema, ensure_ascii=False))
|
||||
short = ("Siga as instruções e os dados recebidos acima e responda só com o JSON pedido."
|
||||
+ (" Use a busca na web (google_web_search) para confirmar os fatos." if search else
|
||||
" Não use ferramentas."))
|
||||
if refs:
|
||||
short += " Frames anexados, na ordem: " + " ".join(refs)
|
||||
args = [*cmd, "-p", short, "-o", "json", "--approval-mode", "plan", "--skip-trust", "-m", model]
|
||||
result = self._run(args, stdin, Path(tmp), timeout, "gemini")
|
||||
return parse_gemini_output(result.stdout.decode("utf-8", errors="replace"))
|
||||
|
||||
|
||||
def parse_gemini_output(stdout: str) -> dict:
|
||||
"""Envelope do `gemini -o json` → objeto JSON da resposta. Erro no envelope é classificado pelo texto (cota,
|
||||
chave…); resposta sem JSON é erro de conteúdo."""
|
||||
envelope = extract_json_object(stdout, fences=False)
|
||||
if envelope is None:
|
||||
raise JudgeError("o Gemini não devolveu JSON", unavailable=False)
|
||||
error = envelope.get("error")
|
||||
if error:
|
||||
message = error.get("message") if isinstance(error, dict) else str(error)
|
||||
raise JudgeError(f"o Gemini terminou com erro: {str(message or error)[:200]}")
|
||||
response = envelope.get("response")
|
||||
if not isinstance(response, str):
|
||||
raise JudgeError("o Gemini não devolveu a resposta", unavailable=False)
|
||||
data = extract_json_object(response)
|
||||
if data is None:
|
||||
raise JudgeError("o Gemini não devolveu o JSON pedido", unavailable=False)
|
||||
return data
|
||||
|
||||
|
||||
|
||||
+116
-28
@@ -19,7 +19,7 @@ from pathlib import Path
|
||||
from . import capture, layout, media
|
||||
from .config import REPO_ROOT
|
||||
from .db import Database, loads, now
|
||||
from .judge import JudgeError
|
||||
from .judge import LANGUAGE_NAMES, JudgeError
|
||||
from .scoring import timeline as timeline_series
|
||||
from .scoring import Word
|
||||
from .sources import SourceError, parse_source
|
||||
@@ -37,21 +37,43 @@ class UserError(Exception):
|
||||
self.message, self.status = message, status
|
||||
|
||||
|
||||
# Idiomas aceitos em `language` (fonte e sessão). '' = padrão do serviço (CLIPPER_LANGUAGE). O painel oferece os mesmos.
|
||||
LANGUAGES = tuple(LANGUAGE_NAMES)
|
||||
|
||||
|
||||
def check_language(value: str | None) -> str | None:
|
||||
"""None = não mexer; '' = voltar ao padrão; código válido = usar. Outra coisa é erro legível."""
|
||||
if value is None:
|
||||
return None
|
||||
code = value.strip()
|
||||
if code and code not in LANGUAGES:
|
||||
raise UserError(f"Idioma inválido: use {', '.join(LANGUAGES)} (ou vazio para o padrão).")
|
||||
return code
|
||||
|
||||
|
||||
class ChannelIn(BaseModel):
|
||||
url: str = Field(min_length=3, max_length=300)
|
||||
displayName: str | None = Field(default=None, max_length=60)
|
||||
monitor: bool = True
|
||||
authorized: bool = False
|
||||
language: str | None = Field(default=None, max_length=12)
|
||||
|
||||
|
||||
class ChannelPatch(BaseModel):
|
||||
displayName: str | None = Field(default=None, max_length=60)
|
||||
monitor: bool | None = None
|
||||
authorized: bool | None = None
|
||||
language: str | None = Field(default=None, max_length=12)
|
||||
|
||||
|
||||
class SessionIn(BaseModel):
|
||||
url: str = Field(min_length=3, max_length=300)
|
||||
language: str | None = Field(default=None, max_length=12)
|
||||
|
||||
|
||||
class StopIn(BaseModel):
|
||||
"""Parar à mão: `pauseMonitor` (padrão) deixa a fonte com o monitor pausado até você religar."""
|
||||
pauseMonitor: bool = True
|
||||
|
||||
|
||||
class ManualClipIn(BaseModel):
|
||||
@@ -62,7 +84,7 @@ class ManualClipIn(BaseModel):
|
||||
|
||||
|
||||
class JudgeIn(BaseModel):
|
||||
provider: Literal["codex", "claude", "off"]
|
||||
provider: Literal["codex", "claude", "gemini", "off"]
|
||||
model: str = Field(default="", max_length=80, pattern=r"^[A-Za-z0-9._:-]*$")
|
||||
minScore: float = Field(default=6, ge=0, le=10)
|
||||
# Modelo do ANALISTA (1º juiz, vê os frames); vazio = o mesmo do editor. None = não mexer.
|
||||
@@ -80,9 +102,17 @@ class GameIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
|
||||
|
||||
class MissionIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=160)
|
||||
chapter: str = Field(default="", max_length=120)
|
||||
summary: str = Field(default="", max_length=500)
|
||||
completion_triggers: list[str] = Field(default_factory=list, max_length=8)
|
||||
|
||||
|
||||
class GameProfileIn(BaseModel):
|
||||
"""Perfil do jogo editado à mão no painel (mesmos campos que a IA devolve)."""
|
||||
"""Perfil do jogo editado à mão no painel (mesmos campos que a IA devolve), em um dos dois idiomas."""
|
||||
name: str = Field(default="", max_length=120)
|
||||
aliases: list[str] = Field(default_factory=list, max_length=10) # outros nomes (categoria, abreviação)
|
||||
summary: str = Field(default="", max_length=1500)
|
||||
genre: str = Field(default="", max_length=120)
|
||||
mechanics: list[str] = Field(default_factory=list, max_length=30)
|
||||
@@ -92,6 +122,14 @@ class GameProfileIn(BaseModel):
|
||||
news: list[str] = Field(default_factory=list, max_length=30)
|
||||
hashtags: list[str] = Field(default_factory=list, max_length=20) # do jogo, a principal primeiro (app/hashtags.py)
|
||||
sources: list[str] = Field(default_factory=list, max_length=20)
|
||||
missions: list[MissionIn] = Field(default_factory=list, max_length=120)
|
||||
end_triggers: list[str] = Field(default_factory=list, max_length=12) # sinais gerais de fim de missão
|
||||
|
||||
|
||||
class GameIn(BaseModel):
|
||||
"""Jogo cadastrado pelo painel; `notes` = pista para a pesquisa (vira o 1º pedido guardado)."""
|
||||
name: str = Field(min_length=2, max_length=120)
|
||||
notes: str = Field(default="", max_length=1500)
|
||||
|
||||
|
||||
class ChatTurnIn(BaseModel):
|
||||
@@ -102,7 +140,8 @@ class ChatTurnIn(BaseModel):
|
||||
class GameRefineIn(BaseModel):
|
||||
instruction: str = Field(min_length=3, max_length=1500)
|
||||
search: bool = True # deixa a IA confirmar na web (mais lento); sem busca é quase instantâneo
|
||||
section: Literal["", "summary", "clip_worthy", "avoid", "mechanics", "news", "jargon", "hashtags", "sources"] = ""
|
||||
section: Literal["", "summary", "clip_worthy", "avoid", "mechanics", "news", "jargon", "hashtags", "sources",
|
||||
"missions", "end_triggers", "aliases"] = ""
|
||||
history: list[ChatTurnIn] = Field(default_factory=list, max_length=20) # conversa do chat da seção
|
||||
|
||||
|
||||
@@ -143,6 +182,8 @@ def clip_view(row: dict) -> dict:
|
||||
"aspect": row.get("aspect") or "vertical",
|
||||
"createdAt": row["created_at"], "updatedAt": row["updated_at"],
|
||||
"channelId": row.get("channel_id"), "platform": row.get("platform"), "sessionUrl": row.get("url"),
|
||||
# Idioma da sessão (resolvido no SELECT: o da sessão ou o padrão do serviço). Ausente só em consultas antigas.
|
||||
"language": row.get("language"),
|
||||
# Editor de cortes: existe projeto de edição? (o export renderiza por ele; capa gerada no export)
|
||||
"edit": ({"updatedAt": row["edit_updated_at"], "exportedAt": row.get("edit_exported_at"), "cover": row.get("edit_cover"),
|
||||
"origin": row.get("edit_origin")}
|
||||
@@ -174,14 +215,19 @@ def session_view(row: dict, engine: Engine) -> dict:
|
||||
# O que a captura gravou de fato (1º bloco de cada execução): qualidade pedida, largura, altura, qps, codec,
|
||||
# kbps, GB/h e `mixed` (retomada em outra resolução). None = sessão antiga ou ainda sem bloco.
|
||||
"capture": loads(row.get("capture_json"), None),
|
||||
# Idioma falado na live (resolvido: o da sessão, senão o padrão do serviço).
|
||||
"language": row.get("language") or engine.settings.language,
|
||||
}
|
||||
|
||||
|
||||
def channel_view(row: dict) -> dict:
|
||||
def channel_view(row: dict, default_language: str = "") -> dict:
|
||||
return {
|
||||
"id": row["id"], "platform": row["platform"], "channel": row["channel"], "url": row["url"],
|
||||
"displayName": row["display_name"], "monitor": bool(row["monitor"]), "authorized": bool(row["authorized"]),
|
||||
"lastCheckAt": row["last_check_at"], "lastStatus": row["last_status"], "createdAt": row["created_at"],
|
||||
# Monitor pausado porque você parou uma sessão à mão (não grava de novo até religar).
|
||||
"monitorPausedAt": row.get("monitor_paused_at"), "monitorPausedBySession": row.get("monitor_paused_session"),
|
||||
"language": row.get("language") or default_language,
|
||||
}
|
||||
|
||||
|
||||
@@ -386,27 +432,62 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
engine.intel.set_game(session_id, body.name.strip(), "user")
|
||||
return session_view(_session(session_id), engine)
|
||||
|
||||
def game_view(g: dict) -> dict:
|
||||
# `profile` = português (o painel mostra); `profileAi` = inglês (vai nos prompts; null = jogo antigo, a IA
|
||||
# usa `profile`). Contrato em doc/clipador/JOGOS.md.
|
||||
return {"id": g["id"], "name": g["name"], "status": g["status"], "error": g["error"],
|
||||
"model": g["model"], "researchedAt": g["researched_at"], "editedAt": g.get("edited_at"),
|
||||
"notes": loads(g.get("notes_json"), []), "profile": loads(g["profile_json"], None),
|
||||
"profileAi": loads(g.get("profile_ai_json"), None), "aiLanguage": "en-US",
|
||||
"translatedAt": g.get("translated_at"), "aliases": loads(g.get("aliases_json"), [])}
|
||||
|
||||
@app.get("/v1/games")
|
||||
def list_games():
|
||||
return {"games": [{"id": g["id"], "name": g["name"], "status": g["status"], "error": g["error"],
|
||||
"model": g["model"], "researchedAt": g["researched_at"], "editedAt": g.get("edited_at"),
|
||||
"notes": loads(g.get("notes_json"), []), "profile": loads(g["profile_json"], None)}
|
||||
for g in db.all("SELECT * FROM games ORDER BY name")]}
|
||||
return {"games": [game_view(g) for g in db.all("SELECT * FROM games ORDER BY name")]}
|
||||
|
||||
@app.post("/v1/games", status_code=201)
|
||||
def add_game(body: GameIn):
|
||||
"""Cadastra um jogo e pesquisa em segundo plano (o jogo aparece `pending` até a pesquisa terminar)."""
|
||||
try:
|
||||
gid = engine.intel.add_game(body.name, body.notes)
|
||||
except LookupError as exc:
|
||||
raise UserError(str(exc), 409) from exc
|
||||
except ValueError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return {**list_games(), "id": gid}
|
||||
|
||||
@app.delete("/v1/games/{game_id}")
|
||||
def delete_game(game_id: str):
|
||||
try:
|
||||
engine.intel.delete_game(game_id)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc), 404) from exc
|
||||
return list_games()
|
||||
|
||||
@app.post("/v1/games/{game_id}/research")
|
||||
def research_game(game_id: str):
|
||||
"""Pesquisa (de novo) o jogo na web pela IA. Leva de 15 s a alguns minutos. Os pedidos guardados entram junto."""
|
||||
"""Pesquisa (de novo) o jogo na web pela IA, em inglês, e traduz para português. Leva de 15 s a alguns minutos.
|
||||
Os pedidos guardados entram junto."""
|
||||
try:
|
||||
engine.intel.research(game_id)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return list_games()
|
||||
|
||||
@app.put("/v1/games/{game_id}")
|
||||
def put_game_profile(game_id: str, body: GameProfileIn):
|
||||
"""Grava o perfil editado à mão. A IA passa a usar na hora."""
|
||||
@app.post("/v1/games/{game_id}/translate")
|
||||
def translate_game(game_id: str):
|
||||
"""Gera a versão da IA (inglês) a partir da portuguesa (jogos de antes dos perfis bilíngues)."""
|
||||
try:
|
||||
engine.intel.save_profile(game_id, body.model_dump())
|
||||
engine.intel.translate(game_id)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return list_games()
|
||||
|
||||
@app.put("/v1/games/{game_id}")
|
||||
def put_game_profile(game_id: str, body: GameProfileIn, lang: Literal["pt", "en"] = "pt"):
|
||||
"""Grava o perfil editado à mão no idioma `lang` e traduz para o outro. A IA passa a usar na hora."""
|
||||
try:
|
||||
engine.intel.save_profile(game_id, body.model_dump(), lang)
|
||||
except JudgeError as exc:
|
||||
raise UserError(str(exc), 404) from exc
|
||||
return list_games()
|
||||
@@ -440,7 +521,7 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
# ---------- canais
|
||||
@app.get("/v1/channels")
|
||||
def list_channels():
|
||||
return {"channels": [channel_view(r) for r in db.all("SELECT * FROM channels ORDER BY display_name")]}
|
||||
return {"channels": [channel_view(r, settings.language) for r in db.all("SELECT * FROM channels ORDER BY display_name")]}
|
||||
|
||||
@app.post("/v1/channels", status_code=201)
|
||||
def create_channel(body: ChannelIn):
|
||||
@@ -449,22 +530,27 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
raise UserError("Para monitorar, use o link do canal (ex.: twitch.tv/alanzoka), não de um vídeo.")
|
||||
if db.get("SELECT 1 FROM channels WHERE id = ?", source.channel_id):
|
||||
raise UserError("Esse canal já está na lista.", 409)
|
||||
db.run("INSERT INTO channels (id, platform, channel, url, display_name, monitor, authorized, created_at)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
language = check_language(body.language) or ""
|
||||
db.run("INSERT INTO channels (id, platform, channel, url, display_name, monitor, authorized, created_at, language)"
|
||||
" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
source.channel_id, source.platform, source.channel, source.url,
|
||||
(body.displayName or source.channel.lstrip("@")).strip(), int(body.monitor), int(body.authorized), now())
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", source.channel_id))
|
||||
(body.displayName or source.channel.lstrip("@")).strip(), int(body.monitor), int(body.authorized), now(), language)
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", source.channel_id), settings.language)
|
||||
|
||||
@app.patch("/v1/channels/{channel_id}")
|
||||
def update_channel(channel_id: str, body: ChannelPatch):
|
||||
row = db.get("SELECT * FROM channels WHERE id = ?", channel_id)
|
||||
if not row:
|
||||
raise UserError("Canal não encontrado.", 404)
|
||||
db.run("UPDATE channels SET display_name = ?, monitor = ?, authorized = ? WHERE id = ?",
|
||||
language = check_language(body.language)
|
||||
db.run("UPDATE channels SET display_name = ?, monitor = ?, authorized = ?, language = ? WHERE id = ?",
|
||||
(body.displayName or row["display_name"]).strip(),
|
||||
int(body.monitor if body.monitor is not None else row["monitor"]),
|
||||
int(body.authorized if body.authorized is not None else row["authorized"]), channel_id)
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", channel_id))
|
||||
int(body.authorized if body.authorized is not None else row["authorized"]),
|
||||
language if language is not None else row.get("language") or "", channel_id)
|
||||
if body.monitor is True:
|
||||
engine.clear_monitor_pause(channel_id) # "Religar" no painel
|
||||
return channel_view(db.get("SELECT * FROM channels WHERE id = ?", channel_id), settings.language)
|
||||
|
||||
@app.delete("/v1/channels/{channel_id}", status_code=204)
|
||||
def delete_channel(channel_id: str):
|
||||
@@ -491,8 +577,9 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
def create_session(body: SessionIn):
|
||||
source = parse_source(body.url)
|
||||
channel = db.get("SELECT id FROM channels WHERE id = ?", source.channel_id) if source.channel else None
|
||||
language = check_language(body.language)
|
||||
try:
|
||||
session_id = engine.start_session(body.url, channel["id"] if channel else None)
|
||||
session_id = engine.start_session(body.url, channel["id"] if channel else None, language=language)
|
||||
except RuntimeError as exc:
|
||||
raise UserError(str(exc)) from exc
|
||||
return session_view(db.get("SELECT * FROM sessions WHERE id = ?", session_id), engine)
|
||||
@@ -533,8 +620,9 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
return clip_view(_clip(int(cur.lastrowid)))
|
||||
|
||||
@app.post("/v1/sessions/{session_id}/stop")
|
||||
def stop_session(session_id: int):
|
||||
engine.stop_session(session_id)
|
||||
def stop_session(session_id: int, body: StopIn | None = None):
|
||||
"""Para a gravação à mão. Sem corpo (ou `pauseMonitor: true`): a fonte fica com o monitor pausado até religar."""
|
||||
engine.stop_session(session_id, pause_monitor=body.pauseMonitor if body else True)
|
||||
return {"ok": True}
|
||||
|
||||
@app.post("/v1/sessions/{session_id}/resume")
|
||||
@@ -566,8 +654,8 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
channel: str | None = None, ids: str | None = None):
|
||||
"""Filtros opcionais (todos separados por vírgula): `status`, `channel` (fontes, ex.: twitch-alanzoka) e `ids`.
|
||||
O despachante de publicação do painel usa `channel` + `status=ready,approved` e `ids` para conferir a fila."""
|
||||
sql = "SELECT c.*, s.channel_id, s.platform, s.url, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE 1 = 1"
|
||||
params: list = []
|
||||
sql = "SELECT c.*, s.channel_id, s.platform, s.url, COALESCE(NULLIF(s.language, ''), ?) AS language, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE 1 = 1"
|
||||
params: list = [settings.language]
|
||||
if status:
|
||||
sql += " AND c.status IN (" + ",".join("?" * len(status.split(","))) + ")"
|
||||
params += status.split(",")
|
||||
@@ -590,7 +678,7 @@ def create_app(settings: Settings | None = None, engine: Engine | None = None, s
|
||||
return {"clips": [clip_view(r) for r in db.all(sql, *params)]}
|
||||
|
||||
def _clip(clip_id: int) -> dict:
|
||||
row = db.get("SELECT c.*, s.channel_id, s.platform, s.url, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE c.id = ?", clip_id)
|
||||
row = db.get("SELECT c.*, s.channel_id, s.platform, s.url, COALESCE(NULLIF(s.language, ''), ?) AS language, e.updated_at AS edit_updated_at, e.exported_at AS edit_exported_at, e.cover AS edit_cover, e.origin AS edit_origin FROM clips c JOIN sessions s ON s.id = c.session_id LEFT JOIN edits e ON e.clip_id = c.id WHERE c.id = ?", settings.language, clip_id)
|
||||
if not row:
|
||||
raise UserError("Corte não encontrado.", 404)
|
||||
return row
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
{
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6", "GTAVI", "Grand Theft Auto 6"],
|
||||
"researchedAt": "2026-11-18T12:00:00Z",
|
||||
"sources": [
|
||||
"https://www.rockstargames.com/VI",
|
||||
"https://www.forbes.com/sites/erikkain/2026/11/16/gta-6-release-date-time-ps5-xbox-series-x-download-size-day-one-update/",
|
||||
"https://hothardware.com/news/gta-6-extended-look-reveals-story-missions-and-massive-map-details",
|
||||
"https://lfcarry.com/guides/gta-6-chapter-list-walkthrough",
|
||||
"https://www.gtabase.com/articles/gta-6/gta-6-previews-recap-all-new-gameplay-features-revealed",
|
||||
"https://allthings.how/gta-6-wanted-system-explained-how-heat-builds-and-how-you-lose-it/",
|
||||
"https://www.redbull.com/int-en/gta-6-gameplay-details",
|
||||
"https://www.gfinityesports.com/article/gta-6-map-guide-every-confirmed-location-in-leonida"
|
||||
],
|
||||
"profileAi": {
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6", "GTAVI", "Grand Theft Auto 6"],
|
||||
"genre": "Open-world action-adventure / crime",
|
||||
"summary": "Rockstar's open-world crime game set in the state of Leonida (a Florida parody), centered on Vice City. You play as Jason Duval and Lucia Caminos, a criminal couple who start with small robberies and work up to bigger jobs, switching between them (even mid-action). Released November 19, 2026 on PS5 and Xbox Series X|S.",
|
||||
"mechanics": [
|
||||
"Two playable protagonists (Jason and Lucia), switchable at any time, including mid-chase",
|
||||
"Robberies of stores, diners and gas stations early on; bigger heists later (bank job at Sinfrontera National Bank shown in trailers)",
|
||||
"Wanted level with up to six stars plus a Heat system: police only react to reported crimes (witness or alarm); the HUD shows what cops know (vehicle, outfit, face, weapons, CCTV)",
|
||||
"Losing the cops: break line of sight, change outfit or vehicle, split Jason and Lucia up, wear masks before crimes",
|
||||
"Carjacking with a slim jim instead of breaking windows; low-end cars and basic locks at the start",
|
||||
"Phone and in-game social media (calls, texts, feeds); the couple can meet up for crimes or dates in free roam",
|
||||
"Huge map: Vice City, Leonida Keys, Grassrivers, Port Gellhorn, Ambrosia, Mount Kalaga; wildlife including alligators",
|
||||
"Activities: hunting and fishing, nightlife, gym, side jobs and strangers"
|
||||
],
|
||||
"clip_worthy": [
|
||||
"Heist or store robbery going wrong: alarm, hostage, partner panics, cops arrive early",
|
||||
"Wild police chase escalating to 5-6 stars, ending in a crash or a lucky escape",
|
||||
"Switching between Jason and Lucia at the perfect moment in a chase or shootout",
|
||||
"Alligator, wildlife or 'Florida Man' NPC chaos (bizarre locals, viral-style street scenes)",
|
||||
"Physics and ragdoll fails: car flips, boat or jet ski crashes, falling off buildings",
|
||||
"Streamer's first reaction to a big reveal: Vice City skyline, a story twist, a famous character",
|
||||
"Mission climax: last-second escape, the payout being counted, or a dramatic WASTED/BUSTED right at the end",
|
||||
"Funny dialogue between Jason and Lucia or with NPCs (Cal, Boobie Ike, Raul)",
|
||||
"Graphics and realism 'wow' moments the chat spams about (crowds, weather, beach)",
|
||||
"Launch-day glitches and bugs (cars in walls, T-poses, NPC weirdness)"
|
||||
],
|
||||
"avoid": [
|
||||
"Menus, map browsing, wardrobe and shopping screens",
|
||||
"Long cutscenes with no reaction from the streamer (also copyright-heavy)",
|
||||
"Driving across the map with nothing happening",
|
||||
"Loading screens, settings and install or update talk",
|
||||
"Repetitive gunfights with no fail, escape or joke"
|
||||
],
|
||||
"jargon": [
|
||||
"Leonida (the state), Vice City / VC, the Keys",
|
||||
"Jason, Lucia (Lu), Cal, Boobie Ike, Raul Bautista, Brian, Dre'Quan, Real Dimez",
|
||||
"estrelas / stars / procurado / wanted, heat, '6 estrelas'",
|
||||
"WASTED / BUSTED",
|
||||
"assalto / roubo / golpe / heist",
|
||||
"boca / stash house",
|
||||
"Florida Man",
|
||||
"chave micha / slim jim",
|
||||
"trocar de personagem / switch",
|
||||
"GTA Online / GTAO (when online launches)"
|
||||
],
|
||||
"news": [
|
||||
"Nov 2026: launch on November 19, 2026 (midnight local time, rolling by region), PS5 and Xbox Series X|S only; no PC version announced",
|
||||
"Nov 2026: download of up to ~212 GB with a day-one update",
|
||||
"Nov 2025: release moved from May 26, 2026 to November 19, 2026",
|
||||
"2026: the 'An Extended Look' gameplay video showed story mission openings, robberies and the wanted/Heat HUD",
|
||||
"May 2025: Trailer 2 introduced Jason, Lucia and the supporting cast"
|
||||
],
|
||||
"hashtags": ["#GTA6", "#GTAVI", "#GrandTheftAutoVI", "#ViceCity", "#GTA6Brasil", "#Rockstar"],
|
||||
"sources": [
|
||||
"https://www.rockstargames.com/VI",
|
||||
"https://www.forbes.com/sites/erikkain/2026/11/16/gta-6-release-date-time-ps5-xbox-series-x-download-size-day-one-update/",
|
||||
"https://hothardware.com/news/gta-6-extended-look-reveals-story-missions-and-massive-map-details",
|
||||
"https://lfcarry.com/guides/gta-6-chapter-list-walkthrough",
|
||||
"https://www.gtabase.com/articles/gta-6/gta-6-previews-recap-all-new-gameplay-features-revealed",
|
||||
"https://allthings.how/gta-6-wanted-system-explained-how-heat-builds-and-how-you-lose-it/",
|
||||
"https://www.redbull.com/int-en/gta-6-gameplay-details",
|
||||
"https://www.gfinityesports.com/article/gta-6-map-guide-every-confirmed-location-in-leonida"
|
||||
],
|
||||
"missions": [
|
||||
{
|
||||
"name": "Boobie Ike stash pickup (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "A drug pickup for Boobie Ike that turns into a police raid.",
|
||||
"completion_triggers": ["Escaping the raid and losing the wanted stars", "Dropping the package at Boobie's spot or the end-of-mission cutscene", "Mission complete banner or results screen"]
|
||||
},
|
||||
{
|
||||
"name": "Raul Bautista getaway (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "A getaway job for the professional robber Raul Bautista.",
|
||||
"completion_triggers": ["Reaching the drop-off or safe point with the police lost", "Payout or split shown on screen", "Mission complete banner or results screen"]
|
||||
},
|
||||
{
|
||||
"name": "Skyscraper security job (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "A security job that turns into a hostage situation inside a skyscraper.",
|
||||
"completion_triggers": ["Hostage standoff resolved (shootout ends or a deal is made)", "Leaving the building or the escape cutscene", "Mission complete banner or results screen"]
|
||||
},
|
||||
{
|
||||
"name": "Rooftop party with a wealthy employer (descriptive name, not official)",
|
||||
"chapter": "Shown in 'An Extended Look' (pre-launch)",
|
||||
"summary": "Jason and Lucia meet a very wealthy, dubious employer at a rooftop party.",
|
||||
"completion_triggers": ["The conversation or cutscene with the employer ends", "A new contact appears on the phone", "Mission complete banner"]
|
||||
}
|
||||
],
|
||||
"end_triggers": [
|
||||
"Mission complete/passed banner or a results screen with time, accuracy or payout",
|
||||
"Robbery payout or money split counted on screen",
|
||||
"Wanted stars disappear (cops lost) right after the getaway",
|
||||
"Arriving at the drop-off, hideout or safehouse marker and the car stops",
|
||||
"Ending cutscene starts (camera leaves gameplay, letterbox bars)",
|
||||
"Failure: WASTED or BUSTED screen, or 'mission failed' with a retry prompt",
|
||||
"Phone call or text from the contact wrapping up the job",
|
||||
"Streamer says 'passou', 'consegui', 'acabou a missão' or celebrates; chat spams GG/W"
|
||||
]
|
||||
},
|
||||
"profile": {
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6", "GTAVI", "Grand Theft Auto 6"],
|
||||
"genre": "Ação e aventura em mundo aberto / crime",
|
||||
"summary": "Jogo de crime em mundo aberto da Rockstar no estado de Leonida (paródia da Flórida), com Vice City no centro. Você joga com Jason Duval e Lucia Caminos, um casal de criminosos que começa com roubos pequenos e sobe para trabalhos maiores, trocando entre os dois (até no meio da ação). Lançado em 19 de novembro de 2026 para PS5 e Xbox Series X|S.",
|
||||
"mechanics": [
|
||||
"Dois protagonistas jogáveis (Jason e Lucia), com troca a qualquer hora, inclusive no meio de uma perseguição",
|
||||
"Roubos de lojas, lanchonetes e postos no começo; golpes maiores depois (assalto ao Sinfrontera National Bank nos trailers)",
|
||||
"Procurado com até seis estrelas mais o sistema de Heat: a polícia só reage a crime denunciado (testemunha ou alarme); o HUD mostra o que a polícia sabe (carro, roupa, rosto, armas, câmeras)",
|
||||
"Despistar a polícia: sair do campo de visão, trocar roupa ou carro, separar Jason e Lucia, usar máscara antes do crime",
|
||||
"Roubo de carro com chave micha (slim jim) em vez de quebrar o vidro; carros fracos e trancas simples no início",
|
||||
"Celular e redes sociais do jogo (ligações, mensagens, feeds); o casal pode se encontrar para crimes ou encontros no mundo aberto",
|
||||
"Mapa enorme: Vice City, Leonida Keys, Grassrivers, Port Gellhorn, Ambrosia, Mount Kalaga; fauna com jacarés",
|
||||
"Atividades: caça e pesca, vida noturna, academia, trabalhos paralelos e personagens aleatórios"
|
||||
],
|
||||
"clip_worthy": [
|
||||
"Assalto ou roubo de loja dando errado: alarme, refém, parceiro em pânico, polícia chegando antes",
|
||||
"Perseguição policial que escala para 5-6 estrelas e termina em batida ou fuga na sorte",
|
||||
"Troca entre Jason e Lucia no momento perfeito de uma perseguição ou tiroteio",
|
||||
"Caos com jacaré, bichos ou NPC 'Florida Man' (moradores bizarros, cenas de rua tipo viral)",
|
||||
"Falhas de física: carro capotando, lancha ou jet ski batendo, queda de prédio",
|
||||
"Primeira reação do streamer a algo grande: horizonte de Vice City, reviravolta da história, personagem famoso",
|
||||
"Clímax de missão: fuga no último segundo, o dinheiro sendo contado, ou um WASTED/BUSTED bem no final",
|
||||
"Diálogo engraçado entre Jason e Lucia ou com NPCs (Cal, Boobie Ike, Raul)",
|
||||
"Momentos de 'olha esse gráfico' que o chat comenta (multidão, clima, praia)",
|
||||
"Bugs e glitches de lançamento (carro na parede, T-pose, NPC estranho)"
|
||||
],
|
||||
"avoid": [
|
||||
"Menus, mapa, guarda-roupa e telas de compra",
|
||||
"Cutscenes longas sem reação do streamer (e com risco de direitos autorais)",
|
||||
"Dirigir pelo mapa sem acontecer nada",
|
||||
"Telas de carregamento, configurações e papo de instalação ou atualização",
|
||||
"Tiroteio repetitivo sem falha, fuga ou piada"
|
||||
],
|
||||
"jargon": [
|
||||
"Leonida (o estado), Vice City / VC, the Keys",
|
||||
"Jason, Lucia (Lu), Cal, Boobie Ike, Raul Bautista, Brian, Dre'Quan, Real Dimez",
|
||||
"estrelas / stars / procurado / wanted, heat, '6 estrelas'",
|
||||
"WASTED / BUSTED",
|
||||
"assalto / roubo / golpe / heist",
|
||||
"boca / stash house",
|
||||
"Florida Man",
|
||||
"chave micha / slim jim",
|
||||
"trocar de personagem / switch",
|
||||
"GTA Online / GTAO (quando o online sair)"
|
||||
],
|
||||
"news": [
|
||||
"nov/2026: lançamento em 19 de novembro de 2026 (meia-noite no horário local, por região), só PS5 e Xbox Series X|S; sem versão de PC anunciada",
|
||||
"nov/2026: download de até ~212 GB com atualização do primeiro dia",
|
||||
"nov/2025: lançamento adiado de 26 de maio de 2026 para 19 de novembro de 2026",
|
||||
"2026: o vídeo 'An Extended Look' mostrou o início de missões da história, roubos e o HUD de procurado/Heat",
|
||||
"mai/2025: o Trailer 2 apresentou Jason, Lucia e o elenco de apoio"
|
||||
],
|
||||
"hashtags": ["#GTA6", "#GTAVI", "#GrandTheftAutoVI", "#ViceCity", "#GTA6Brasil", "#Rockstar"],
|
||||
"sources": [
|
||||
"https://www.rockstargames.com/VI",
|
||||
"https://www.forbes.com/sites/erikkain/2026/11/16/gta-6-release-date-time-ps5-xbox-series-x-download-size-day-one-update/",
|
||||
"https://hothardware.com/news/gta-6-extended-look-reveals-story-missions-and-massive-map-details",
|
||||
"https://lfcarry.com/guides/gta-6-chapter-list-walkthrough",
|
||||
"https://www.gtabase.com/articles/gta-6/gta-6-previews-recap-all-new-gameplay-features-revealed",
|
||||
"https://allthings.how/gta-6-wanted-system-explained-how-heat-builds-and-how-you-lose-it/",
|
||||
"https://www.redbull.com/int-en/gta-6-gameplay-details",
|
||||
"https://www.gfinityesports.com/article/gta-6-map-guide-every-confirmed-location-in-leonida"
|
||||
],
|
||||
"missions": [
|
||||
{
|
||||
"name": "Boobie Ike stash pickup (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Uma coleta de droga para o Boobie Ike que vira uma batida policial.",
|
||||
"completion_triggers": ["Fugir da batida e perder as estrelas", "Entregar a carga no ponto do Boobie ou a cutscene de fim", "Banner de missão concluída ou tela de resultado"]
|
||||
},
|
||||
{
|
||||
"name": "Raul Bautista getaway (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Uma fuga para o assaltante profissional Raul Bautista.",
|
||||
"completion_triggers": ["Chegar ao ponto de entrega com a polícia despistada", "Dinheiro ou divisão aparecendo na tela", "Banner de missão concluída ou tela de resultado"]
|
||||
},
|
||||
{
|
||||
"name": "Skyscraper security job (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Um trabalho de segurança que vira uma situação com reféns num arranha-céu.",
|
||||
"completion_triggers": ["Impasse com reféns resolvido (fim do tiroteio ou acordo)", "Saída do prédio ou cutscene de fuga", "Banner de missão concluída ou tela de resultado"]
|
||||
},
|
||||
{
|
||||
"name": "Rooftop party with a wealthy employer (nome descritivo, não oficial)",
|
||||
"chapter": "Mostrada em 'An Extended Look' (antes do lançamento)",
|
||||
"summary": "Jason e Lucia conhecem um patrão muito rico e suspeito numa festa na cobertura.",
|
||||
"completion_triggers": ["A conversa ou cutscene com o patrão termina", "Um contato novo aparece no celular", "Banner de missão concluída"]
|
||||
}
|
||||
],
|
||||
"end_triggers": [
|
||||
"Banner de missão concluída ou tela de resultado com tempo, precisão ou pagamento",
|
||||
"Dinheiro do roubo ou a divisão sendo contados na tela",
|
||||
"As estrelas de procurado somem (polícia despistada) logo depois da fuga",
|
||||
"Chegada ao marcador de entrega, esconderijo ou casa e o carro para",
|
||||
"Começa a cutscene final (a câmera sai do gameplay, faixas pretas)",
|
||||
"Falha: tela WASTED ou BUSTED, ou 'missão falhou' com opção de tentar de novo",
|
||||
"Ligação ou mensagem do contato encerrando o trabalho",
|
||||
"Streamer fala 'passou', 'consegui', 'acabou a missão' ou comemora; chat enche de GG/W"
|
||||
]
|
||||
}
|
||||
}
|
||||
+48
-9
@@ -67,11 +67,12 @@ class VoiceClient:
|
||||
except httpx.HTTPError:
|
||||
return False
|
||||
|
||||
def transcribe(self, wav: bytes, idempotency_key: str) -> list[Word]:
|
||||
def transcribe(self, wav: bytes, idempotency_key: str, language: str | None = None) -> list[Word]:
|
||||
"""`language` = idioma da sessão (fonte gringa); vazio/None = o padrão do serviço (CLIPPER_LANGUAGE)."""
|
||||
if not self.configured:
|
||||
raise RuntimeError("serviço de voz não instalado")
|
||||
headers = {
|
||||
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": self.language,
|
||||
"X-Service-Key": self.key or "", "Content-Type": "audio/wav", "X-Language": language or self.language,
|
||||
"X-Detail": "words", "X-Idempotency-Key": idempotency_key,
|
||||
}
|
||||
response = httpx.post(f"{self.url}/v1/transcribe", content=wav, headers=headers, timeout=180)
|
||||
@@ -462,6 +463,9 @@ class Engine:
|
||||
self.db.run("UPDATE sessions SET status = 'starting', ended_at = NULL, error = NULL WHERE id = ?", session_id)
|
||||
capture = Capture(self, session_id, source, REPO_ROOT / session["dir"], start_idx=(last + 1) if last is not None else 0)
|
||||
self.captures[session_id] = capture
|
||||
if session["channel_id"] and not only_if_status:
|
||||
# Você retomou pelo painel: a fonte volta a ser monitorada (a retomada automática não mexe na pausa).
|
||||
self.clear_monitor_pause(session["channel_id"])
|
||||
capture.start()
|
||||
return True
|
||||
|
||||
@@ -513,7 +517,9 @@ class Engine:
|
||||
return self.judge_config()
|
||||
|
||||
# ---------- sessões
|
||||
def start_session(self, url: str, channel_id: str | None = None) -> int:
|
||||
def start_session(self, url: str, channel_id: str | None = None, language: str | None = None) -> int:
|
||||
"""Começa a gravar (live) ou baixar (VOD). `language` = idioma falado; vazio herda o da fonte ('' = padrão).
|
||||
Gravar à mão uma fonte com o monitor pausado religa o monitor (você ligou de propósito)."""
|
||||
source = parse_source(url)
|
||||
if not self.settings.streamlink or not self.settings.ffmpeg:
|
||||
raise RuntimeError("Streamlink ou FFmpeg não encontrados: rode o setup.bat.")
|
||||
@@ -521,10 +527,14 @@ class Engine:
|
||||
active = self.db.get("SELECT id FROM sessions WHERE url = ? AND status IN ('starting', 'recording')", source.url)
|
||||
if active:
|
||||
return active["id"]
|
||||
channel = self.db.get("SELECT language FROM channels WHERE id = ?", channel_id) if channel_id else None
|
||||
cur = self.db.run(
|
||||
"INSERT INTO sessions (channel_id, platform, kind, url, status, dir, started_at) VALUES (?, ?, ?, ?, 'starting', '', ?)",
|
||||
channel_id, source.platform, source.kind, source.url, now())
|
||||
"INSERT INTO sessions (channel_id, platform, kind, url, status, dir, started_at, language)"
|
||||
" VALUES (?, ?, ?, ?, 'starting', '', ?, ?)",
|
||||
channel_id, source.platform, source.kind, source.url, now(), (language or (channel or {}).get("language") or "").strip())
|
||||
session_id = int(cur.lastrowid)
|
||||
if channel_id:
|
||||
self.clear_monitor_pause(channel_id)
|
||||
workdir = self.settings.data_dir / "sessions" / str(session_id)
|
||||
self.db.run("UPDATE sessions SET dir = ? WHERE id = ?", rel(workdir), session_id)
|
||||
capture = Capture(self, session_id, source, workdir)
|
||||
@@ -548,12 +558,28 @@ class Engine:
|
||||
if session:
|
||||
self.intel.check_game(session, force=True)
|
||||
|
||||
def stop_session(self, session_id: int) -> None:
|
||||
def stop_session(self, session_id: int, *, pause_monitor: bool = True) -> None:
|
||||
"""Para a gravação. `pause_monitor` (padrão): a fonte monitorada fica com o monitor PAUSADO — senão, 60 s depois
|
||||
o monitor abriria uma sessão nova, porque a live continua no ar (reclamação do dono, 18/11/2026). A queda de
|
||||
live (captura cai sozinha) não passa por aqui e continua retomando na mesma sessão (`keep_live`)."""
|
||||
with self.lock:
|
||||
capture = self.captures.get(session_id)
|
||||
if capture:
|
||||
self.db.run("UPDATE sessions SET status = 'stopped' WHERE id = ? AND status IN ('starting', 'recording')", session_id)
|
||||
capture.stop()
|
||||
if pause_monitor:
|
||||
session = self.db.get("SELECT channel_id FROM sessions WHERE id = ?", session_id)
|
||||
if session and session["channel_id"]:
|
||||
changed = self.db.run("UPDATE channels SET monitor_paused_at = ?, monitor_paused_session = ? WHERE id = ? AND monitor = 1",
|
||||
now(), session_id, session["channel_id"]).rowcount
|
||||
if changed:
|
||||
log.info("fonte %s: monitor pausado (você parou a sessão %s)", session["channel_id"], session_id)
|
||||
|
||||
def clear_monitor_pause(self, channel_id: str) -> None:
|
||||
"""Religa o monitor da fonte (PATCH monitor=true, gravar pelo link ou retomar uma sessão dela)."""
|
||||
if self.db.run("UPDATE channels SET monitor_paused_at = NULL, monitor_paused_session = NULL WHERE id = ? AND monitor_paused_at IS NOT NULL",
|
||||
channel_id).rowcount:
|
||||
log.info("fonte %s: monitor religado", channel_id)
|
||||
|
||||
def capture_finished(self, session_id: int) -> None:
|
||||
with self.lock:
|
||||
@@ -571,9 +597,19 @@ class Engine:
|
||||
# ---------- monitor de canais
|
||||
def _monitor_loop(self) -> None:
|
||||
while not self.stop_event.is_set():
|
||||
self.monitor_once()
|
||||
self.stop_event.wait(self.settings.poll_s)
|
||||
|
||||
def monitor_once(self) -> list[int]:
|
||||
"""Uma passada do monitor: checa cada fonte monitorada (e não pausada) sem sessão ativa e grava as que estão
|
||||
ao vivo. Devolve os ids das sessões iniciadas (os testes chamam direto)."""
|
||||
started: list[int] = []
|
||||
for channel in self.db.all("SELECT * FROM channels WHERE monitor = 1"):
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
if channel.get("monitor_paused_at"):
|
||||
log.debug("fonte %s: monitor pausado (sessão %s parada à mão), pulando", channel["id"], channel.get("monitor_paused_session"))
|
||||
continue
|
||||
busy = self.db.get("SELECT id FROM sessions WHERE channel_id = ? AND status IN ('starting', 'recording')", channel["id"])
|
||||
if busy:
|
||||
continue
|
||||
@@ -585,9 +621,10 @@ class Engine:
|
||||
try:
|
||||
session_id = self.start_session(channel["url"], channel["id"])
|
||||
self.db.run("UPDATE sessions SET title = ? WHERE id = ?", title[:200], session_id)
|
||||
started.append(session_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("canal %s: não iniciou (%s)", channel["id"], exc)
|
||||
self.stop_event.wait(self.settings.poll_s)
|
||||
return started
|
||||
|
||||
def live_check(self, url: str) -> LiveCheck:
|
||||
"""Streamlink --json, separando "offline" de "não deu para checar". Falha de checagem vai para o log com o
|
||||
@@ -701,7 +738,9 @@ class Engine:
|
||||
pcm = media.decode_pcm(self.settings.ffmpeg or "ffmpeg", [file])
|
||||
loudness = media.loudness_per_second(pcm)
|
||||
try:
|
||||
rel_words = self.voice.transcribe(media.to_wav(pcm), f"clipper-{segment['session_id']}-{segment['idx']}")
|
||||
owner = self.db.get("SELECT language FROM sessions WHERE id = ?", segment["session_id"])
|
||||
rel_words = self.voice.transcribe(media.to_wav(pcm), f"clipper-{segment['session_id']}-{segment['idx']}",
|
||||
language=(owner or {}).get("language") or None)
|
||||
words = [Word(round(w.start + segment["start_s"], 3), round(w.end + segment["start_s"], 3), w.word)
|
||||
for w in rel_words]
|
||||
except Exception as exc: # noqa: BLE001 - sem voz o corte segue pelo chat
|
||||
@@ -1051,7 +1090,7 @@ class Engine:
|
||||
self.db.run("UPDATE segments SET deleted = 1 WHERE session_id = ? AND idx = ?", seg["session_id"], seg["idx"])
|
||||
|
||||
def delete_session(self, session_id: int) -> None:
|
||||
self.stop_session(session_id)
|
||||
self.stop_session(session_id, pause_monitor=False)
|
||||
session = self.db.get("SELECT * FROM sessions WHERE id = ?", session_id)
|
||||
if not session:
|
||||
return
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Configuração comum dos testes do Clipador."""
|
||||
import pytest
|
||||
|
||||
import app.ai_settings as ai_settings_module
|
||||
import app.intel as intel_module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolated_ai_settings(tmp_path_factory, monkeypatch):
|
||||
# Configurações → IA do painel (data/ai real) não entram nos testes: cada teste começa com o padrão do doc.
|
||||
monkeypatch.setattr(ai_settings_module, "DEFAULT_AI_DIR", tmp_path_factory.mktemp("ai-settings"))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_real_game_seeds(tmp_path_factory, monkeypatch):
|
||||
# As sementes de jogo do repositório (app/seeds/games, ex.: GTA VI) entrariam em todo banco de teste e mudariam
|
||||
# a lista de jogos. Cada teste começa sem nenhuma; quem testa sementes passa a própria pasta.
|
||||
monkeypatch.setattr(intel_module, "SEEDS_DIR", tmp_path_factory.mktemp("no-seeds"))
|
||||
@@ -0,0 +1,313 @@
|
||||
"""Gemini no juiz, IA reserva e modo chave de API (contrato em doc/ia.md). Nenhuma CLI de verdade roda aqui:
|
||||
`subprocess.run` e os `find_*` do juiz são trocados por falsos."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from app import judge as judge_module
|
||||
from app.ai_settings import DEFAULT_SETTINGS, AiConfig, normalize_settings
|
||||
from app.judge import (DEFAULT_MODELS, VERDICT_SCHEMA, Judge, JudgeError, extract_json_object, is_availability_error,
|
||||
parse_gemini_output)
|
||||
from tests.test_sources_and_api import KEY, auth, env # noqa: F401 - fixture reaproveitada
|
||||
|
||||
VERDICT = {"keep": True, "score": 8, "start_s": 100, "end_s": 170, "title": "Virada", "caption": "c",
|
||||
"hashtags": ["lag"], "reason": "r"}
|
||||
|
||||
|
||||
class ReversedCipher:
|
||||
"""Cifrador falso: o "blob" é o JSON de trás para frente (garante que o cofre passa pelo cifrador)."""
|
||||
|
||||
def unprotect(self, data: bytes) -> bytes:
|
||||
return data[::-1]
|
||||
|
||||
|
||||
_STAMPS = iter(range(1_700_000_000, 1_800_000_000, 7))
|
||||
|
||||
|
||||
def write_settings(folder: Path, data: dict) -> None:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
path = folder / "settings.json"
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
# mtime sempre diferente do anterior (o sistema de arquivos pode ter resolução grossa)
|
||||
stamp = next(_STAMPS) * 1_000_000_000
|
||||
os.utime(path, ns=(stamp, stamp))
|
||||
|
||||
|
||||
def write_vault(folder: Path, keys: dict) -> None:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
(folder / "vault.bin").write_bytes(json.dumps(keys).encode("utf-8")[::-1])
|
||||
|
||||
|
||||
def settings_with(**providers) -> dict:
|
||||
data = json.loads(json.dumps(DEFAULT_SETTINGS))
|
||||
for name, conf in providers.items():
|
||||
data["providers"][name].update(conf)
|
||||
return data
|
||||
|
||||
|
||||
class FakeCli:
|
||||
"""Faz o papel das três CLIs. `behavior[provider]` = "ok", "content" (resposta sem JSON) ou um texto de erro
|
||||
(sai com código 1 e esse texto no stderr)."""
|
||||
|
||||
def __init__(self, behavior: dict[str, str]):
|
||||
self.behavior = behavior
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def run(self, args, input=None, capture_output=True, timeout=None, cwd=None, creationflags=0, env=None):
|
||||
provider = args[0]
|
||||
self.calls.append({"provider": provider, "args": list(args), "env": dict(env or {}), "cwd": cwd,
|
||||
"stdin": (input or b"").decode("utf-8"),
|
||||
"files": sorted(p.name for p in Path(cwd).iterdir()) if cwd else []})
|
||||
mode = self.behavior.get(provider, "ok")
|
||||
if mode not in ("ok", "content"):
|
||||
return subprocess.CompletedProcess(args, 1, b"", mode.encode("utf-8"))
|
||||
answer = VERDICT if mode == "ok" else None
|
||||
if provider == "codex":
|
||||
out = Path(args[args.index("-o") + 1])
|
||||
out.write_text(json.dumps(answer) if answer else "não sei", encoding="utf-8")
|
||||
return subprocess.CompletedProcess(args, 0, b"", b"")
|
||||
if provider == "claude":
|
||||
envelope = {"is_error": False, "structured_output": answer, "result": "" if answer else "não sei"}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(envelope).encode(), b"")
|
||||
text = f"Aqui está:\n```json\n{json.dumps(answer)}\n```" if answer else "Não consegui."
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps({"response": text, "stats": {}}).encode(), b"")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ai_dir(tmp_path):
|
||||
return tmp_path / "ai"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_judge(tmp_path, ai_dir, monkeypatch):
|
||||
clock = {"t": 1_000_000.0}
|
||||
|
||||
def factory(behavior=None, provider="codex", model="", installed=("codex", "claude", "gemini")):
|
||||
cli = FakeCli(behavior or {})
|
||||
monkeypatch.setattr(judge_module.subprocess, "run", cli.run)
|
||||
for name in ("codex", "claude", "gemini"):
|
||||
monkeypatch.setattr(judge_module, f"find_{name}", (lambda n=name: [n] if n in installed else None))
|
||||
ai = AiConfig(ai_dir, cipher=ReversedCipher(), environ={"PATH": "x", "ANTHROPIC_API_KEY": "global",
|
||||
"GOOGLE_GENAI_USE_GCA": "true"})
|
||||
judge = Judge(provider, model, tmp_path / "judge", ai=ai, clock=lambda: clock["t"])
|
||||
judge.cli, judge.clock = cli, clock
|
||||
return judge
|
||||
|
||||
return factory
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- classificador
|
||||
@pytest.mark.parametrize("text", [
|
||||
"Error: 429 Too Many Requests", "You've hit your usage limit", "Your credit balance is too low",
|
||||
"API Error: 529 overloaded_error", "503 Service Unavailable", "Not logged in · Please run /login",
|
||||
"invalid api key", "IneligibleTierError: UNSUPPORTED_CLIENT", "connect ECONNREFUSED 127.0.0.1",
|
||||
"getaddrinfo ENOTFOUND api.openai.com", "network error", "a CLI passou de 240 s (tempo esgotado)",
|
||||
"Codex CLI não encontrado", "RESOURCE_EXHAUSTED: quota exceeded", "401 Unauthorized", "status 403",
|
||||
])
|
||||
def test_availability_errors(text):
|
||||
assert is_availability_error(text)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "o Codex não devolveu o JSON pedido", "resposta sem os campos ['title']",
|
||||
"Expecting value: line 1 column 1", "schema validation failed"])
|
||||
def test_content_errors_are_not_availability(text):
|
||||
assert not is_availability_error(text)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- settings.json e cofre
|
||||
def test_settings_default_when_missing_or_invalid(ai_dir):
|
||||
config = AiConfig(ai_dir, cipher=ReversedCipher())
|
||||
assert config.settings() == DEFAULT_SETTINGS
|
||||
ai_dir.mkdir(parents=True)
|
||||
(ai_dir / "settings.json").write_text("{quebrado", encoding="utf-8")
|
||||
assert AiConfig(ai_dir).settings() == DEFAULT_SETTINGS
|
||||
assert DEFAULT_SETTINGS["providers"]["gemini"] == {"enabled": False, "authMode": "apiKey"}
|
||||
|
||||
|
||||
def test_settings_normalized_field_by_field():
|
||||
data = normalize_settings({"providers": {"gemini": {"enabled": True, "authMode": "senha"}, "gpt": {}},
|
||||
"order": ["gemini", "gpt", "gemini"], "fallback": {"enabled": False, "cooldownMin": -3}})
|
||||
assert data["providers"]["gemini"] == {"enabled": True, "authMode": "apiKey"} # modo inválido fica no padrão
|
||||
assert data["order"] == ["gemini", "claude", "codex"] # desconhecido sai, faltantes vão para o fim
|
||||
assert data["fallback"] == {"enabled": False, "cooldownMin": 15.0}
|
||||
|
||||
|
||||
def test_settings_reread_when_mtime_changes(ai_dir):
|
||||
config = AiConfig(ai_dir)
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True}))
|
||||
assert config.settings()["providers"]["gemini"]["enabled"] is True
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": False}, claude={"authMode": "apiKey"}))
|
||||
assert config.settings()["providers"]["gemini"]["enabled"] is False
|
||||
assert config.settings()["providers"]["claude"]["authMode"] == "apiKey"
|
||||
|
||||
|
||||
def test_env_per_auth_mode(ai_dir):
|
||||
environ = {"PATH": "x", "ANTHROPIC_API_KEY": "global", "CODEX_API_KEY": "global", "GEMINI_API_KEY": "global",
|
||||
"GOOGLE_GENAI_USE_GCA": "true"}
|
||||
config = AiConfig(ai_dir, cipher=ReversedCipher(), environ=environ)
|
||||
write_vault(ai_dir, {"claude": "sk-ant-1", "gemini": "AIza-2", "outro": "x"})
|
||||
# padrão: claude/codex em oauth (a variável sai), gemini em apiKey (a chave do cofre entra, GCA sai)
|
||||
claude, codex, gemini = (config.provider_env(p) for p in ("claude", "codex", "gemini"))
|
||||
assert "ANTHROPIC_API_KEY" not in claude and claude["PATH"] == "x"
|
||||
assert "CODEX_API_KEY" not in codex
|
||||
assert gemini["GEMINI_API_KEY"] == "AIza-2" and "GOOGLE_GENAI_USE_GCA" not in gemini
|
||||
write_settings(ai_dir, settings_with(claude={"authMode": "apiKey"}, gemini={"authMode": "oauth"}))
|
||||
assert config.provider_env("claude")["ANTHROPIC_API_KEY"] == "sk-ant-1"
|
||||
gemini = config.provider_env("gemini")
|
||||
assert gemini["GOOGLE_GENAI_USE_GCA"] == "true" and "GEMINI_API_KEY" not in gemini
|
||||
assert environ["ANTHROPIC_API_KEY"] == "global" # o ambiente do processo não muda
|
||||
assert config.api_keys() == {"claude": "sk-ant-1", "gemini": "AIza-2"}
|
||||
|
||||
|
||||
def test_unreadable_vault_means_no_keys(ai_dir):
|
||||
ai_dir.mkdir(parents=True)
|
||||
(ai_dir / "vault.bin").write_bytes(b"\x00lixo")
|
||||
config = AiConfig(ai_dir, cipher=ReversedCipher())
|
||||
assert config.api_keys() == {} and config.vault_error
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- cadeia de reserva
|
||||
def test_chain_skips_disabled_missing_cli_no_key_and_paused(make_judge, ai_dir):
|
||||
judge = make_judge(provider="codex")
|
||||
# padrão: gemini desligado → codex (escolhido) e depois claude
|
||||
assert judge.fallback_chain() == ["codex", "claude"]
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True})) # ligado, mas sem chave no cofre
|
||||
assert judge.fallback_chain() == ["codex", "claude"]
|
||||
write_vault(ai_dir, {"gemini": "AIza"})
|
||||
assert judge.fallback_chain() == ["codex", "claude", "gemini"]
|
||||
judge.pause("claude", "429")
|
||||
assert judge.fallback_chain() == ["codex", "gemini"]
|
||||
judge.clock["t"] += 15 * 60 + 1 # a pausa vence
|
||||
assert judge.fallback_chain() == ["codex", "claude", "gemini"]
|
||||
write_settings(ai_dir, {**settings_with(gemini={"enabled": True}), "order": ["gemini", "codex", "claude"]})
|
||||
assert judge.fallback_chain() == ["codex", "gemini", "claude"]
|
||||
write_settings(ai_dir, {**settings_with(), "fallback": {"enabled": False, "cooldownMin": 15}})
|
||||
assert judge.fallback_chain() == ["codex"]
|
||||
write_settings(ai_dir, settings_with())
|
||||
assert make_judge(provider="codex", installed=("claude",)).fallback_chain() == ["claude"] # codex sem CLI
|
||||
|
||||
|
||||
def test_unavailable_switches_to_next_with_its_default_model_and_pauses(make_judge):
|
||||
judge = make_judge({"codex": "Error: 429 Too Many Requests"}, provider="codex", model="gpt-caro")
|
||||
verdict = judge.judge("prompt", 100, 170, lo=0, hi=300)
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["codex", "claude"]
|
||||
assert verdict.model == f"claude:{DEFAULT_MODELS['claude']}" # quem de fato respondeu, com o modelo padrão dele
|
||||
claude_args = judge.cli.calls[1]["args"]
|
||||
assert claude_args[claude_args.index("--model") + 1] == "haiku"
|
||||
pauses = judge.describe()["pauses"]
|
||||
assert [p["provider"] for p in pauses] == ["codex"] and "429" in pauses[0]["reason"]
|
||||
# próxima chamada já pula o codex em pausa
|
||||
judge.cli.calls.clear()
|
||||
judge.judge("prompt", 100, 170, lo=0, hi=300)
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["claude"]
|
||||
|
||||
|
||||
def test_content_error_does_not_switch(make_judge):
|
||||
judge = make_judge({"codex": "content"}, provider="codex")
|
||||
with pytest.raises(JudgeError) as info:
|
||||
judge.judge("prompt", 100, 170)
|
||||
assert info.value.unavailable is False
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["codex"] and judge.pauses() == {}
|
||||
|
||||
|
||||
def test_all_fail_raises_summary(make_judge):
|
||||
judge = make_judge({"codex": "503 unavailable", "claude": "Not logged in"}, provider="codex")
|
||||
with pytest.raises(JudgeError) as info:
|
||||
judge.judge("prompt", 100, 170)
|
||||
message = str(info.value)
|
||||
assert "codex:" in message and "claude:haiku" in message and info.value.unavailable is True
|
||||
assert set(judge.pauses()) == {"codex", "claude"}
|
||||
|
||||
|
||||
def test_fallback_disabled_keeps_only_primary(make_judge, ai_dir):
|
||||
write_settings(ai_dir, {**settings_with(), "fallback": {"enabled": False, "cooldownMin": 15}})
|
||||
judge = make_judge({"codex": "429"}, provider="codex")
|
||||
with pytest.raises(JudgeError):
|
||||
judge.judge("prompt", 100, 170)
|
||||
assert [c["provider"] for c in judge.cli.calls] == ["codex"] and judge.pauses() == {}
|
||||
|
||||
|
||||
def test_primary_disabled_in_settings_is_skipped(make_judge, ai_dir):
|
||||
write_settings(ai_dir, settings_with(codex={"enabled": False}))
|
||||
judge = make_judge(provider="codex")
|
||||
assert judge.judge("prompt", 100, 170).model == "claude:haiku"
|
||||
assert judge.describe()["unavailableReason"] == "desligada em Configurações → IA"
|
||||
|
||||
|
||||
def test_describe_format(make_judge, ai_dir):
|
||||
judge = make_judge(provider="gemini", model="")
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True}))
|
||||
write_vault(ai_dir, {"gemini": "AIza"})
|
||||
judge.pause("codex", "usage limit")
|
||||
data = judge.describe()
|
||||
assert data["provider"] == "gemini" and data["model"] == "gemini-3.5-flash" and data["authMode"] == "apiKey"
|
||||
assert data["fallback"] == {"enabled": True, "cooldownMin": 15.0, "chain": ["gemini", "claude"]}
|
||||
assert data["pauses"][0]["provider"] == "codex" and data["pauses"][0]["until"].endswith("+00:00")
|
||||
assert "gemini" in judge.models() and judge.models()["defaults"]["gemini"] == "gemini-3.5-flash"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- Gemini
|
||||
def test_gemini_call_args_images_and_env(make_judge, ai_dir, tmp_path):
|
||||
write_settings(ai_dir, settings_with(gemini={"enabled": True}))
|
||||
write_vault(ai_dir, {"gemini": "AIza-chave"})
|
||||
frames = []
|
||||
for i in range(2):
|
||||
frame = tmp_path / "frames" / f"clip1-{i}.JPG"
|
||||
frame.parent.mkdir(exist_ok=True)
|
||||
frame.write_bytes(b"jpg")
|
||||
frames.append(frame)
|
||||
judge = make_judge(provider="gemini", model="gemini-2.5-pro")
|
||||
verdict = judge.judge("PROMPT GRANDE", 100, 170, frames)
|
||||
call = judge.cli.calls[0]
|
||||
args = call["args"]
|
||||
assert args[:2] == ["gemini", "-p"] and "@frame-01.jpg @frame-02.jpg" in args[2]
|
||||
assert args[args.index("-o") + 1] == "json" and args[args.index("--approval-mode") + 1] == "plan"
|
||||
assert "--skip-trust" in args and args[args.index("-m") + 1] == "gemini-2.5-pro"
|
||||
assert "PROMPT GRANDE" in call["stdin"] and '"start_s"' in call["stdin"] and "PROMPT GRANDE" not in args[2]
|
||||
assert call["files"] == ["frame-01.jpg", "frame-02.jpg"] # imagens copiadas para a pasta de trabalho
|
||||
assert call["env"]["GEMINI_API_KEY"] == "AIza-chave" and "GOOGLE_GENAI_USE_GCA" not in call["env"]
|
||||
assert verdict.model == "gemini:gemini-2.5-pro" and verdict.title == "Virada"
|
||||
|
||||
|
||||
def test_extract_json_object_tolerates_fences_and_prose():
|
||||
assert extract_json_object('```json\n{"a": 1}\n```') == {"a": 1}
|
||||
assert extract_json_object('Claro! {"a": {"b": [1, 2]}} espero ter ajudado') == {"a": {"b": [1, 2]}}
|
||||
assert extract_json_object("o conjunto {x} e depois {\"ok\": true}") == {"ok": True}
|
||||
assert extract_json_object("sem json") is None and extract_json_object("") is None
|
||||
|
||||
|
||||
def test_parse_gemini_output():
|
||||
assert parse_gemini_output(json.dumps({"response": '```json\n{"keep": true}\n```', "stats": {}})) == {"keep": True}
|
||||
with pytest.raises(JudgeError) as info:
|
||||
parse_gemini_output(json.dumps({"response": "não deu"}))
|
||||
assert info.value.unavailable is False
|
||||
with pytest.raises(JudgeError) as info:
|
||||
parse_gemini_output(json.dumps({"error": {"type": "Error", "message": "429 RESOURCE_EXHAUSTED quota"}}))
|
||||
assert info.value.unavailable is None and is_availability_error(str(info.value))
|
||||
assert set(VERDICT) == set(VERDICT_SCHEMA["required"])
|
||||
|
||||
|
||||
def test_find_gemini_runs_bundle_with_node_on_windows(tmp_path, monkeypatch):
|
||||
npm = tmp_path / "npm"
|
||||
bundle = npm / "node_modules" / "@google" / "gemini-cli" / "bundle" / "gemini.js"
|
||||
bundle.parent.mkdir(parents=True)
|
||||
bundle.write_text("//", encoding="utf-8")
|
||||
monkeypatch.delenv("GEMINI_BIN", raising=False)
|
||||
monkeypatch.setattr(judge_module.sys, "platform", "win32")
|
||||
which = {"gemini.cmd": str(npm / "gemini.cmd"), "node": "C:/node/node.exe"}
|
||||
monkeypatch.setattr(judge_module.shutil, "which", lambda name: which.get(name))
|
||||
assert judge_module.find_gemini() == ["C:/node/node.exe", str(bundle)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- API
|
||||
def test_api_accepts_gemini(env): # noqa: F811
|
||||
client, engine = env
|
||||
r = client.put("/v1/judge", json={"provider": "gemini", "model": "", "minScore": 6}, headers=auth())
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["provider"] == "gemini" and body["model"] == "gemini-3.5-flash" and "gemini" in body["models"]
|
||||
assert "chain" in body["fallback"] and isinstance(body["pauses"], list)
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Perfis de jogo bilíngues (doc/clipador/JOGOS.md): inglês para a IA, português para ler, missões, gatilhos de fim,
|
||||
outros nomes, cadastro pelo painel e sementes."""
|
||||
import json
|
||||
|
||||
from app.intel import clean_profile
|
||||
from app.judge import JudgeError
|
||||
from tests.test_sources_and_api import FakeJudge, auth, env, seed_session # noqa: F401 - fixture reaproveitada
|
||||
|
||||
EN = {
|
||||
"name": "Grand Theft Auto VI", "aliases": ["GTA 6", "GTA VI"], "summary": "Open-world crime game in Leonida.",
|
||||
"genre": "Action", "mechanics": ["heists"], "clip_worthy": ["police chase ends in a crash"], "avoid": ["menus"],
|
||||
"jargon": ["wanted level"], "news": ["Released Nov 2026"], "hashtags": ["#GTA6"], "sources": ["https://example.com"],
|
||||
"missions": [{"name": "Hometown", "chapter": "Prologue", "summary": "Lucia and Jason meet.",
|
||||
"completion_triggers": ["MISSION PASSED banner"]}],
|
||||
"end_triggers": ["MISSION PASSED", "WASTED"],
|
||||
}
|
||||
|
||||
|
||||
def to_pt(profile: dict) -> dict:
|
||||
"""Tradução falsa: marca os textos traduzíveis com [pt] e mantém o resto, como o TRANSLATE_SYSTEM pede."""
|
||||
out = json.loads(json.dumps(profile))
|
||||
out["summary"] = "[pt] " + out["summary"]
|
||||
out["clip_worthy"] = ["[pt] " + x for x in out["clip_worthy"]]
|
||||
for m in out["missions"]:
|
||||
m["summary"] = "[pt] " + m["summary"]
|
||||
return out
|
||||
|
||||
|
||||
class BilingualJudge(FakeJudge):
|
||||
def __init__(self, fail_translate=False):
|
||||
super().__init__()
|
||||
self.fail_translate = fail_translate
|
||||
self.translations: list[str] = []
|
||||
|
||||
def research_game(self, name, live_title="", notes=None):
|
||||
return {**EN, "name": name}
|
||||
|
||||
def translate_game(self, profile, target):
|
||||
self.translations.append(target)
|
||||
if self.fail_translate:
|
||||
raise JudgeError("cota acabou")
|
||||
if target == "pt-BR":
|
||||
return to_pt(profile)
|
||||
back = json.loads(json.dumps(profile))
|
||||
back["summary"] = "[en] " + back["summary"]
|
||||
return back
|
||||
|
||||
def refine_game(self, name, profile, instruction, search=True, section="", history=None):
|
||||
return {**profile, "end_triggers": [*profile["end_triggers"], "Reward screen"], "reply": "Acrescentei a tela de recompensa."}
|
||||
|
||||
|
||||
def add(engine, name="Grand Theft Auto VI"):
|
||||
engine.db.run("INSERT INTO games (id, name, status) VALUES (?, ?, 'pending')",
|
||||
name.lower().replace(" ", "-"), name)
|
||||
return name.lower().replace(" ", "-")
|
||||
|
||||
|
||||
def test_research_stores_english_for_ai_and_portuguese_for_reading(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
game = client.get("/v1/games", headers=auth()).json()["games"][0]
|
||||
assert game["status"] == "ready" and game["aiLanguage"] == "en-US" and game["translatedAt"]
|
||||
assert game["profileAi"]["summary"] == EN["summary"]
|
||||
assert game["profile"]["summary"].startswith("[pt] ")
|
||||
# Nome oficial da missão e hashtags não mudam na tradução.
|
||||
assert game["profile"]["missions"][0]["name"] == "Hometown" and game["profile"]["hashtags"] == ["#GTA6"]
|
||||
assert game["aliases"] == ["gta-6", "gta-vi"]
|
||||
# A IA lê o inglês.
|
||||
assert engine.intel.profile("Grand Theft Auto VI")["summary"] == EN["summary"]
|
||||
|
||||
|
||||
def test_failed_translation_keeps_english_in_both_and_explains(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge(fail_translate=True)
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
game = client.get("/v1/games", headers=auth()).json()["games"][0]
|
||||
assert game["status"] == "ready" and "tradução falhou" in game["error"]
|
||||
assert game["profile"]["summary"] == EN["summary"] and game["translatedAt"] is None
|
||||
|
||||
|
||||
def test_manual_save_in_portuguese_translates_to_english(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
pt = to_pt(EN)
|
||||
pt["summary"] = "Jogo de crime em Leonida, editado por mim."
|
||||
r = client.put(f"/v1/games/{gid}", json=pt, headers=auth())
|
||||
assert r.status_code == 200
|
||||
game = r.json()["games"][0]
|
||||
assert game["profile"]["summary"] == "Jogo de crime em Leonida, editado por mim."
|
||||
assert game["profileAi"]["summary"] == "[en] Jogo de crime em Leonida, editado por mim." and game["editedAt"]
|
||||
assert engine.judge.translations[-1] == "en-US"
|
||||
# Editar a versão da IA direto (lang=en) traduz para português.
|
||||
r = client.put(f"/v1/games/{gid}?lang=en", json=EN, headers=auth())
|
||||
assert r.json()["games"][0]["profileAi"]["summary"] == EN["summary"]
|
||||
assert engine.judge.translations[-1] == "pt-BR"
|
||||
|
||||
|
||||
def test_refine_applies_on_english_and_replies_in_portuguese(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
gid = add(engine)
|
||||
engine.intel.research(gid)
|
||||
r = client.post(f"/v1/games/{gid}/refine", json={"instruction": "acrescente a tela de recompensa", "section": "end_triggers"},
|
||||
headers=auth())
|
||||
assert r.status_code == 200 and r.json()["reply"] == "Acrescentei a tela de recompensa."
|
||||
game = r.json()["games"][0]
|
||||
assert "Reward screen" in game["profileAi"]["end_triggers"] and "Reward screen" in game["profile"]["end_triggers"]
|
||||
|
||||
|
||||
def test_context_uses_english_profile_with_missions_and_end_triggers(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.intel.research(add(engine))
|
||||
sid = seed_session(engine)
|
||||
# Categoria por outro nome ("GTA 6") cai no mesmo perfil.
|
||||
engine.db.run("UPDATE sessions SET game = 'GTA 6' WHERE id = ?", sid)
|
||||
context = engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
|
||||
assert EN["summary"] in context and "MISSION PASSED; WASTED" in context
|
||||
assert "Hometown (fim: MISSION PASSED banner)" in context and "termine o corte logo depois do gatilho" in context
|
||||
|
||||
|
||||
def test_mission_list_in_prompt_is_capped():
|
||||
from app.judge import mission_lines
|
||||
profile = clean_profile({"missions": [{"name": f"Mission number {i}", "completion_triggers": ["MISSION PASSED"]}
|
||||
for i in range(110)]})
|
||||
lines = mission_lines(profile)
|
||||
assert len(profile["missions"]) == 110
|
||||
missions = next(line for line in lines if line.startswith("Missões"))
|
||||
assert "…e mais" in missions and len(missions) < 1700
|
||||
|
||||
|
||||
def test_add_game_conflicts_by_alias_and_delete(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.intel.research(add(engine))
|
||||
r = client.post("/v1/games", json={"name": "GTA 6"}, headers=auth())
|
||||
assert r.status_code == 409 and "já está na lista" in r.json()["error"]
|
||||
r = client.post("/v1/games", json={"name": "Hollow Knight: Silksong", "notes": "foco em chefes"}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["id"] == "hollow-knight-silksong"
|
||||
new = next(g for g in r.json()["games"] if g["id"] == "hollow-knight-silksong")
|
||||
assert new["notes"][0]["text"] == "foco em chefes"
|
||||
r = client.delete("/v1/games/hollow-knight-silksong", headers=auth())
|
||||
assert r.status_code == 200 and all(g["id"] != "hollow-knight-silksong" for g in r.json()["games"])
|
||||
assert client.delete("/v1/games/nao-existe", headers=auth()).status_code == 404
|
||||
|
||||
|
||||
def test_translate_route_makes_ai_version_for_old_games(env): # noqa: F811
|
||||
client, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.db.run("INSERT INTO games (id, name, status, profile_json) VALUES ('rob-run', 'ROB RUN', 'ready', ?)",
|
||||
json.dumps(clean_profile({"name": "ROB RUN", "summary": "Jogo de assalto."})))
|
||||
assert client.get("/v1/games", headers=auth()).json()["games"][0]["profileAi"] is None
|
||||
r = client.post("/v1/games/rob-run/translate", headers=auth())
|
||||
assert r.status_code == 200 and r.json()["games"][0]["profileAi"]["summary"] == "[en] Jogo de assalto."
|
||||
|
||||
|
||||
def test_seeds_import_once_and_never_overwrite(env, tmp_path): # noqa: F811
|
||||
_, engine = env
|
||||
folder = tmp_path / "seeds"
|
||||
folder.mkdir()
|
||||
(folder / "game.json").write_text(json.dumps({
|
||||
"name": "Seed Game", "aliases": ["SG"], "researchedAt": "2026-11-18T00:00:00+00:00", "sources": ["https://a"],
|
||||
"profileAi": {"summary": "English summary", "missions": [{"name": "M1"}]},
|
||||
"profile": {"summary": "Resumo em português", "missions": [{"name": "M1"}]},
|
||||
}), encoding="utf-8")
|
||||
assert engine.intel.import_seeds(folder) == ["seed-game"]
|
||||
row = engine.db.get("SELECT * FROM games WHERE id = 'seed-game'")
|
||||
assert row["status"] == "ready" and row["model"] == "seed"
|
||||
assert json.loads(row["profile_ai_json"])["aliases"] == ["SG"] and json.loads(row["profile_json"])["sources"] == ["https://a"]
|
||||
assert engine.intel.profile("SG")["summary"] == "English summary"
|
||||
engine.db.run("UPDATE games SET profile_json = '{\"summary\": \"editado\"}' WHERE id = 'seed-game'")
|
||||
assert engine.intel.import_seeds(folder) == []
|
||||
assert json.loads(engine.db.get("SELECT profile_json FROM games WHERE id = 'seed-game'")["profile_json"])["summary"] == "editado"
|
||||
|
||||
|
||||
def test_category_by_alias_does_not_create_duplicate_game(env): # noqa: F811
|
||||
_, engine = env
|
||||
engine.judge = BilingualJudge()
|
||||
engine.intel.research(add(engine))
|
||||
sid = seed_session(engine)
|
||||
engine.intel.set_game(sid, "GTA VI", "platform")
|
||||
assert [r["id"] for r in engine.db.all("SELECT id FROM games")] == ["grand-theft-auto-vi"]
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Parar à mão pausa o monitor da fonte (reclamação de 18/11/2026: 60 s depois de "Parar" o monitor abria uma sessão
|
||||
nova, porque a live continuava no ar) e idioma por fonte/sessão (transcrição e textos da IA em outro idioma)."""
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
import app.worker as worker_module
|
||||
from app.judge import output_language_note
|
||||
|
||||
from .test_sources_and_api import auth, env # noqa: F401 - fixture reaproveitada
|
||||
|
||||
URL = "https://www.twitch.tv/alanzoka"
|
||||
CHANNEL = "twitch-alanzoka"
|
||||
|
||||
|
||||
class FakeCapture:
|
||||
"""Captura falsa: `stop` avisa o motor como a real faz ao terminar (sai de `captures`, senão não dá para retomar)."""
|
||||
def __init__(self, eng, session_id, source, workdir, start_idx=0):
|
||||
self.eng, self.session_id = eng, session_id
|
||||
self.chat = None
|
||||
|
||||
def start(self):
|
||||
pass
|
||||
|
||||
def stop(self):
|
||||
self.eng.capture_finished(self.session_id)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ready(env, monkeypatch): # noqa: F811
|
||||
"""Serviço com ferramentas "achadas", captura falsa e a live sempre no ar (sem Streamlink de verdade)."""
|
||||
client, engine = env
|
||||
monkeypatch.setattr(engine, "settings", replace(engine.settings, streamlink="streamlink", ffmpeg="ffmpeg"))
|
||||
monkeypatch.setattr(worker_module, "Capture", FakeCapture)
|
||||
monkeypatch.setattr(engine, "_fill_title", lambda *_a, **_k: None)
|
||||
# A pasta de dados do teste fica fora do repositório: o caminho relativo da sessão não importa aqui.
|
||||
monkeypatch.setattr(worker_module, "rel", lambda path: path.as_posix())
|
||||
engine.check_live = lambda url: (True, "live no ar")
|
||||
return client, engine
|
||||
|
||||
|
||||
def channel(client):
|
||||
return next(c for c in client.get("/v1/channels", headers=auth()).json()["channels"] if c["id"] == CHANNEL)
|
||||
|
||||
|
||||
def test_stop_by_hand_pauses_monitor_until_relit(ready):
|
||||
client, engine = ready
|
||||
assert client.post("/v1/channels", json={"url": URL}, headers=auth()).status_code == 201
|
||||
started = engine.monitor_once()
|
||||
assert len(started) == 1
|
||||
sid = started[0]
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
# Parar sem corpo (painel antigo) = pausa o monitor da fonte.
|
||||
assert client.post(f"/v1/sessions/{sid}/stop", headers=auth()).json() == {"ok": True}
|
||||
c = channel(client)
|
||||
assert c["monitor"] is True and c["monitorPausedAt"] and c["monitorPausedBySession"] == sid
|
||||
assert engine.db.get("SELECT status FROM sessions WHERE id = ?", sid)["status"] == "stopped"
|
||||
# A live continua no ar, mas o monitor NÃO abre sessão nova.
|
||||
assert engine.monitor_once() == []
|
||||
assert engine.db.get("SELECT COUNT(*) AS n FROM sessions")["n"] == 1
|
||||
|
||||
# "Religar" = PATCH monitor=true limpa a pausa; a próxima passada grava de novo.
|
||||
r = client.patch(f"/v1/channels/{CHANNEL}", json={"monitor": True}, headers=auth())
|
||||
assert r.json()["monitorPausedAt"] is None and r.json()["monitorPausedBySession"] is None
|
||||
assert len(engine.monitor_once()) == 1
|
||||
|
||||
|
||||
def test_stop_without_pause_keeps_monitor(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL}, headers=auth())
|
||||
sid = engine.monitor_once()[0]
|
||||
client.post(f"/v1/sessions/{sid}/stop", json={"pauseMonitor": False}, headers=auth())
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
assert len(engine.monitor_once()) == 1 # a live segue no ar: grava de novo (você pediu assim)
|
||||
|
||||
|
||||
def test_recording_by_link_or_resuming_relights_monitor(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL}, headers=auth())
|
||||
sid = engine.monitor_once()[0]
|
||||
client.post(f"/v1/sessions/{sid}/stop", headers=auth())
|
||||
assert channel(client)["monitorPausedAt"]
|
||||
|
||||
# Gravar pelo link à mão: você ligou de propósito → a pausa some.
|
||||
r = client.post("/v1/sessions", json={"url": URL}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["id"] != sid
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
# Parar de novo e retomar pelo painel também religa.
|
||||
client.post(f"/v1/sessions/{r.json()['id']}/stop", headers=auth())
|
||||
assert channel(client)["monitorPausedAt"]
|
||||
assert client.post(f"/v1/sessions/{r.json()['id']}/resume", headers=auth()).status_code == 200
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
|
||||
def test_deleting_a_session_does_not_pause(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL}, headers=auth())
|
||||
sid = engine.monitor_once()[0]
|
||||
assert client.delete(f"/v1/sessions/{sid}", headers=auth()).status_code == 204
|
||||
assert channel(client)["monitorPausedAt"] is None
|
||||
|
||||
|
||||
def test_unmonitored_channel_is_not_paused(ready):
|
||||
client, engine = ready
|
||||
client.post("/v1/channels", json={"url": URL, "monitor": False}, headers=auth())
|
||||
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
|
||||
client.post(f"/v1/sessions/{sid}/stop", headers=auth())
|
||||
assert channel(client)["monitorPausedAt"] is None # nada a pausar: o monitor já estava desligado
|
||||
|
||||
|
||||
# ---------- idioma
|
||||
|
||||
def test_language_on_channel_and_session(ready):
|
||||
client, engine = ready
|
||||
default = engine.settings.language
|
||||
r = client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
|
||||
assert r.status_code == 201 and r.json()["language"] == "en-US"
|
||||
assert client.post("/v1/channels", json={"url": "https://kick.com/gaules", "language": "xx"}, headers=auth()).status_code == 400
|
||||
r2 = client.post("/v1/channels", json={"url": "https://kick.com/gaules"}, headers=auth())
|
||||
assert r2.json()["language"] == default # sem idioma = padrão do serviço, já resolvido na visão
|
||||
|
||||
# A sessão herda o idioma da fonte; `language` explícito vence; VOD solto fica no padrão.
|
||||
s = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()
|
||||
assert s["language"] == "en-US"
|
||||
assert engine.db.get("SELECT language FROM sessions WHERE id = ?", s["id"])["language"] == "en-US"
|
||||
s2 = client.post("/v1/sessions", json={"url": "https://kick.com/gaules", "language": "es-419"}, headers=auth()).json()
|
||||
assert s2["language"] == "es-419"
|
||||
assert client.post("/v1/sessions", json={"url": URL, "language": "klingon"}, headers=auth()).status_code == 400
|
||||
|
||||
# PATCH troca ('' volta ao padrão) e não mexe quando ausente.
|
||||
assert client.patch(f"/v1/channels/{CHANNEL}", json={"displayName": "Alan"}, headers=auth()).json()["language"] == "en-US"
|
||||
assert client.patch(f"/v1/channels/{CHANNEL}", json={"language": ""}, headers=auth()).json()["language"] == default
|
||||
assert client.get("/v1/status", headers=auth()).json()["settings"]["language"] == default
|
||||
|
||||
|
||||
def test_language_note_reaches_the_ai_context(ready):
|
||||
client, engine = ready
|
||||
assert output_language_note("pt-BR") == "" and output_language_note("") == "" and output_language_note(None) == ""
|
||||
assert "English (US)" in output_language_note("en-US")
|
||||
client.post("/v1/channels", json={"url": URL, "language": "en-US"}, headers=auth())
|
||||
sid = client.post("/v1/sessions", json={"url": URL}, headers=auth()).json()["id"]
|
||||
gringa = engine.db.get("SELECT * FROM sessions WHERE id = ?", sid)
|
||||
assert "Idioma de saída: English (US)" in engine.intel.context(gringa)
|
||||
engine.db.run("UPDATE sessions SET language = '' WHERE id = ?", sid)
|
||||
assert "Idioma de saída" not in engine.intel.context(engine.db.get("SELECT * FROM sessions WHERE id = ?", sid))
|
||||
|
||||
|
||||
def test_transcription_uses_session_language(ready, monkeypatch):
|
||||
_client, engine = ready
|
||||
seen = {}
|
||||
|
||||
class FakeVoice:
|
||||
configured = True
|
||||
|
||||
def transcribe(self, wav, key, language=None):
|
||||
seen["language"] = language
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(engine, "voice", FakeVoice())
|
||||
monkeypatch.setattr(worker_module.media, "decode_pcm", lambda *_a, **_k: b"")
|
||||
monkeypatch.setattr(worker_module.media, "loudness_per_second", lambda _pcm: [])
|
||||
monkeypatch.setattr(worker_module.media, "to_wav", lambda _pcm: b"")
|
||||
cur = engine.db.run("INSERT INTO sessions (platform, kind, url, status, dir, started_at, language) VALUES"
|
||||
" ('twitch', 'live', ?, 'processing', '', '2026-11-18T00:00:00+00:00', 'en-US')", URL)
|
||||
sid = cur.lastrowid
|
||||
engine.db.run("INSERT INTO segments (session_id, idx, file, start_s, end_s, wall_end) VALUES (?, 0, 'x/seg.ts', 0, 30, 0)", sid)
|
||||
engine.analyze_segment(engine.db.get("SELECT * FROM segments WHERE session_id = ?", sid))
|
||||
assert seen["language"] == "en-US"
|
||||
@@ -0,0 +1,75 @@
|
||||
# Clipador — perfis de jogo bilíngues, missões e gatilhos (18/11/2026)
|
||||
|
||||
## Pedido do dono
|
||||
|
||||
- Perfil do jogo em **português para ler** e em **inglês para a IA** (é o que vai nos prompts).
|
||||
- Cadastrar **jogo novo** pelo painel (antes só nascia quando uma live trazia a categoria).
|
||||
- **Missões** do jogo (quando já estão publicadas na internet) e **gatilhos de fim de missão**.
|
||||
- Jogos em **lista**; clicar abre um **modal** (o cartão grande ocupava a tela).
|
||||
- **GTA 6 completo**.
|
||||
|
||||
## Contrato (serviço `clipper/` ↔ painel)
|
||||
|
||||
### Perfil (mesmo formato nos dois idiomas)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"name": "Grand Theft Auto VI",
|
||||
"aliases": ["GTA 6", "GTA VI", "GTA6"], // outros nomes: a categoria da Twitch e o que a IA vê na tela caem no mesmo jogo
|
||||
"summary": "…", "genre": "…",
|
||||
"mechanics": [], "clip_worthy": [], "avoid": [], "jargon": [], "news": [], "hashtags": [], "sources": [],
|
||||
"missions": [ // [] quando ainda não há lista pública confiável
|
||||
{ "name": "…", "chapter": "…", "summary": "…", "completion_triggers": ["…"] }
|
||||
],
|
||||
"end_triggers": ["…"] // sinais gerais de fim de missão/objetivo (banner, tela de resultado, fala)
|
||||
}
|
||||
```
|
||||
|
||||
### `GET /v1/games` — cada jogo
|
||||
|
||||
| Campo | O que é |
|
||||
|---|---|
|
||||
| `profile` | Perfil em **português** (o que o painel mostra). Jogos antigos: o perfil que já existia. |
|
||||
| `profileAi` | Perfil em **inglês** (o que vai para a IA). `null` = ainda não traduzido (a IA usa `profile`). |
|
||||
| `aiLanguage` | `"en-US"` |
|
||||
| `translatedAt` | Quando a versão da IA foi gerada a partir da outra (ou vice-versa). |
|
||||
| `aliases` | Atalho de `profileAi.aliases ∪ profile.aliases`. |
|
||||
| demais | `id, name, status (pending/ready/error), error, model, researchedAt, editedAt, notes` (como antes) |
|
||||
|
||||
### Rotas
|
||||
|
||||
| Rota | O que faz |
|
||||
|---|---|
|
||||
| `POST /v1/games` `{name, notes?}` | Cadastra jogo (status `pending`) e pesquisa em segundo plano. 409 se já existe (inclusive por alias). |
|
||||
| `POST /v1/games/{id}/research` | Pesquisa na web **em inglês** (missões e gatilhos inclusos) e traduz para português. |
|
||||
| `PUT /v1/games/{id}?lang=pt\|en` | Grava a edição à mão no idioma `lang` (padrão `pt`) e traduz para o outro. Sem IA ligada: grava e marca a outra versão como desatualizada. |
|
||||
| `POST /v1/games/{id}/refine` | Pedido à IA (em português): atualiza a versão em inglês e traduz para português. Resposta `reply` em português. |
|
||||
| `POST /v1/games/{id}/translate` | Gera a versão em inglês a partir da portuguesa (jogos antigos). |
|
||||
| `DELETE /v1/games/{id}` | Apaga o jogo (sessões não mudam; o perfil é pesquisado de novo se o jogo voltar). |
|
||||
|
||||
Detalhes da implementação (serviço):
|
||||
|
||||
- `POST /v1/games` responde `{games, id}` (201); `DELETE` responde a lista. `PUT ?lang=` aceita `pt` (padrão) ou `en`.
|
||||
- `refine` aceita também as seções `missions`, `end_triggers` e `aliases`.
|
||||
- Tradução que falha (ou IA desligada): a versão traduzida fica como estava (na pesquisa, as duas em inglês) e
|
||||
`error` explica; `translatedAt` só muda quando a tradução deu certo. A tradução nunca mexe em nome, hashtags,
|
||||
fontes e outros nomes, e é recusada se perder missões.
|
||||
- Limites: até 120 missões, 8 gatilhos por missão (200 caracteres), 10 outros nomes, 12 `end_triggers`.
|
||||
|
||||
### Sementes
|
||||
|
||||
`clipper/app/seeds/games/*.json` (formato: `{name, aliases, researchedAt, sources, profileAi, profile}`) é
|
||||
importado na subida do serviço **só se o jogo ainda não existe** (nunca sobrescreve edição). O GTA VI vem assim.
|
||||
|
||||
### Prompts
|
||||
|
||||
- O contexto da IA (`game_context`) usa `profileAi` (fallback `profile`), inclui `end_triggers` e as missões
|
||||
(nome + gatilhos, limitado) e diz ao editor: corte de missão termina logo depois do gatilho de fim.
|
||||
- Busca por nome casa `id` **ou** alias (categoria "Grand Theft Auto VI", tela "GTA 6" → mesmo perfil).
|
||||
|
||||
## Painel
|
||||
|
||||
- `/clipper/games`: tabela (nome, gênero, estado, missões, última pesquisa/edição) + "Adicionar jogo" (diálogo).
|
||||
- Clique abre o **modal do jogo**: abas Visão geral · Rende corte · Missões · Gatilhos de fim · Termos e hashtags ·
|
||||
Fontes · Pedidos à IA; alternância **Português (você lê) / English (vai para a IA)**; ações Pesquisar de novo, Editar, Pedir à
|
||||
IA, Apagar.
|
||||
@@ -0,0 +1,64 @@
|
||||
# Clipador — reorganização da interface (18/11/2026)
|
||||
|
||||
## Por que
|
||||
|
||||
A página `/clipper` cresceu por acréscimo: um resumo com 4 cartões, a barra da live, 5 abas, e dentro
|
||||
delas cartões gigantes (um corte ocupa meia tela; uma sessão, uma tela inteira). Os cliques ficaram
|
||||
confusos (ação primária e secundária no mesmo peso), a informação do corte aprovado se perde, e não há
|
||||
lugar para o que vem a seguir: canais em outros idiomas (público gringo) ao lado dos canais em português.
|
||||
|
||||
## O que muda
|
||||
|
||||
### Navegação: subpáginas, não abas
|
||||
|
||||
| Rota | O que é | Conteúdo |
|
||||
|---|---|---|
|
||||
| `/clipper` | **Cortes** | Lista (uma linha por corte), filtros por etapa / fonte / sessão / idioma, ordenação. Clique abre o **modal do corte** (`?clip=ID`), com anterior/próximo para aprovar em sequência. Ações rápidas na linha (Aprovar, Rejeitar, Publicar). |
|
||||
| `/clipper/sessions` | **Sessões** | Lista compacta (estado, fonte, duração, cortes, saúde em uma frase). "Gravar pelo link" vira um botão que abre diálogo. |
|
||||
| `/clipper/sessions/[id]` | **Detalhe da sessão** | O que hoje é o cartão da sessão (saúde, "agora na live", chat/transcrição/IA/cortes, gráfico, emotes, câmera, jogo, configuração do corte) e os cortes dela. |
|
||||
| `/clipper/sources` | **Fontes** | Lista das fontes (streamers): ao vivo/offline, monitor (ligado / **pausado** / desligado), autorização, idioma da live, canais de publicação ligados. "Adicionar fonte" em diálogo. |
|
||||
| `/clipper/games` | **Jogos** | O que a IA sabe dos jogos (como hoje). |
|
||||
| `/clipper/settings` | **Ajustes** | Juiz (IA), estado do serviço e das ferramentas, transcrição, idioma padrão. |
|
||||
|
||||
A sidebar mostra os subitens do Clipador quando ele está ativo; a mesma sub-navegação aparece no topo
|
||||
das páginas, com contadores (para aprovar, gravando agora). O editor em tela cheia (`/clipper/edit/[id]`)
|
||||
fica fora desse quadro (grupo de rotas `(studio)`).
|
||||
|
||||
### Hierarquia visual
|
||||
|
||||
- Um bloco **"Ao vivo agora · N"** acima do conteúdo em todas as subpáginas enquanto algo grava: uma linha
|
||||
fina por live (nome, relógio, chat, "Cortar agora", Parar só com ícone). Pensado para 5 canais no ar ao
|
||||
mesmo tempo sem tomar a tela. É a única coisa que precisa estar sempre à mão.
|
||||
- O "Resumo" com 4 cartões sai. O estado do serviço vira uma linha discreta ao lado da sub-navegação
|
||||
(ponto verde/vermelho + texto) e o detalhe mora em Ajustes.
|
||||
- Listas antes de cartões: a lista mostra o que decide (título, nota da IA, situação, fonte, duração,
|
||||
estado); o modal mostra o resto (vídeo, veredito completo, sinais, legenda, ajuste de trecho, transcrição,
|
||||
publicação).
|
||||
|
||||
### Sessão: parar é parar
|
||||
|
||||
Hoje o monitor da fonte reabre uma sessão nova 60 s depois de você parar à mão, porque a live continua no ar.
|
||||
Regra nova:
|
||||
|
||||
- **Parar à mão pausa o monitor daquela fonte** (`channels.monitor_paused_at` + a sessão que motivou). O
|
||||
monitor pula a fonte enquanto a pausa existir. A fonte aparece como "monitor pausado · você parou a sessão
|
||||
#11" com o botão **Religar**. Ligar o switch "Monitorar" também limpa a pausa.
|
||||
- No diálogo de parar há a opção "voltar a gravar sozinho quando a live cair e voltar": marcada, não pausa.
|
||||
- Queda de live (captura cai sem ninguém pedir) continua sendo **retomada na mesma sessão** (`interrupted`
|
||||
→ `keep_live`), como já era. Isso é o "caso caia, liga".
|
||||
|
||||
### Idioma e público (preparação para canais gringos)
|
||||
|
||||
- **Fonte** e **sessão** ganham `language` (idioma falado na live; padrão `CLIPPER_LANGUAGE`). A transcrição
|
||||
(Whisper) usa o idioma da sessão; os prompts da IA recebem o idioma de saída (título, legenda, hashtags).
|
||||
- **Canal de publicação** (`accounts`) ganha `language` (idioma/público: pt-BR, en-US, es-419…). O diálogo
|
||||
"Publicar" avisa quando o idioma do corte difere do idioma do canal.
|
||||
- Lista de cortes e sessões filtram por idioma. Versões traduzidas de um corte (legenda queimada e textos em
|
||||
outro idioma a partir da mesma sessão) são a **próxima etapa**; o modelo já tem onde encaixar.
|
||||
|
||||
## Arquivos
|
||||
|
||||
- Dados compartilhados: `panel/src/components/clipper-provider.tsx` (contexto + consulta periódica).
|
||||
- Moldura: `panel/src/components/clipper-shell.tsx` (cabeçalho compacto, sub-navegação, barra da live).
|
||||
- Páginas: `panel/src/app/clipper/(studio)/…`.
|
||||
- Serviço: `clipper/app/worker.py` (pausa do monitor), `db.py` (colunas novas), `main.py` (rotas/visões).
|
||||
@@ -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>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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}
|
||||
<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>
|
||||
<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>
|
||||
<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,43 +155,108 @@ 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">
|
||||
<>
|
||||
<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-44 flex-1 gap-1">
|
||||
<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 max-w-60" />
|
||||
<Button size="sm" variant="secondary" disabled={pending !== null}>{pending === "rename" ? <Spinner className="size-3.5" /> : <CheckIcon size={15} />}Salvar</Button>
|
||||
<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>
|
||||
) : (
|
||||
<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">
|
||||
<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>
|
||||
{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>
|
||||
</span>
|
||||
)}
|
||||
<p className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-subtle">
|
||||
<span className="flex flex-wrap items-center gap-x-2 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>
|
||||
<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>
|
||||
{accounts.length > 0 && (
|
||||
<span className="inline-flex flex-wrap items-center gap-1.5">
|
||||
<UsersIcon size={13} />
|
||||
</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>
|
||||
)}
|
||||
</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}>
|
||||
@@ -142,41 +265,60 @@ function ChannelRow({ channel: c, accounts, onChanged, onConfigure, showEmotes }
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
) : (
|
||||
<Link href="/accounts" className="text-xs text-fg-subtle underline-offset-2 hover:text-fg hover:underline">ligar a um canal</Link>
|
||||
)}
|
||||
</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>
|
||||
</Td>
|
||||
|
||||
<Td className="text-right">
|
||||
<div className="flex flex-wrap items-center justify-end gap-1">
|
||||
{isLive && checked?.live && (
|
||||
<Button size="sm" disabled={pending !== null}
|
||||
<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="ghost" size="sm" disabled={pending !== null} aria-label={`Remover a fonte ${name}`}
|
||||
<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={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>
|
||||
{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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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")} />;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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" };
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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}</>;
|
||||
}
|
||||
@@ -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) {
|
||||
/** 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 (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
<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 (
|
||||
<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 ---------- */
|
||||
|
||||
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}%
|
||||
<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>
|
||||
{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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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">
|
||||
<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>
|
||||
</form>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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)!;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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() : "—");
|
||||
}
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user