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) {
@@ -190,6 +191,7 @@ function projectItem(p, smtp, dbCfg, imap) {
+
diff --git a/test/http.test.js b/test/http.test.js
index 180dc6e..b37f721 100644
--- a/test/http.test.js
+++ b/test/http.test.js
@@ -161,3 +161,16 @@ test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressa
assert.equal(r.status, 200, 'on peut ressaisir');
} finally { console.warn = warn; }
});
+
+test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => {
+ 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();
+ const r = await post(`/api/projects/${id}/evolution`, { count: 3, level: 'rapide', when: 'night' });
+ assert.equal(r.status, 200);
+ const job = app.db.prepare("SELECT run_after FROM jobs WHERE type = 'evolution' ORDER BY id DESC LIMIT 1").get();
+ const { parisParts } = await import('../src/services/paris-time.js');
+ const p = parisParts(new Date(job.run_after * 1000));
+ assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
+ const sys = await (await get('/api/system')).json();
+ assert.ok(job.run_after > now() ? sys.scheduled >= 1 : true);
+});
diff --git a/test/night.test.js b/test/night.test.js
new file mode 100644
index 0000000..07ac142
--- /dev/null
+++ b/test/night.test.js
@@ -0,0 +1,43 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
+import { openDb, now } from '../src/db.js';
+import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
+
+const iso = (d) => d.toISOString();
+
+test('parisParts / parisTime : aller-retour, été comme hiver', () => {
+ assert.deepEqual(parisParts(new Date('2026-10-21T13:34:00Z')), { year: 2026, month: 10, day: 21, hour: 15, minute: 34, weekday: 'Wed' });
+ assert.equal(iso(parisTime(2026, 7, 14, 9)), '2026-07-14T07:00:00.000Z', 'été : UTC+2');
+ assert.equal(iso(parisTime(2026, 12, 25, 9)), '2026-12-25T08:00:00.000Z', 'hiver : UTC+1');
+ assert.deepEqual(addParisDays(new Date('2026-12-31T22:00:00Z'), 1), { year: 2027, month: 1, day: 1 }, 'passage d\'année');
+});
+
+test('prochain créneau de nuit (1h-6h Paris)', () => {
+ const at = (s) => iso(nextNightSlot(new Date(s)));
+ assert.equal(at('2026-10-21T15:30:00+02:00'), '2026-10-21T23:00:00.000Z', 'après-midi → 1h le lendemain');
+ assert.equal(at('2026-10-22T00:30:00+02:00'), '2026-10-21T23:00:00.000Z', '0h30 → 1h le même jour');
+ assert.equal(at('2026-10-22T03:00:00+02:00'), '2026-10-22T01:00:00.000Z', 'déjà dans le créneau → tout de suite');
+ assert.equal(at('2026-10-22T06:00:00+02:00'), '2026-10-22T23:00:00.000Z', '6h pile → nuit suivante');
+ assert.equal(at('2026-10-24T22:00:00+02:00'), '2026-10-24T23:00:00.000Z', 'nuit du passage à l\'heure d\'hiver');
+ assert.equal(at('2027-03-27T20:00:00+01:00'), '2027-03-28T00:00:00.000Z', 'nuit du passage à l\'heure d\'été');
+ assert.equal(at('2026-12-31T23:59:00+01:00'), '2027-01-01T00:00:00.000Z', 'Saint-Sylvestre');
+});
+
+test('le worker ne démarre pas un job programmé avant son heure', async () => {
+ const db = openDb(':memory:');
+ let clock = now();
+ const ran = [];
+ const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
+ { thermalMax: 999, log: { error() {} }, clock: () => clock });
+ db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
+ enqueue(db, { projectId: 1, type: 'prospect', runAfter: clock + 3600 });
+ enqueue(db, { projectId: 1, type: 'evolution' });
+ assert.equal(await w.tick(), true);
+ assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
+ assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
+ assert.equal(latestJobs(db, 1).prospect.runAfter, clock + 3600);
+ clock += 3601;
+ assert.equal(await w.tick(), true);
+ assert.deepEqual(ran, ['evolution', 'prospect']);
+});