// IA: configuração (data/ai/settings.json), classificador de indisponibilidade, ambiente por modo de login, cofre // 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"; import os from "node:os"; import path from "node:path"; import { before, describe, it } from "node:test"; const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "cenaforge-ai-")); process.env.CENAFORGE_ROOT = ROOT; type Ai = typeof import("./ai"); type Agents = typeof import("./agents"); type Db = typeof import("./db"); let ai: Ai; let agents: Agents; let dbm: Db; const SETTINGS = () => path.join(ROOT, "data", "ai", "settings.json"); before(async () => { ai = await import("./ai"); agents = await import("./agents"); dbm = await import("./db"); }); describe("configuração da IA", () => { 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", "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.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: ["antigravity", "antigravity", "gemini", "x"], providers: { codex: { enabled: "sim", authMode: "nada" }, gemini: { enabled: true } }, fallback: { cooldownMin: 9999 } })); const s = ai.readAiSettings(); 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); fs.rmSync(SETTINGS()); }); it("salva só o que veio e recusa ordem inválida", () => { 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: { antigravity: { authMode: "senha" as never } } }), /Modo de login/); assert.equal(ai.readAiSettings().fallback.cooldownMin, 30); }); }); describe("indisponibilidade (dispara a reserva)", () => { for (const text of [ "API Error: 429 rate_limit_error", "You've hit your usage limit", "Credit balance is too low", "Overloaded (529)", "IneligibleTierError: This client is no longer supported", "Not logged in · Please run /login", "getaddrinfo ENOTFOUND api.openai.com", "não iniciou: spawn ENOENT", "Invalid API key", ]) it(`troca de IA: ${text}`, () => assert.equal(ai.isAvailabilityError(text), true)); for (const text of ["saiu com código 1", "SyntaxError: Unexpected token in JSON", "Parou no teto de gasto desta tarefa", ""]) { it(`não troca: ${text || "(vazio)"}`, () => assert.equal(ai.isAvailabilityError(text), false)); } }); describe("ambiente de cada chamada", () => { 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"); assert.equal(ai.providerEnv("antigravity", base).GEMINI_API_KEY, undefined); }); it("modo chave sem chave salva não vaza a do ambiente do painel", () => { ai.updateAiSettings({ providers: { codex: { authMode: "apiKey" } } }); assert.equal(ai.providerEnv("codex", { CODEX_API_KEY: "sk-do-sistema" }).CODEX_API_KEY, undefined); }); it("cofre DPAPI: guarda, injeta só na chamada e apaga", { skip: process.platform !== "win32" && "DPAPI só existe no Windows" }, () => { assert.throws(() => ai.setApiKey("codex", "curta"), /não parece válida/); ai.setApiKey("codex", "sk-test-0123456789abcdefWXYZ"); const bytes = fs.readFileSync(path.join(ROOT, "data", "ai", "vault.bin")); assert.equal(bytes.includes(Buffer.from("sk-test")), false, "a chave não pode ficar em texto claro"); assert.equal(ai.providerEnv("codex", {}).CODEX_API_KEY, "sk-test-0123456789abcdefWXYZ"); ai.setApiKey("codex", null); assert.equal(fs.existsSync(path.join(ROOT, "data", "ai", "vault.bin")), false); assert.equal(ai.providerEnv("codex", {}).CODEX_API_KEY, undefined); }); }); 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("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) => 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)" }]); }); });