diff --git a/public/app.js b/public/app.js index 41f89ff..378a226 100644 --- a/public/app.js +++ b/public/app.js @@ -36,6 +36,14 @@ }; // ---------- 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 `IA ${label} : ${used}`; + const r = x.used / x.limit; + return `IA ${label} : ${used} / ${x.limit} $`; + } + async function refreshSys() { const el = $('#sys'); if (!el) return; @@ -43,7 +51,8 @@ const s = await api('/api/system'); const hot = s.temp !== null && s.temp >= s.thermalMax - 5; el.innerHTML = `${s.temp !== null ? `${s.temp} °C` : ''} - IA 24 h : $${s.usage.day.cost.toFixed(2)} · 30 j : $${s.usage.month.cost.toFixed(2)} + ${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)} + ${s.budget.blocked ? 'Budget IA atteint : jobs IA en attente' : ''} ${s.queue ? `${s.queue} job(s)` : ''} ${s.scheduled ? `${s.scheduled} programmé(s) cette nuit` : ''}`; } catch { /* silencieux */ } @@ -67,7 +76,7 @@ const extra = type === 'prospect' && p.found !== undefined ? `${p.found} prospect(s) trouvé(s) sur ${p.target}` : ''; box.innerHTML = `
-
${esc(job.status === 'queued' ? 'En file d\'attente…' : p.message || 'En cours…')}
${extra ? `
${extra}
` : ''}
+
${esc(p.message || (job.status === 'queued' ? 'En file d\'attente…' : 'En cours…'))}
${extra ? `
${extra}
` : ''}
`; } else if (job.status === 'error') { box.innerHTML = `

${LABELS[type]} en échec : ${esc(job.error)}

`; @@ -263,13 +272,13 @@ case 'target': await api(`/api/projects/${id}/target`, data); toast('Cible validée'); setTimeout(() => location.reload(), 500); break; case 'prospect': { 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; } case 'evolution': { 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); - 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; } case 'template': { diff --git a/src/routes.js b/src/routes.js index 5dfe8f7..8c07c3b 100644 --- a/src/routes.js +++ b/src/routes.js @@ -12,6 +12,7 @@ import { checkInbox } from './services/inbox.js'; import { followupPlan } from './services/followup.js'; import { nextNightSlot } from './services/paris-time.js'; import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js'; +import { budgetState, AI_JOBS } from './services/budget.js'; import { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, @@ -70,6 +71,8 @@ export function registerRoutes(router, app) { send_delay_max: getSetting(db, 'send_delay_max', '60'), prospect_model: getSetting(db, 'prospect_model', 'haiku'), 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 }, }; 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_max', String(dmax)); 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(); 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' 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; - 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 }) => { @@ -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) const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null; 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')); diff --git a/src/server.js b/src/server.js index 8993e20..b735733 100644 --- a/src/server.js +++ b/src/server.js @@ -11,6 +11,7 @@ import { Worker } from './services/jobs.js'; import { makeHandlers } from './handlers.js'; import { Scheduler } from './services/scheduler.js'; import { notify, notifyJob } from './services/notify.js'; +import { budgetState, AI_JOBS } from './services/budget.js'; import { layout } from './views.js'; 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), { thermalMax: cfg.thermalMax, 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', { title: 'Pause thermique', level: 'warn', description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`, diff --git a/src/services/budget.js b/src/services/budget.js new file mode 100644 index 0000000..08a04ce --- /dev/null +++ b/src/services/budget.js @@ -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 }; +} diff --git a/src/services/jobs.js b/src/services/jobs.js index addb748..d77e780 100644 --- a/src/services/jobs.js +++ b/src/services/jobs.js @@ -39,8 +39,12 @@ export function latestJobs(db, projectId) { } 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.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.onThermal = onThermal; // (°C) → une fois par pause this.db = db; @@ -78,8 +82,26 @@ export class Worker { } async tick() { - const job = 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()); + const due = this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued' + 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; const handler = this.handlers[job.type]; if (!handler) { @@ -138,10 +160,11 @@ export function addUsage(ctx, r) { 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) { const since = now() - 30 * 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) }; } diff --git a/src/views.js b/src/views.js index 0273e9a..7641e2b 100644 --- a/src/views.js +++ b/src/views.js @@ -266,6 +266,13 @@ ${saved ? '

Enregistré.

' : ''} +

Budget IA

+

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.

+
+ + +