From 8d9a04937a024fcdf04a2183d5d1658ce65e2fb7 Mon Sep 17 00:00:00 2001 From: Tony Averty Date: Wed, 21 Oct 2026 15:36:11 +0200 Subject: [PATCH] feat: schedule heavy jobs for the night Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ --- public/app.css | 2 ++ public/app.js | 20 +++++++++++++--- src/db.js | 4 ++++ src/routes.js | 11 ++++++--- src/services/jobs.js | 14 ++++++----- src/services/paris-time.js | 48 ++++++++++++++++++++++++++++++++++++++ src/views.js | 2 ++ test/http.test.js | 13 +++++++++++ test/night.test.js | 43 ++++++++++++++++++++++++++++++++++ 9 files changed, 145 insertions(+), 12 deletions(-) create mode 100644 src/services/paris-time.js create mode 100644 test/night.test.js diff --git a/public/app.css b/public/app.css index f62cc2b..8fc0d94 100644 --- a/public/app.css +++ b/public/app.css @@ -100,3 +100,5 @@ form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lin .inbox { margin: 10px 0 4px; line-height: 1.9; } .inbox:empty { display: none; } .followup { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); } +.running.scheduled { background: transparent; border: 1px dashed var(--line); } +.moon { width: 18px; height: 18px; border-radius: 50%; box-shadow: inset -5px -3px 0 0 var(--accent); flex: none; transform: rotate(-20deg); } diff --git a/public/app.js b/public/app.js index a276677..8f6b453 100644 --- a/public/app.js +++ b/public/app.js @@ -44,7 +44,8 @@ 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)} - ${s.queue ? `${s.queue} job(s)` : ''}`; + ${s.queue ? `${s.queue} job(s)` : ''} + ${s.scheduled ? `${s.scheduled} programmé(s) cette nuit` : ''}`; } catch { /* silencieux */ } } refreshSys(); @@ -55,6 +56,13 @@ if (!box) return; if (!job) { box.innerHTML = ''; return; } const p = job.progress || {}; + if (job.status === 'queued' && job.runAfter && job.runAfter * 1000 > Date.now()) { + const at = new Date(job.runAfter * 1000).toLocaleString('fr-FR', { weekday: 'long', hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Paris' }); + box.innerHTML = `
+
${LABELS[type]} programmé(e) : ${esc(at)}
Le Pi est au frais et ton quota Claude est libre.
+
`; + return; + } if (ACTIVE.includes(job.status)) { const extra = type === 'prospect' && p.found !== undefined ? `${p.found} prospect(s) trouvé(s) sur ${p.target}` : ''; @@ -247,10 +255,16 @@ break; } case 'target': await api(`/api/projects/${id}/target`, data); toast('Cible validée'); setTimeout(() => location.reload(), 500); break; - case 'prospect': await api(`/api/projects/${id}/prospect`, data); toast('Recherche lancée en arrière-plan'); 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'); + break; + } case 'evolution': { if (data.level === 'approfondi' && !confirm('Le niveau approfondi utilise Opus et consomme beaucoup de quota. Continuer ?')) break; - await api(`/api/projects/${id}/evolution`, data); toast('Recherche d\'évolutions lancée'); 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'); + break; } case 'template': { data.kind = form.dataset.kind; diff --git a/src/db.js b/src/db.js index 1230762..c8a0c71 100644 --- a/src/db.js +++ b/src/db.js @@ -101,6 +101,10 @@ export const MIGRATIONS = [ ALTER TABLE projects ADD COLUMN followup_enabled INTEGER NOT NULL DEFAULT 0; ALTER TABLE projects ADD COLUMN followup_days INTEGER NOT NULL DEFAULT 7; `, + // 6 — jobs programmés (la nuit) + ` + ALTER TABLE jobs ADD COLUMN run_after INTEGER; -- ne pas démarrer avant (epoch s) + `, ]; export function openDb(dataDir) { diff --git a/src/routes.js b/src/routes.js index b6d2762..e959285 100644 --- a/src/routes.js +++ b/src/routes.js @@ -10,6 +10,7 @@ import { allowedToSend, EMAIL_RE } from './services/mailer.js'; import { cpuTemp } from './services/thermal.js'; import { checkInbox } from './services/inbox.js'; import { followupPlan } from './services/followup.js'; +import { nextNightSlot } from './services/paris-time.js'; import { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, @@ -94,8 +95,10 @@ export function registerRoutes(router, app) { // ---------- API JSON ---------- router.get('/api/system', ({ res }) => { - const queue = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get().n; - json(res, { temp: cpuTemp(), queue, usage: usageSummary(db), thermalMax: cfg.thermalMax }); + 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 }); }); router.post('/api/projects', async ({ req, res }) => { @@ -161,7 +164,9 @@ export function registerRoutes(router, app) { const p = getProject(app, pid(params)); const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {}; guard(p, b); - const r = enqueue(db, { projectId: p.id, type, params: paramsOf(b) }); + // "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); }; diff --git a/src/services/jobs.js b/src/services/jobs.js index b0b092b..da4adcf 100644 --- a/src/services/jobs.js +++ b/src/services/jobs.js @@ -2,13 +2,13 @@ import { now } from '../db.js'; import { waitCool } from './thermal.js'; -export function enqueue(db, { projectId, type, params = {} }) { +export function enqueue(db, { projectId, type, params = {}, runAfter = null }) { const running = db.prepare( "SELECT id FROM jobs WHERE project_id IS ? AND type = ? AND status IN ('queued','running')" ).get(projectId ?? null, type); if (running) return { id: running.id, existing: true }; - const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at) VALUES(?, ?, ?, ?)') - .run(projectId ?? null, type, JSON.stringify(params), now()); + const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?)') + .run(projectId ?? null, type, JSON.stringify(params), now(), runAfter); return { id: Number(r.lastInsertRowid), existing: false }; } @@ -32,14 +32,15 @@ export function latestJobs(db, projectId) { id: r.id, status: r.status, error: r.error, progress: r.progress_json ? JSON.parse(r.progress_json) : null, result: r.result_json ? JSON.parse(r.result_json) : null, - createdAt: r.created_at, finishedAt: r.finished_at, + createdAt: r.created_at, finishedAt: r.finished_at, runAfter: r.run_after, }; } return out; } export class Worker { - constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console } = {}) { + constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now } = {}) { + this.clock = clock; this.db = db; this.handlers = handlers; this.thermalMax = thermalMax; @@ -69,7 +70,8 @@ export class Worker { } async tick() { - const job = this.db.prepare("SELECT * FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1").get(); + 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()); if (!job) return false; const handler = this.handlers[job.type]; if (!handler) { diff --git a/src/services/paris-time.js b/src/services/paris-time.js new file mode 100644 index 0000000..44f2e8b --- /dev/null +++ b/src/services/paris-time.js @@ -0,0 +1,48 @@ +// Heures "murales" de Paris, changements d'heure compris. Aucune dépendance. +const TZ = 'Europe/Paris'; + +const partsFmt = new Intl.DateTimeFormat('en-GB', { + timeZone: TZ, year: 'numeric', month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', weekday: 'short', hourCycle: 'h23', +}); +const offsetFmt = new Intl.DateTimeFormat('en-US', { timeZone: TZ, timeZoneName: 'shortOffset' }); + +/** @returns {{year:number, month:number, day:number, hour:number, minute:number, weekday:string}} */ +export function parisParts(date = new Date()) { + const p = Object.fromEntries(partsFmt.formatToParts(date).map((x) => [x.type, x.value])); + return { year: +p.year, month: +p.month, day: +p.day, hour: +p.hour % 24, minute: +p.minute, weekday: p.weekday }; +} + +// Décalage de Paris par rapport à UTC à un instant donné, en minutes (+60 l'hiver, +120 l'été) +function offsetMinutes(date) { + const name = offsetFmt.formatToParts(date).find((x) => x.type === 'timeZoneName')?.value || 'GMT'; + const m = /GMT([+-])(\d{1,2})(?::(\d{2}))?/.exec(name); + return m ? (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3] || 0)) : 0; +} + +/** Heure murale à Paris → instant. */ +export function parisTime(year, month, day, hour, minute = 0) { + const guess = Date.UTC(year, month - 1, day, hour, minute); + let t = guess - offsetMinutes(new Date(guess)) * 60_000; + t = guess - offsetMinutes(new Date(t)) * 60_000; // 2e passe : correct autour du changement d'heure + return new Date(t); +} + +/** Même heure murale, N jours plus tard. */ +export function addParisDays(date, days) { + const p = parisParts(date); + const noon = parisTime(p.year, p.month, p.day, 12); + const q = parisParts(new Date(noon.getTime() + days * 86_400_000)); + return { year: q.year, month: q.month, day: q.day }; +} + +// Créneau de nuit : le Pi est au frais et le quota Claude n'est pas utilisé par toi +export const NIGHT = { start: 1, end: 6 }; + +/** Prochain début de créneau de nuit (ou maintenant si on y est déjà). */ +export function nextNightSlot(date = new Date()) { + const p = parisParts(date); + if (p.hour >= NIGHT.start && p.hour < NIGHT.end) return date; + const d = p.hour < NIGHT.start ? p : addParisDays(date, 1); + return parisTime(d.year, d.month, d.day, NIGHT.start); +} diff --git a/src/views.js b/src/views.js index 2b5665e..e8d551d 100644 --- a/src/views.js +++ b/src/views.js @@ -151,6 +151,7 @@ function projectItem(p, smtp, dbCfg, imap) {