Clipador: fontes em inglês (juízes em inglês, painel em português) e monitor de uso da IA
Clipador em inglês (doc/clipador/IDIOMAS.md):
- Fonte en-US: analista, editor e varredura com prompts, glossário de chat e saída em inglês;
a mesma resposta traz o bloco `pt` (tradução para o painel, sem chamada extra).
- Fala do corte traduzida por frase (clips.translation_json, migração v13) e
POST /v1/clips/{id}/translate.
- caption.translation (só para desenvolver): português embaixo da legenda em inglês.
- Risada e gírias do chat em inglês na heurística (LMAO, LOL, 💀, 😭, no way, bruh...).
- Idioma do público → código do Whisper (en-US dava 422 no serviço de voz).
- Painel: bloco "Em português" no corte, análise/resumo em PT, título traduzido na lista,
coluna "Ao vivo" mostra a gravação ativa da fonte.
IA: monitor de uso do limite (ai-usage) e 4º provedor (Antigravity CLI).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+122
-41
@@ -1,5 +1,5 @@
|
||||
// IA: configuração (data/ai/settings.json), classificador de indisponibilidade, ambiente por modo de login, cofre
|
||||
// DPAPI (só no Windows) e o normalizador do Gemini. Tudo numa pasta TEMPORÁRIA (CENAFORGE_ROOT); nenhuma CLI real é
|
||||
// DPAPI (só no Windows), uso e limites e o Antigravity. Tudo numa pasta TEMPORÁRIA (CENAFORGE_ROOT); nenhuma CLI real é
|
||||
// chamada. Rodar: pnpm --filter cenaforge-panel test:panel
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
@@ -25,20 +25,22 @@ before(async () => {
|
||||
});
|
||||
|
||||
describe("configuração da IA", () => {
|
||||
it("sem arquivo usa o padrão: Claude e Codex ligados na conta, Gemini desligado", () => {
|
||||
it("sem arquivo usa o padrão: Claude e Codex ligados na conta, Antigravity desligado", () => {
|
||||
const s = ai.readAiSettings();
|
||||
assert.deepEqual(s.order, ["claude", "codex", "gemini"]);
|
||||
assert.deepEqual(s.order, ["claude", "codex", "antigravity"]);
|
||||
assert.equal(s.providers.antigravity.enabled, false);
|
||||
assert.equal(s.providers.antigravity.authMode, "oauth");
|
||||
assert.equal(s.fallback.usageLimitPercent, 90);
|
||||
assert.equal(s.providers.claude.enabled, true);
|
||||
assert.equal(s.providers.gemini.enabled, false);
|
||||
assert.equal(s.providers.gemini.authMode, "apiKey");
|
||||
assert.equal(s.fallback.enabled, true);
|
||||
});
|
||||
|
||||
it("normaliza arquivo estragado: ordem sem repetição e completa, pausa dentro do limite", () => {
|
||||
fs.mkdirSync(path.dirname(SETTINGS()), { recursive: true });
|
||||
fs.writeFileSync(SETTINGS(), JSON.stringify({ order: ["gemini", "gemini", "x"], providers: { codex: { enabled: "sim", authMode: "nada" } }, fallback: { cooldownMin: 9999 } }));
|
||||
fs.writeFileSync(SETTINGS(), JSON.stringify({ order: ["antigravity", "antigravity", "gemini", "x"], providers: { codex: { enabled: "sim", authMode: "nada" }, gemini: { enabled: true } }, fallback: { cooldownMin: 9999 } }));
|
||||
const s = ai.readAiSettings();
|
||||
assert.deepEqual(s.order, ["gemini", "claude", "codex"]);
|
||||
assert.deepEqual(s.order, ["antigravity", "claude", "codex"], "o \"gemini\" de um arquivo antigo é ignorado");
|
||||
assert.equal("gemini" in s.providers, false);
|
||||
assert.equal(s.providers.codex.enabled, true);
|
||||
assert.equal(s.providers.codex.authMode, "oauth");
|
||||
assert.equal(s.fallback.cooldownMin, 240);
|
||||
@@ -46,12 +48,13 @@ describe("configuração da IA", () => {
|
||||
});
|
||||
|
||||
it("salva só o que veio e recusa ordem inválida", () => {
|
||||
const s = ai.updateAiSettings({ providers: { gemini: { enabled: true } }, order: ["codex", "gemini", "claude"], fallback: { cooldownMin: 30 } });
|
||||
assert.equal(s.providers.gemini.enabled, true);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(SETTINGS(), "utf8")).order, ["codex", "gemini", "claude"]);
|
||||
const s = ai.updateAiSettings({ providers: { antigravity: { enabled: true } }, order: ["codex", "antigravity", "claude"], fallback: { cooldownMin: 30 } });
|
||||
assert.equal(s.providers.antigravity.enabled, true);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(SETTINGS(), "utf8")).order, ["codex", "antigravity", "claude"]);
|
||||
assert.throws(() => ai.updateAiSettings({ order: ["codex", "codex", "claude"] }), /cada IA uma vez/);
|
||||
assert.throws(() => ai.updateAiSettings({ order: ["codex", "gemini", "claude"] }), /cada IA uma vez/);
|
||||
assert.throws(() => ai.updateAiSettings({ fallback: { cooldownMin: 0 } }), /entre 1 e 240/);
|
||||
assert.throws(() => ai.updateAiSettings({ providers: { gemini: { authMode: "senha" as never } } }), /Modo de login/);
|
||||
assert.throws(() => ai.updateAiSettings({ providers: { antigravity: { authMode: "senha" as never } } }), /Modo de login/);
|
||||
assert.equal(ai.readAiSettings().fallback.cooldownMin, 30);
|
||||
});
|
||||
});
|
||||
@@ -68,15 +71,13 @@ describe("indisponibilidade (dispara a reserva)", () => {
|
||||
});
|
||||
|
||||
describe("ambiente de cada chamada", () => {
|
||||
it("modo conta tira a chave do ambiente; Gemini na conta liga GOOGLE_GENAI_USE_GCA", () => {
|
||||
ai.updateAiSettings({ providers: { claude: { authMode: "oauth" }, gemini: { authMode: "oauth" } } });
|
||||
it("modo conta tira a chave do ambiente (a CLI usaria a chave em vez da conta)", () => {
|
||||
ai.updateAiSettings({ providers: { claude: { authMode: "oauth" }, antigravity: { authMode: "oauth" } } });
|
||||
const base = { ANTHROPIC_API_KEY: "sk-ant-velha", GEMINI_API_KEY: "AIza-velha", PATH: "x" };
|
||||
const claude = ai.providerEnv("claude", base);
|
||||
assert.equal(claude.ANTHROPIC_API_KEY, undefined);
|
||||
assert.equal(claude.PATH, "x");
|
||||
const gemini = ai.providerEnv("gemini", base);
|
||||
assert.equal(gemini.GEMINI_API_KEY, undefined);
|
||||
assert.equal(gemini.GOOGLE_GENAI_USE_GCA, "true");
|
||||
assert.equal(ai.providerEnv("antigravity", base).GEMINI_API_KEY, undefined);
|
||||
});
|
||||
|
||||
it("modo chave sem chave salva não vaza a do ambiente do painel", () => {
|
||||
@@ -96,32 +97,112 @@ describe("ambiente de cada chamada", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Gemini: eventos do stream-json", () => {
|
||||
it("junta o texto em pedaços, registra sessão, ferramenta e resultado", () => {
|
||||
const id = Number(dbm.run(`INSERT INTO agent_runs (provider, model, kind, prompt, status, log_path, started_at)
|
||||
VALUES ('gemini', '', 'free', 'oi', 'running', '', ?)`, dbm.now()).lastInsertRowid);
|
||||
const state: import("./agents").GeminiState = { text: "" };
|
||||
const n = (o: Record<string, unknown>) => agents.normalizeGemini(o, id, state);
|
||||
assert.deepEqual(n({ type: "init", session_id: "abc-123", model: "gemini-3.5-flash" }).map((e) => e.kind), ["system"]);
|
||||
assert.deepEqual(n({ type: "message", role: "user", content: "oi" }), []);
|
||||
assert.deepEqual(n({ type: "message", role: "assistant", content: "Vou ", delta: true }), []);
|
||||
assert.deepEqual(n({ type: "message", role: "assistant", content: "ler.", delta: true }), []);
|
||||
const tool = n({ type: "tool_use", tool_name: "read_file", tool_id: "t1", parameters: { file_path: "README.md" } });
|
||||
assert.deepEqual(tool.map((e) => [e.kind, e.text]), [["text", "Vou ler."], ["tool", "read_file README.md"]]);
|
||||
assert.equal(n({ type: "tool_result", tool_id: "t1", status: "error", error: { message: "sem permissão" } })[0].isError, true);
|
||||
const done = n({ type: "result", status: "error", error: { type: "API", message: "429 quota exceeded" }, stats: {} });
|
||||
assert.equal(done[0].isError, true);
|
||||
const row = dbm.get<{ session_id: string; error: string; num_turns: number }>("SELECT session_id, error, num_turns FROM agent_runs WHERE id = ?", id)!;
|
||||
assert.equal(row.session_id, "abc-123");
|
||||
assert.match(row.error, /429/);
|
||||
assert.equal(ai.isAvailabilityError(row.error), true);
|
||||
describe("uso e limites", () => {
|
||||
type Usage = typeof import("./ai-usage");
|
||||
let usage: Usage;
|
||||
before(async () => { usage = await import("./ai-usage"); });
|
||||
const NOW = new Date(2026, 10, 18, 2, 30); // 18/11/2026 02:30, horário local
|
||||
|
||||
it("lê o texto do /usage do Claude (sessão, semana e semana por modelo)", () => {
|
||||
const text = "You are currently using your subscription to power your Claude Code usage\n\n" +
|
||||
"Current session: 2% used · resets Nov 18, 7:10am (America/Sao_Paulo)\n" +
|
||||
"Current week (all models): 67% used · resets Nov 21, 2pm (America/Sao_Paulo)\n" +
|
||||
"Current week (Fable): 24% used · resets Nov 21, 2pm (America/Sao_Paulo)\n\nWhat's contributing to your usage?";
|
||||
const r = usage.parseClaudeUsageText(text, NOW);
|
||||
assert.equal(r.subscription, true);
|
||||
assert.deepEqual(r.windows.map((w) => [w.id, w.usedPercent]), [["five_hour", 2], ["seven_day", 67], ["seven_day_fable", 24]]);
|
||||
assert.equal(new Date(r.windows[0].resetsAt!).getTime(), new Date(2026, 10, 18, 7, 10).getTime());
|
||||
assert.equal(new Date(r.windows[1].resetsAt!).getTime(), new Date(2026, 10, 21, 14, 0).getTime());
|
||||
});
|
||||
|
||||
it("argumentos: modo headless, edição automática, retomada e shell só o liberado", () => {
|
||||
const args = agents.geminiArgs("faça X", "gemini-2.5-pro", "sess-1");
|
||||
assert.deepEqual(args.slice(0, 7), ["-p", "faça X", "-o", "stream-json", "--approval-mode", "auto_edit", "--skip-trust"]);
|
||||
assert.ok(args.includes("--resume") && args.includes("sess-1"));
|
||||
assert.ok(args.some((a) => a.startsWith("run_shell_command(pnpm render")));
|
||||
assert.equal(args.includes("--yolo"), false);
|
||||
it("reset só com a hora: hoje, ou amanhã se já passou; virada de ano", () => {
|
||||
assert.equal(new Date(usage.parseClaudeReset("5pm", NOW)!).getDate(), 18);
|
||||
assert.equal(new Date(usage.parseClaudeReset("1:15am", NOW)!).getDate(), 19);
|
||||
assert.equal(new Date(usage.parseClaudeReset("Jan 2, 9am", new Date(2026, 11, 30))!).getFullYear(), 2027);
|
||||
});
|
||||
|
||||
it("lê o account/rateLimits/read do Codex e marca quando bateu", () => {
|
||||
const u = usage.parseCodexLimits({
|
||||
ordinaryUsageAllowed: false,
|
||||
rateLimits: { primary: { usedPercent: 100, windowDurationMins: 300, resetsAt: 1794979788 },
|
||||
secondary: { usedPercent: 29, windowDurationMins: 10080, resetsAt: 1795530834 }, planType: "plus", rateLimitReachedType: "rate_limit_reached" },
|
||||
rateLimitResetCredits: { availableCount: 2 },
|
||||
});
|
||||
assert.deepEqual(u.windows.map((w) => [w.label, w.usedPercent]), [["Sessão (5 h)", 100], ["Semana", 29]]);
|
||||
assert.equal(u.blocked, true);
|
||||
assert.equal(u.plan, "plus");
|
||||
assert.match(u.note!, /2 resets/);
|
||||
});
|
||||
|
||||
it("evento rate_limit_event do agente Claude vira uso (0–1 → %)", () => {
|
||||
usage.recordClaudeRateLimit({ status: "allowed", unifiedWindows: {
|
||||
five_hour: { utilization: 0.93, resetsAt: Math.floor(Date.now() / 1000) + 3600 },
|
||||
seven_day: { utilization: 0.4, resetsAt: Math.floor(Date.now() / 1000) + 86400 } } });
|
||||
const u = ai.getUsage("claude")!;
|
||||
assert.equal(u.windows[0].usedPercent, 93);
|
||||
assert.equal(u.source, "run");
|
||||
assert.ok(fs.existsSync(path.join(ROOT, "data", "ai", "usage.json")), "o Clipador lê o uso deste arquivo");
|
||||
});
|
||||
|
||||
it("limite: 90% tira da frente; janela que já zerou e leitura velha não contam", () => {
|
||||
ai.updateAiSettings({ fallback: { usageLimitPercent: 90 } });
|
||||
assert.match(ai.overLimit("claude")!, /Sessão \(5 h\) em 93%/);
|
||||
ai.updateAiSettings({ fallback: { usageLimitPercent: 95 } });
|
||||
assert.equal(ai.overLimit("claude"), null);
|
||||
const base = { source: "cli" as const, plan: null, note: null, error: null };
|
||||
ai.setUsage("codex", { ...base, at: new Date().toISOString(), blocked: true,
|
||||
windows: [{ id: "five_hour", label: "Sessão (5 h)", usedPercent: 100, resetsAt: new Date(Date.now() - 60_000).toISOString() }] });
|
||||
assert.equal(ai.overLimit("codex"), null, "a janela já zerou");
|
||||
ai.setUsage("codex", { ...base, at: new Date(Date.now() - 3_600_000).toISOString(), blocked: true,
|
||||
windows: [{ id: "five_hour", label: "Sessão (5 h)", usedPercent: 100, resetsAt: new Date(Date.now() + 60_000).toISOString() }] });
|
||||
assert.equal(ai.overLimit("codex"), null, "leitura de 1 h atrás não decide");
|
||||
assert.throws(() => ai.updateAiSettings({ fallback: { usageLimitPercent: 30 } }), /entre 50% e 100%/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Antigravity (agy 1.5.10)", () => {
|
||||
it("argumentos: headless, edição automática e shell só com regra exata (sem curinga)", () => {
|
||||
const args = agents.antigravityArgs("faça X", "gemini-3.8-flash-medium", "conv-1");
|
||||
assert.deepEqual(args.slice(0, 6), ["-p", "faça X", "--output-format", "stream-json", "--mode", "accept-edits"]);
|
||||
const settings = JSON.parse(args[args.indexOf("--settings") + 1]) as { permissions: { allow: string[] } };
|
||||
assert.ok(settings.permissions.allow.includes("command(pnpm typecheck)"));
|
||||
assert.equal(settings.permissions.allow.some((r) => r.includes("*")), false);
|
||||
assert.ok(args.includes("--conversation") && args.includes("conv-1"));
|
||||
assert.equal(args.includes("--dangerously-skip-permissions"), false);
|
||||
});
|
||||
|
||||
it("eventos: conversa, texto em pedaços, ferramenta (ativa e recusada) e resultado", () => {
|
||||
const id = Number(dbm.run(`INSERT INTO agent_runs (provider, model, kind, prompt, status, log_path, started_at)
|
||||
VALUES ('antigravity', '', 'free', 'oi', 'running', '', ?)`, dbm.now()).lastInsertRowid);
|
||||
const state: import("./agents").TextBuffer = { text: "" };
|
||||
const n = (o: Record<string, unknown>) => agents.normalizeAntigravity(o, id, state);
|
||||
n({ event: "init", conversation_id: "c-9", init: { permission_mode: "request-review" } });
|
||||
assert.deepEqual(n({ event: "step_update", step_update: { step_type: "agent_response", state: "ACTIVE", text_delta: "Vou " } }), []);
|
||||
n({ event: "step_update", step_update: { step_type: "agent_response", state: "DONE", text_delta: "criar." } });
|
||||
const tool = n({ event: "step_update", step_update: { step_type: "tool", state: "ACTIVE", tool_name: "write_file", tool_info: { parameters: { Path: "teste.txt" } } } });
|
||||
assert.deepEqual(tool.map((e) => [e.kind, e.text]), [["text", "Vou criar."], ["tool", "write_file teste.txt"]]);
|
||||
const denied = n({ event: "step_update", step_update: { step_type: "tool", state: "ERROR", tool_name: "run_command", tool_info: { parameters: { CommandLine: "whoami" } } } });
|
||||
assert.equal(denied[0].isError, true);
|
||||
const done = n({ event: "result", result: { status: "SUCCESS", response: "feito", num_turns: 1, usage: { input_tokens: 11199, output_tokens: 247, cache_read_tokens: 6791 } } });
|
||||
assert.match(done[0].text, /11199 tokens de entrada \(6791 em cache\)/);
|
||||
const row = dbm.get<{ session_id: string; result: string }>("SELECT session_id, result FROM agent_runs WHERE id = ?", id)!;
|
||||
assert.deepEqual([row.session_id, row.result], ["c-9", "feito"]);
|
||||
});
|
||||
|
||||
it("uso (/usage): fração restante → % usado, do grupo Gemini; o outro grupo vira nota", async () => {
|
||||
const { parseAgyUsage } = await import("./ai-usage");
|
||||
const u = parseAgyUsage({ groups: [
|
||||
{ name: "Gemini Models", buckets: [
|
||||
{ id: "gemini-weekly", window: "weekly", remaining_fraction: 0.949576735496521, reset_time: "2026-11-25T03:53:32Z" },
|
||||
{ id: "gemini-5h", window: "5h", remaining_fraction: 0.8792469501495361, reset_time: "2026-11-18T08:53:32Z" }] },
|
||||
{ name: "Claude and GPT models", buckets: [{ id: "3p-5h", window: "5h", remaining_fraction: 1 }] }] });
|
||||
assert.deepEqual(u.windows.map((w) => [w.label, w.usedPercent]), [["Semana", 5], ["Sessão (5 h)", 12.1]]);
|
||||
assert.equal(u.blocked, false);
|
||||
assert.match(u.note!, /Claude and GPT models: 0% usado/);
|
||||
});
|
||||
|
||||
it("modelos: lê `agy models` (id + tab + nome) e ignora a linha de aviso", () => {
|
||||
const list = ai.parseAgyModels("Fetching available models...\ngemini-4-carbon-medium\tGemini 4 Carbon (Medium)\ngemini-3.8-flash-medium\tGemini 3.8 Flash (Medium)\n");
|
||||
assert.deepEqual(list, [{ id: "gemini-4-carbon-medium", label: "Gemini 4 Carbon (Medium)" }, { id: "gemini-3.8-flash-medium", label: "Gemini 3.8 Flash (Medium)" }]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user