feat: cap daily and monthly ai budget
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
bf84577097
commit
4cba23b264
8 changed files with 185 additions and 11 deletions
|
|
@ -36,6 +36,14 @@
|
||||||
};
|
};
|
||||||
|
|
||||||
// ---------- Barre système ----------
|
// ---------- Barre système ----------
|
||||||
|
// "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint
|
||||||
|
function gauge(label, x) {
|
||||||
|
const used = `${x.used.toFixed(2)} $`;
|
||||||
|
if (!x.limit) return `<span title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used}</span>`;
|
||||||
|
const r = x.used / x.limit;
|
||||||
|
return `<span class="${r >= 1 ? 'error' : r >= 0.8 ? 'warn' : ''}" title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used} / ${x.limit} $</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshSys() {
|
async function refreshSys() {
|
||||||
const el = $('#sys');
|
const el = $('#sys');
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
@ -43,7 +51,8 @@
|
||||||
const s = await api('/api/system');
|
const s = await api('/api/system');
|
||||||
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
||||||
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
||||||
<span title="Équivalent API, consommé sur ton quota Pro">IA 24 h : $${s.usage.day.cost.toFixed(2)} · 30 j : $${s.usage.month.cost.toFixed(2)}</span>
|
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
||||||
|
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}
|
||||||
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}
|
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}
|
||||||
${s.scheduled ? `<span>${s.scheduled} programmé(s) cette nuit</span>` : ''}`;
|
${s.scheduled ? `<span>${s.scheduled} programmé(s) cette nuit</span>` : ''}`;
|
||||||
} catch { /* silencieux */ }
|
} catch { /* silencieux */ }
|
||||||
|
|
@ -67,7 +76,7 @@
|
||||||
const extra = type === 'prospect' && p.found !== undefined
|
const extra = type === 'prospect' && p.found !== undefined
|
||||||
? `<strong>${p.found}</strong> prospect(s) trouvé(s) sur ${p.target}` : '';
|
? `<strong>${p.found}</strong> prospect(s) trouvé(s) sur ${p.target}` : '';
|
||||||
box.innerHTML = `<div class="running"><span class="spinner"></span>
|
box.innerHTML = `<div class="running"><span class="spinner"></span>
|
||||||
<div><div>${esc(job.status === 'queued' ? 'En file d\'attente…' : p.message || 'En cours…')}</div>${extra ? `<div class="small">${extra}</div>` : ''}</div>
|
<div><div>${esc(p.message || (job.status === 'queued' ? 'En file d\'attente…' : 'En cours…'))}</div>${extra ? `<div class="small">${extra}</div>` : ''}</div>
|
||||||
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
|
<button class="btn small" data-cancel="${job.id}">Annuler</button></div>`;
|
||||||
} else if (job.status === 'error') {
|
} else if (job.status === 'error') {
|
||||||
box.innerHTML = `<p class="error small">${LABELS[type]} en échec : ${esc(job.error)}</p>`;
|
box.innerHTML = `<p class="error small">${LABELS[type]} en échec : ${esc(job.error)}</p>`;
|
||||||
|
|
@ -263,13 +272,13 @@
|
||||||
case 'target': await api(`/api/projects/${id}/target`, data); toast('Cible validée'); setTimeout(() => location.reload(), 500); break;
|
case 'target': await api(`/api/projects/${id}/target`, data); toast('Cible validée'); setTimeout(() => location.reload(), 500); break;
|
||||||
case 'prospect': {
|
case 'prospect': {
|
||||||
const r = await api(`/api/projects/${id}/prospect`, data);
|
const r = await api(`/api/projects/${id}/prospect`, data);
|
||||||
toast(r.existing ? 'Une recherche est déjà prévue ou en cours' : data.when === 'night' ? 'Recherche programmée cette nuit' : 'Recherche lancée en arrière-plan');
|
toast(r.budgetBlocked ? `En file, mais ${r.budgetBlocked}` : r.existing ? 'Une recherche est déjà prévue ou en cours' : data.when === 'night' ? 'Recherche programmée cette nuit' : 'Recherche lancée en arrière-plan', r.budgetBlocked ? 'error' : 'ok');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'evolution': {
|
case 'evolution': {
|
||||||
if (data.level === 'approfondi' && !confirm('Le niveau approfondi utilise Opus et consomme beaucoup de quota. Continuer ?')) break;
|
if (data.level === 'approfondi' && !confirm('Le niveau approfondi utilise Opus et consomme beaucoup de quota. Continuer ?')) break;
|
||||||
const r = await api(`/api/projects/${id}/evolution`, data);
|
const r = await api(`/api/projects/${id}/evolution`, data);
|
||||||
toast(r.existing ? 'Une recherche est déjà prévue ou en cours' : data.when === 'night' ? 'Évolutions programmées cette nuit' : 'Recherche d\'évolutions lancée');
|
toast(r.budgetBlocked ? `En file, mais ${r.budgetBlocked}` : r.existing ? 'Une recherche est déjà prévue ou en cours' : data.when === 'night' ? 'Évolutions programmées cette nuit' : 'Recherche d\'évolutions lancée', r.budgetBlocked ? 'error' : 'ok');
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'template': {
|
case 'template': {
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import { checkInbox } from './services/inbox.js';
|
||||||
import { followupPlan } from './services/followup.js';
|
import { followupPlan } from './services/followup.js';
|
||||||
import { nextNightSlot } from './services/paris-time.js';
|
import { nextNightSlot } from './services/paris-time.js';
|
||||||
import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js';
|
import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js';
|
||||||
|
import { budgetState, AI_JOBS } from './services/budget.js';
|
||||||
import {
|
import {
|
||||||
getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp,
|
getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp,
|
||||||
prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats,
|
prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats,
|
||||||
|
|
@ -70,6 +71,8 @@ export function registerRoutes(router, app) {
|
||||||
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
||||||
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
||||||
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
||||||
|
budget_day_usd: getSetting(db, 'budget_day_usd', ''),
|
||||||
|
budget_month_usd: getSetting(db, 'budget_month_usd', ''),
|
||||||
discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS },
|
discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS },
|
||||||
};
|
};
|
||||||
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
||||||
|
|
@ -88,6 +91,9 @@ export function registerRoutes(router, app) {
|
||||||
setSetting(db, 'send_delay_min', String(dmin));
|
setSetting(db, 'send_delay_min', String(dmin));
|
||||||
setSetting(db, 'send_delay_max', String(dmax));
|
setSetting(db, 'send_delay_max', String(dmax));
|
||||||
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||||
|
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
||||||
|
setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
||||||
|
setSetting(db, 'budget_month_usd', money(b.budget_month_usd));
|
||||||
|
|
||||||
const hook = String(b.discord_webhook || '').trim();
|
const hook = String(b.discord_webhook || '').trim();
|
||||||
if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)');
|
if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)');
|
||||||
|
|
@ -113,7 +119,7 @@ export function registerRoutes(router, app) {
|
||||||
const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
||||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n;
|
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n;
|
||||||
const scheduled = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
const scheduled = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
||||||
json(res, { temp: cpuTemp(), queue, scheduled, usage: usageSummary(db), thermalMax: cfg.thermalMax });
|
json(res, { temp: cpuTemp(), queue, scheduled, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects', async ({ req, res }) => {
|
router.post('/api/projects', async ({ req, res }) => {
|
||||||
|
|
@ -182,7 +188,8 @@ export function registerRoutes(router, app) {
|
||||||
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
||||||
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
||||||
const r = enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
const r = enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
||||||
json(res, r);
|
const budget = AI_JOBS.has(type) ? budgetState(db) : null;
|
||||||
|
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
||||||
};
|
};
|
||||||
|
|
||||||
router.post('/api/projects/:id/analyze', jobRoute('analyze'));
|
router.post('/api/projects/:id/analyze', jobRoute('analyze'));
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ import { Worker } from './services/jobs.js';
|
||||||
import { makeHandlers } from './handlers.js';
|
import { makeHandlers } from './handlers.js';
|
||||||
import { Scheduler } from './services/scheduler.js';
|
import { Scheduler } from './services/scheduler.js';
|
||||||
import { notify, notifyJob } from './services/notify.js';
|
import { notify, notifyJob } from './services/notify.js';
|
||||||
|
import { budgetState, AI_JOBS } from './services/budget.js';
|
||||||
import { layout } from './views.js';
|
import { layout } from './views.js';
|
||||||
|
|
||||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
@ -74,6 +75,12 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create
|
||||||
w = new Worker(db, makeHandlers(app), {
|
w = new Worker(db, makeHandlers(app), {
|
||||||
thermalMax: cfg.thermalMax,
|
thermalMax: cfg.thermalMax,
|
||||||
onFinish: (job, r) => notifyJob(app, job, r),
|
onFinish: (job, r) => notifyJob(app, job, r),
|
||||||
|
budget: () => budgetState(db),
|
||||||
|
isAiJob: (type) => AI_JOBS.has(type),
|
||||||
|
onBudget: (reason) => notify(app, 'budget', {
|
||||||
|
title: 'Budget IA atteint', level: 'warn',
|
||||||
|
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
||||||
|
}),
|
||||||
onThermal: (t) => notify(app, 'thermal', {
|
onThermal: (t) => notify(app, 'thermal', {
|
||||||
title: 'Pause thermique', level: 'warn',
|
title: 'Pause thermique', level: 'warn',
|
||||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
||||||
|
|
|
||||||
29
src/services/budget.js
Normal file
29
src/services/budget.js
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
// Budget IA : plafonds glissants 24 h / 30 j, en équivalent $ API remonté par Claude Code.
|
||||||
|
// Avec un abonnement Pro rien n'est facturé en plus : c'est un garde-fou pour ne pas épuiser le quota.
|
||||||
|
import { getSetting, now } from '../db.js';
|
||||||
|
|
||||||
|
// Jobs qui appellent Claude (les envois et relances n'en consomment pas)
|
||||||
|
export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_template', 'evolution']);
|
||||||
|
|
||||||
|
const usd = (n) => `${n.toFixed(2)} $`;
|
||||||
|
|
||||||
|
// La dépense compte au moment où le job s'est terminé (un job de nuit compte la nuit)
|
||||||
|
function spentSince(db, since) {
|
||||||
|
return db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(since).c;
|
||||||
|
}
|
||||||
|
|
||||||
|
function limit(db, key) {
|
||||||
|
const v = Number(getSetting(db, key, ''));
|
||||||
|
return Number.isFinite(v) && v > 0 ? v : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {{day: {used:number, limit:number|null}, month: {used:number, limit:number|null}, blocked: boolean, reason: string|null}} */
|
||||||
|
export function budgetState(db, { at = now() } = {}) {
|
||||||
|
const day = { used: spentSince(db, at - 86400), limit: limit(db, 'budget_day_usd') };
|
||||||
|
const month = { used: spentSince(db, at - 30 * 86400), limit: limit(db, 'budget_month_usd') };
|
||||||
|
const over = (x) => x.limit != null && x.used >= x.limit;
|
||||||
|
const reason = over(day) ? `budget IA des dernières 24 h atteint (${usd(day.used)} / ${usd(day.limit)})`
|
||||||
|
: over(month) ? `budget IA des 30 derniers jours atteint (${usd(month.used)} / ${usd(month.limit)})`
|
||||||
|
: null;
|
||||||
|
return { day, month, blocked: !!reason, reason };
|
||||||
|
}
|
||||||
|
|
@ -39,8 +39,12 @@ export function latestJobs(db, projectId) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Worker {
|
export class Worker {
|
||||||
constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal } = {}) {
|
constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal, budget, isAiJob, onBudget } = {}) {
|
||||||
this.clock = clock;
|
this.clock = clock;
|
||||||
|
this.budget = budget; // () => {blocked, reason}
|
||||||
|
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget atteint
|
||||||
|
this.onBudget = onBudget; // (reason) → une notif quand le blocage commence
|
||||||
|
this.budgetBlocked = false;
|
||||||
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
||||||
this.onThermal = onThermal; // (°C) → une fois par pause
|
this.onThermal = onThermal; // (°C) → une fois par pause
|
||||||
this.db = db;
|
this.db = db;
|
||||||
|
|
@ -78,8 +82,26 @@ export class Worker {
|
||||||
}
|
}
|
||||||
|
|
||||||
async tick() {
|
async tick() {
|
||||||
const job = this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
const due = this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
||||||
AND (run_after IS NULL OR run_after <= ?) ORDER BY id LIMIT 1`).get(this.clock());
|
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
||||||
|
if (!due.length) return false;
|
||||||
|
|
||||||
|
// Budget atteint : les jobs IA restent en file (pas perdus), les autres passent devant
|
||||||
|
const budget = this.budget?.() || { blocked: false };
|
||||||
|
let job = null;
|
||||||
|
let waiting = false;
|
||||||
|
for (const j of due) {
|
||||||
|
if (budget.blocked && this.isAiJob?.(j.type)) {
|
||||||
|
waiting = true;
|
||||||
|
const msg = JSON.stringify({ message: `En attente : ${budget.reason}` });
|
||||||
|
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
job = j;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
||||||
|
this.budgetBlocked = waiting;
|
||||||
if (!job) return false;
|
if (!job) return false;
|
||||||
const handler = this.handlers[job.type];
|
const handler = this.handlers[job.type];
|
||||||
if (!handler) {
|
if (!handler) {
|
||||||
|
|
@ -138,10 +160,11 @@ export function addUsage(ctx, r) {
|
||||||
ctx.usage.tokensOut += r.tokensOut || 0;
|
ctx.usage.tokensOut += r.tokensOut || 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Conso des 30 derniers jours, pour la jauge
|
// Conso des 30 derniers jours, pour la jauge (comptée à la fin du job, comme le budget)
|
||||||
export function usageSummary(db) {
|
export function usageSummary(db) {
|
||||||
const since = now() - 30 * 86400;
|
const since = now() - 30 * 86400;
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const q = (s) => db.prepare('SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n FROM jobs WHERE created_at > ?').get(s);
|
const q = (s) => db.prepare(`SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n
|
||||||
|
FROM jobs WHERE COALESCE(finished_at, created_at) > ?`).get(s);
|
||||||
return { month: q(since), day: q(day) };
|
return { month: q(since), day: q(day) };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -266,6 +266,13 @@ ${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
||||||
<label>Délai min entre 2 mails (s)<input name="send_delay_min" type="number" min="5" value="${esc(s.send_delay_min)}"></label>
|
<label>Délai min entre 2 mails (s)<input name="send_delay_min" type="number" min="5" value="${esc(s.send_delay_min)}"></label>
|
||||||
<label>Délai max (s)<input name="send_delay_max" type="number" min="5" value="${esc(s.send_delay_max)}"></label>
|
<label>Délai max (s)<input name="send_delay_max" type="number" min="5" value="${esc(s.send_delay_max)}"></label>
|
||||||
</div>
|
</div>
|
||||||
|
<h4>Budget IA</h4>
|
||||||
|
<p class="muted small">En équivalent $ API remonté par Claude Code (ton abonnement Pro ne facture rien en plus : c'est un garde-fou pour ton quota).
|
||||||
|
Au-delà, les jobs IA attendent sans être perdus ; envois et relances continuent. Vide = pas de limite.</p>
|
||||||
|
<div class="grid2">
|
||||||
|
<label>Plafond sur 24 h glissantes ($)<input name="budget_day_usd" inputmode="decimal" value="${esc(s.budget_day_usd)}" placeholder="ex. 2"></label>
|
||||||
|
<label>Plafond sur 30 jours glissants ($)<input name="budget_month_usd" inputmode="decimal" value="${esc(s.budget_month_usd)}" placeholder="ex. 30"></label>
|
||||||
|
</div>
|
||||||
<label>Modèle pour la prospection<select name="prospect_model">
|
<label>Modèle pour la prospection<select name="prospect_model">
|
||||||
<option value="haiku" ${s.prospect_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
<option value="haiku" ${s.prospect_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
||||||
<option value="sonnet" ${s.prospect_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
<option value="sonnet" ${s.prospect_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
||||||
|
|
|
||||||
75
test/budget.test.js
Normal file
75
test/budget.test.js
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { openDb, now, setSetting } from '../src/db.js';
|
||||||
|
import { budgetState, AI_JOBS } from '../src/services/budget.js';
|
||||||
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
|
function setup() {
|
||||||
|
const db = openDb(':memory:');
|
||||||
|
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
||||||
|
const spend = (usd, finishedAgo) => db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(1, 'prospect', 'done', ?, ?, ?)")
|
||||||
|
.run(usd, now() - finishedAgo - 60, now() - finishedAgo);
|
||||||
|
return { db, spend };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', () => {
|
||||||
|
const s = setup();
|
||||||
|
s.spend(1.5, 3600); // il y a 1 h
|
||||||
|
s.spend(10, 5 * 86400); // il y a 5 jours
|
||||||
|
s.spend(99, 40 * 86400); // hors fenêtre
|
||||||
|
let b = budgetState(s.db);
|
||||||
|
assert.equal(b.blocked, false);
|
||||||
|
assert.equal(b.day.used, 1.5);
|
||||||
|
assert.equal(b.month.used, 11.5);
|
||||||
|
|
||||||
|
setSetting(s.db, 'budget_day_usd', '2');
|
||||||
|
assert.equal(budgetState(s.db).blocked, false);
|
||||||
|
setSetting(s.db, 'budget_day_usd', '1.5');
|
||||||
|
b = budgetState(s.db);
|
||||||
|
assert.equal(b.blocked, true);
|
||||||
|
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
||||||
|
|
||||||
|
setSetting(s.db, 'budget_day_usd', '');
|
||||||
|
setSetting(s.db, 'budget_month_usd', '10');
|
||||||
|
assert.match(budgetState(s.db).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
||||||
|
assert.equal(budgetState(s.db, { at: now() + 30 * 86400 }).blocked, false, 'la fenêtre glisse');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('les envois et relances ne consomment pas d\'IA', () => {
|
||||||
|
for (const t of ['send', 'followup']) assert.equal(AI_JOBS.has(t), false);
|
||||||
|
for (const t of ['analyze', 'prospect', 'template', 'followup_template', 'evolution']) assert.equal(AI_JOBS.has(t), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, une seule notif', async () => {
|
||||||
|
const s = setup();
|
||||||
|
s.spend(5, 600);
|
||||||
|
setSetting(s.db, 'budget_day_usd', '3');
|
||||||
|
const ran = [];
|
||||||
|
const alerts = [];
|
||||||
|
const h = (name) => async () => { ran.push(name); };
|
||||||
|
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, {
|
||||||
|
thermalMax: 999, log: { error() {} },
|
||||||
|
budget: () => budgetState(s.db), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
||||||
|
});
|
||||||
|
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||||
|
enqueue(s.db, { projectId: 1, type: 'send' });
|
||||||
|
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
||||||
|
|
||||||
|
assert.equal(await w.tick(), true);
|
||||||
|
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
||||||
|
assert.equal(await w.tick(), false);
|
||||||
|
assert.equal(await w.tick(), false);
|
||||||
|
assert.equal(alerts.length, 1, 'une seule notif, pas une toutes les 3 s');
|
||||||
|
const jobs = latestJobs(s.db, 1);
|
||||||
|
assert.equal(jobs.prospect.status, 'queued');
|
||||||
|
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
||||||
|
|
||||||
|
setSetting(s.db, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
||||||
|
await w.tick(); await w.tick();
|
||||||
|
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
||||||
|
|
||||||
|
setSetting(s.db, 'budget_day_usd', '1');
|
||||||
|
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||||
|
await w.tick();
|
||||||
|
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
||||||
|
});
|
||||||
|
|
@ -192,3 +192,20 @@ test('réglages Discord : URL validée, chiffrée, événements enregistrés', a
|
||||||
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
||||||
assert.equal(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value, null);
|
assert.equal(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('budget : réglages, jauge et avertissement au lancement', async () => {
|
||||||
|
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
||||||
|
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
||||||
|
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
||||||
|
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
||||||
|
app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
||||||
|
const sys = await (await get('/api/system')).json();
|
||||||
|
assert.equal(sys.budget.blocked, true);
|
||||||
|
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
||||||
|
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
||||||
|
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
||||||
|
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
|
||||||
|
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue