feat: show Claude Pro quota usage (session + week) in the system bar
La CLI remonte un `rate_limit_event` à chaque appel (session glissante de 5 h et semaine glissante de 7 j, en % d'utilisation). C'était ignoré jusqu'ici. On le capture dans runClaude(), on le persiste en réglage après chaque appel, et la barre système l'affiche à côté du budget IA en $ — pour juger en amont si une tâche vaut le coup avant de taper dans un quota Pro limité à la semaine. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
69045dd196
commit
e17cf9bb08
8 changed files with 80 additions and 8 deletions
|
|
@ -44,6 +44,23 @@
|
||||||
return `<span class="${r >= 1 ? 'error' : r >= 0.8 ? 'warn' : ''}" title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used} / ${x.limit} $</span>`;
|
return `<span class="${r >= 1 ? 'error' : r >= 0.8 ? 'warn' : ''}" title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used} / ${x.limit} $</span>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Quota du compte Claude Pro lui-même (session glissante de 5 h + semaine glissante de 7 j),
|
||||||
|
// remonté par la CLI à chaque appel. Permet de décider en amont si une tâche vaut le coup.
|
||||||
|
function resetLabel(ts) {
|
||||||
|
if (!ts) return '';
|
||||||
|
return new Date(ts * 1000).toLocaleString('fr-FR', { weekday: 'short', hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Paris' });
|
||||||
|
}
|
||||||
|
function claudeBit(label, w) {
|
||||||
|
if (!w) return '';
|
||||||
|
const cls = w.utilization >= 1 ? 'error' : w.utilization >= 0.8 ? 'warn' : '';
|
||||||
|
const reset = resetLabel(w.resetsAt);
|
||||||
|
return `<span class="${cls}"${reset ? ` title="Réinitialisation ${esc(reset)}"` : ''}>Claude ${label} : ${pct(w.utilization)}</span>`;
|
||||||
|
}
|
||||||
|
function claudeQuota(rl) {
|
||||||
|
if (!rl) return '<span class="muted" title="Mesuré après le premier job IA">Claude : pas encore mesuré</span>';
|
||||||
|
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshSys() {
|
async function refreshSys() {
|
||||||
const el = $('#sys');
|
const el = $('#sys');
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
@ -51,6 +68,7 @@
|
||||||
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>` : ''}
|
||||||
|
${claudeQuota(s.claudeRateLimit)}
|
||||||
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
${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.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)` : ''}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
// Handlers des jobs en arrière-plan.
|
// Handlers des jobs en arrière-plan.
|
||||||
import { now, getSetting } from './db.js';
|
import { now, getSetting, setSetting } from './db.js';
|
||||||
import { runClaude, extractJson } from './services/claude.js';
|
import { runClaude, extractJson, rateLimitWindows } from './services/claude.js';
|
||||||
import { addUsage } from './services/jobs.js';
|
import { addUsage } from './services/jobs.js';
|
||||||
import { syncRepo } from './services/git.js';
|
import { syncRepo } from './services/git.js';
|
||||||
import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js';
|
import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js';
|
||||||
|
|
@ -38,7 +38,13 @@ export function parseProspectLine(line) {
|
||||||
|
|
||||||
export function makeHandlers(app) {
|
export function makeHandlers(app) {
|
||||||
const { db, cfg } = app;
|
const { db, cfg } = app;
|
||||||
const claude = (o) => runClaude({ bin: cfg.claudeBin, ...o });
|
const claude = async (o) => {
|
||||||
|
const r = await runClaude({ bin: cfg.claudeBin, ...o });
|
||||||
|
// État du quota Pro (session 5h + semaine), affiché dans la barre système
|
||||||
|
const w = rateLimitWindows(r.rateLimit);
|
||||||
|
if (w) setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
|
||||||
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -135,7 +135,11 @@ 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), budget: budgetState(db), thermalMax: cfg.thermalMax });
|
const rlRaw = getSetting(db, 'claude_rate_limit_json');
|
||||||
|
json(res, {
|
||||||
|
temp: cpuTemp(), queue, scheduled, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax,
|
||||||
|
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects', async ({ req, res }) => {
|
router.post('/api/projects', async ({ req, res }) => {
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,7 @@ export function runClaude(o) {
|
||||||
let buf = '';
|
let buf = '';
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
let result = null;
|
let result = null;
|
||||||
|
let rateLimit = null;
|
||||||
const texts = [];
|
const texts = [];
|
||||||
|
|
||||||
const timer = setTimeout(() => child.kill('SIGTERM'), o.timeoutMs || 30 * 60_000);
|
const timer = setTimeout(() => child.kill('SIGTERM'), o.timeoutMs || 30 * 60_000);
|
||||||
|
|
@ -62,6 +63,9 @@ export function runClaude(o) {
|
||||||
}
|
}
|
||||||
} else if (ev.type === 'result') {
|
} else if (ev.type === 'result') {
|
||||||
result = ev;
|
result = ev;
|
||||||
|
} else if (ev.type === 'rate_limit_event' && ev.rate_limit_info) {
|
||||||
|
// Dernier reçu = état le plus à jour (session 5h + semaine), remonté à chaque appel
|
||||||
|
rateLimit = ev.rate_limit_info;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -80,11 +84,24 @@ export function runClaude(o) {
|
||||||
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
|
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
|
||||||
tokensOut: usage.output_tokens || 0,
|
tokensOut: usage.output_tokens || 0,
|
||||||
turns: result.num_turns,
|
turns: result.num_turns,
|
||||||
|
rateLimit,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalise la session (5h glissantes) et la semaine (7j glissants) quel que soit le détail
|
||||||
|
// exact remonté par la CLI. Pour afficher où en est le quota Pro avant de lancer un job.
|
||||||
|
export function rateLimitWindows(info) {
|
||||||
|
if (!info) return null;
|
||||||
|
const w = info.unifiedWindows || {};
|
||||||
|
const pick = (k) => (w[k] && typeof w[k].utilization === 'number' ? { utilization: w[k].utilization, resetsAt: w[k].resetsAt ?? null } : null);
|
||||||
|
const fiveHour = pick('five_hour');
|
||||||
|
const sevenDay = pick('seven_day');
|
||||||
|
if (!fiveHour && !sevenDay) return null;
|
||||||
|
return { fiveHour, sevenDay };
|
||||||
|
}
|
||||||
|
|
||||||
// Extrait le premier objet JSON d'une réponse (Claude entoure parfois de ```json)
|
// Extrait le premier objet JSON d'une réponse (Claude entoure parfois de ```json)
|
||||||
export function extractJson(text) {
|
export function extractJson(text) {
|
||||||
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
|
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
|
||||||
|
|
|
||||||
5
test/fixtures/fake-claude.js
vendored
5
test/fixtures/fake-claude.js
vendored
|
|
@ -15,4 +15,9 @@ const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringi
|
||||||
'PROSPECT {"company":"Coiffure Zen","email":"Hello@Zen.fr","website":"https://zen.fr","city":"Vern","score":6,"source":"https://zen.fr"}']
|
'PROSPECT {"company":"Coiffure Zen","email":"Hello@Zen.fr","website":"https://zen.fr","city":"Vern","score":6,"source":"https://zen.fr"}']
|
||||||
: ['```json\n{"ok":true,"args":' + JSON.stringify(process.argv.slice(2)) + '}\n```'];
|
: ['```json\n{"ok":true,"args":' + JSON.stringify(process.argv.slice(2)) + '}\n```'];
|
||||||
for (const t of lines) out({ type: 'assistant', message: { content: [{ type: 'text', text: t }] } });
|
for (const t of lines) out({ type: 'assistant', message: { content: [{ type: 'text', text: t }] } });
|
||||||
|
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel
|
||||||
|
out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: {
|
||||||
|
five_hour: { utilization: 0.33, resetsAt: 1_700_000_000 },
|
||||||
|
seven_day: { utilization: 0.5, resetsAt: 1_700_300_000 },
|
||||||
|
} } });
|
||||||
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, setSetting, now } from '../src/db.js';
|
import { openDb, setSetting, getSetting, now } from '../src/db.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
||||||
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
||||||
|
|
@ -48,6 +48,9 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
assert.equal(p.target.zone, 'Bretagne');
|
assert.equal(p.target.zone, 'Bretagne');
|
||||||
assert.equal(p.targetValidated, false);
|
assert.equal(p.targetValidated, false);
|
||||||
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
||||||
|
const rl = JSON.parse(getSetting(s.db, 'claude_rate_limit_json'));
|
||||||
|
assert.equal(rl.fiveHour.utilization, 0.33, 'quota Claude (session) enregistré après l\'appel');
|
||||||
|
assert.equal(rl.sevenDay.utilization, 0.5, 'quota Claude (semaine) enregistré après l\'appel');
|
||||||
|
|
||||||
const refused = await run(s, 'prospect', { count: 3 });
|
const refused = await run(s, 'prospect', { count: 3 });
|
||||||
assert.match(refused.error, /Valide la cible/);
|
assert.match(refused.error, /Valide la cible/);
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { randomBytes } from 'node:crypto';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { openDb, now, setSetting } from '../src/db.js';
|
||||||
import { createApp } from '../src/server.js';
|
import { createApp } from '../src/server.js';
|
||||||
import { unsubToken } from '../src/crypto.js';
|
import { unsubToken } from '../src/crypto.js';
|
||||||
|
|
||||||
|
|
@ -202,8 +202,13 @@ test('budget : réglages, jauge et avertissement au lancement', async () => {
|
||||||
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
||||||
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
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());
|
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();
|
let sys = await (await get('/api/system')).json();
|
||||||
assert.equal(sys.budget.blocked, true);
|
assert.equal(sys.budget.blocked, true);
|
||||||
|
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
||||||
|
setSetting(app.db, 'claude_rate_limit_json', JSON.stringify({ at: now(), fiveHour: { utilization: 0.42, resetsAt: 123 }, sevenDay: { utilization: 0.1, resetsAt: 456 } }));
|
||||||
|
sys = await (await get('/api/system')).json();
|
||||||
|
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
||||||
|
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
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();
|
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' });
|
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { runClaude, extractJson } from '../src/services/claude.js';
|
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
||||||
import { waitCool } from '../src/services/thermal.js';
|
import { waitCool } from '../src/services/thermal.js';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { openDb, now } from '../src/db.js';
|
||||||
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
||||||
|
|
@ -20,12 +20,26 @@ test('runClaude parse le flux et la conso', async () => {
|
||||||
assert.ok(j.args.includes('Read,Grep'));
|
assert.ok(j.args.includes('Read,Grep'));
|
||||||
assert.ok(j.args.join(' ').includes('Bash,Edit,Write'));
|
assert.ok(j.args.join(' ').includes('Bash,Edit,Write'));
|
||||||
assert.equal(seen.length, 1);
|
assert.equal(seen.length, 1);
|
||||||
|
assert.deepEqual(r.rateLimit.unifiedWindows.five_hour, { utilization: 0.33, resetsAt: 1_700_000_000 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('runClaude remonte une erreur si le process meurt', async () => {
|
test('runClaude remonte une erreur si le process meurt', async () => {
|
||||||
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
|
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('rateLimitWindows normalise la session (5h) et la semaine, quel que soit le format reçu', () => {
|
||||||
|
assert.deepEqual(rateLimitWindows({ unifiedWindows: {
|
||||||
|
five_hour: { utilization: 0.1, resetsAt: 111 },
|
||||||
|
seven_day: { utilization: 0.2, resetsAt: 222 },
|
||||||
|
} }), { fiveHour: { utilization: 0.1, resetsAt: 111 }, sevenDay: { utilization: 0.2, resetsAt: 222 } });
|
||||||
|
// Une seule fenêtre présente : l'autre reste null plutôt que de tout rejeter
|
||||||
|
assert.deepEqual(rateLimitWindows({ unifiedWindows: { five_hour: { utilization: 0.4 } } }),
|
||||||
|
{ fiveHour: { utilization: 0.4, resetsAt: null }, sevenDay: null });
|
||||||
|
assert.equal(rateLimitWindows(null), null);
|
||||||
|
assert.equal(rateLimitWindows({}), null);
|
||||||
|
assert.equal(rateLimitWindows({ unifiedWindows: { five_hour: { utilization: 'beaucoup' } } }), null, 'valeur non numérique ignorée');
|
||||||
|
});
|
||||||
|
|
||||||
test('extractJson gère texte, fences et accolades dans les chaînes', () => {
|
test('extractJson gère texte, fences et accolades dans les chaînes', () => {
|
||||||
assert.deepEqual(extractJson('Voilà : {"a":"x}y","b":[1,{"c":2}]} fin'), { a: 'x}y', b: [1, { c: 2 }] });
|
assert.deepEqual(extractJson('Voilà : {"a":"x}y","b":[1,{"c":2}]} fin'), { a: 'x}y', b: [1, { c: 2 }] });
|
||||||
assert.deepEqual(extractJson('```json\n[1,2]\n```'), [1, 2]);
|
assert.deepEqual(extractJson('```json\n[1,2]\n```'), [1, 2]);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue