feat(p10): archivage automatique des sessions terminées (rétention configurable)
- DB: migration #10 (sessions.archived_at + index), helpers archive/unarchive/archiveExpired (soft-archive, jamais de DELETE) - core/retention-settings.ts: session_retention_days (défaut 30, 0=jamais, 1-3650) + session_purge_days (off) - core/session-archive.ts: scheduler start/stop/sweep (calqué DiscoveryService), câblé dans runDaemon - pty-manager.list({includeArchived}) + SessionSummary.archived + emitHistoricalUpdate - routes: GET /sessions?includeArchived, POST/DELETE /sessions/:id/archive, POST /sessions/archive-now - protocole additif: message WS session_archived (relayé par la gateway, abonnés 'sessions') - settings: retentionDays/purgeDays exposés et validés dans PATCH /settings - web: store sessions (showArchived + archive/unarchive), SessionsListView (toggle/badge/actions), SettingsView (slider rétention), i18n EN+FR - tests: retention-settings + session-archive (vitest) + settings-routes étendu ; acceptance-p10.mjs (sweep, event WS, resume d'une session archivée → 201, rétention=0)
This commit is contained in:
@@ -23,6 +23,25 @@ const NOTIFY_DEBOUNCE_MS = 1500;
|
||||
const CLAUDE_ID_POLL_MS = 400;
|
||||
const CLAUDE_ID_TIMEOUT_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Ligne `sessions` telle que lue pour construire un SessionSummary historique (session terminée).
|
||||
* `type` (et non `interface`) pour que TS infère l'index signature implicite → cast direct depuis
|
||||
* le `Record<string, SQLOutputValue>` de node:sqlite.
|
||||
*/
|
||||
type HistoricalRow = {
|
||||
id: string;
|
||||
cwd: string;
|
||||
command: string;
|
||||
title: string | null;
|
||||
created_at: string;
|
||||
ended_at: string | null;
|
||||
exit_code: number | null;
|
||||
claude_session_id: string | null;
|
||||
added_dirs: string | null;
|
||||
group_id: string | null;
|
||||
archived_at: string | null;
|
||||
};
|
||||
|
||||
/** Parse la colonne `added_dirs` (JSON array de chemins) de façon défensive ; [] si NULL/invalide. */
|
||||
function parseAddedDirs(raw: string | null): string[] {
|
||||
if (!raw) return [];
|
||||
@@ -246,41 +265,61 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
return set;
|
||||
}
|
||||
|
||||
list(): SessionSummary[] {
|
||||
list(opts?: { includeArchived?: boolean }): SessionSummary[] {
|
||||
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
|
||||
const liveIds = new Set(this.live.keys());
|
||||
const rows = this.db
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id FROM sessions ORDER BY created_at DESC LIMIT 100')
|
||||
.all() as Array<{ id: string; cwd: string; command: string; title: string | null; created_at: string; ended_at: string | null; exit_code: number | null; claude_session_id: string | null; added_dirs: string | null; group_id: string | null }>;
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at FROM sessions ORDER BY created_at DESC LIMIT 100')
|
||||
.all() as HistoricalRow[];
|
||||
const historical: SessionSummary[] = rows
|
||||
.filter((r) => !liveIds.has(r.id))
|
||||
.map((r) => {
|
||||
const addedDirs = parseAddedDirs(r.added_dirs);
|
||||
return {
|
||||
id: r.id,
|
||||
cwd: r.cwd,
|
||||
command: r.command,
|
||||
title: r.title,
|
||||
status: 'exited' as const,
|
||||
live: false,
|
||||
createdAt: r.created_at,
|
||||
endedAt: r.ended_at,
|
||||
exitCode: r.exit_code,
|
||||
clients: 0,
|
||||
source: 'managed' as const,
|
||||
claudeSessionId: r.claude_session_id,
|
||||
pid: null,
|
||||
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
||||
resumable: r.command === 'claude' && r.claude_session_id != null,
|
||||
attachable: false,
|
||||
registryStatus: null,
|
||||
...(addedDirs.length ? { addedDirs } : {}),
|
||||
groupId: r.group_id,
|
||||
};
|
||||
});
|
||||
// Sessions auto-archivées exclues par défaut (filtre indépendant et cumulable avec hidden).
|
||||
.filter((r) => (opts?.includeArchived ? true : r.archived_at == null))
|
||||
.map((r) => this.historicalSummary(r));
|
||||
return [...liveSummaries, ...historical];
|
||||
}
|
||||
|
||||
/** Construit le SessionSummary d'une ligne historique (session managée terminée). */
|
||||
private historicalSummary(r: HistoricalRow): SessionSummary {
|
||||
const addedDirs = parseAddedDirs(r.added_dirs);
|
||||
return {
|
||||
id: r.id,
|
||||
cwd: r.cwd,
|
||||
command: r.command,
|
||||
title: r.title,
|
||||
status: 'exited' as const,
|
||||
live: false,
|
||||
createdAt: r.created_at,
|
||||
endedAt: r.ended_at,
|
||||
exitCode: r.exit_code,
|
||||
clients: 0,
|
||||
source: 'managed' as const,
|
||||
claudeSessionId: r.claude_session_id,
|
||||
pid: null,
|
||||
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
||||
resumable: r.command === 'claude' && r.claude_session_id != null,
|
||||
attachable: false,
|
||||
registryStatus: null,
|
||||
...(addedDirs.length ? { addedDirs } : {}),
|
||||
groupId: r.group_id,
|
||||
archived: r.archived_at != null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ré-émet un `session_update` pour une session historique (P10) — utilisé au dés-archivage pour
|
||||
* que tous les clients rafraîchissent le row (le champ `archived` repasse à false). No-op si la
|
||||
* session est vivante (déjà couverte par le flux live) ou inconnue.
|
||||
*/
|
||||
emitHistoricalUpdate(id: string): void {
|
||||
if (this.live.has(id)) return;
|
||||
const r = this.db
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at FROM sessions WHERE id = ?')
|
||||
.get(id) as HistoricalRow | undefined;
|
||||
if (!r) return;
|
||||
this.emit('session_update', this.historicalSummary(r));
|
||||
}
|
||||
|
||||
get(id: string): SessionSummary | null {
|
||||
const s = this.live.get(id);
|
||||
return s ? this.summarize(s) : null;
|
||||
|
||||
48
packages/server/src/core/retention-settings.ts
Normal file
48
packages/server/src/core/retention-settings.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
// Réglages de rétention des sessions terminées (archivage auto), persistés dans `settings`.
|
||||
// Frontière de sécurité : clés NON sensibles, n'entrent dans l'allow-list du PATCH /api/v1/settings
|
||||
// que via les validateurs ci-dessous. Calqué sur scan-settings.ts.
|
||||
import { getSetting } from '../db/index.js';
|
||||
import type { Db } from '../db/index.js';
|
||||
|
||||
export const RETENTION_DAYS_KEY = 'session_retention_days';
|
||||
export const PURGE_DAYS_KEY = 'session_purge_days';
|
||||
|
||||
/** Au-delà de N jours après la fin, une session managée est auto-archivée. 0 = jamais. */
|
||||
export const DEFAULT_RETENTION_DAYS = 30;
|
||||
/** Purge définitive (DELETE) après N jours. 0 = désactivée (conçue mais OFF par défaut). */
|
||||
export const DEFAULT_PURGE_DAYS = 0;
|
||||
export const MIN_RETENTION_DAYS = 1;
|
||||
export const MAX_RETENTION_DAYS = 3650;
|
||||
|
||||
/** Rétention en jours (0 = jamais archiver). Défaut DEFAULT_RETENTION_DAYS. Lecture tolérante. */
|
||||
export function readRetentionDays(db: Db): number {
|
||||
return readDaysSetting(db, RETENTION_DAYS_KEY, DEFAULT_RETENTION_DAYS);
|
||||
}
|
||||
|
||||
/** Purge définitive en jours (0 = désactivée). Défaut DEFAULT_PURGE_DAYS. Lecture tolérante. */
|
||||
export function readPurgeDays(db: Db): number {
|
||||
return readDaysSetting(db, PURGE_DAYS_KEY, DEFAULT_PURGE_DAYS);
|
||||
}
|
||||
|
||||
function readDaysSetting(db: Db, key: string, fallback: number): number {
|
||||
const raw = getSetting(db, key);
|
||||
if (raw === null) return fallback;
|
||||
const n = Number(raw);
|
||||
return isValidDays(n) ? n : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Valide un nombre de jours : entier `0` (= désactivé) OU dans [MIN, MAX]. Retourne null si invalide
|
||||
* (⇒ 400). Le même validateur sert pour la rétention et la purge (mêmes bornes, même sémantique de 0).
|
||||
*/
|
||||
export function normalizeRetentionDays(raw: unknown): number | null {
|
||||
return typeof raw === 'number' && isValidDays(raw) ? raw : null;
|
||||
}
|
||||
|
||||
/** Alias sémantique pour la purge (mêmes règles). */
|
||||
export const normalizePurgeDays = normalizeRetentionDays;
|
||||
|
||||
function isValidDays(n: number): boolean {
|
||||
if (!Number.isInteger(n)) return false;
|
||||
return n === 0 || (n >= MIN_RETENTION_DAYS && n <= MAX_RETENTION_DAYS);
|
||||
}
|
||||
75
packages/server/src/core/session-archive.ts
Normal file
75
packages/server/src/core/session-archive.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
// Archivage automatique des sessions terminées (P10). Scheduler calqué sur DiscoveryService :
|
||||
// start()/stop() + setInterval().unref(). Soft-archive uniquement (jamais de DELETE dans cette
|
||||
// itération ; la purge définitive est conçue mais désactivée par défaut, cf. retention-settings).
|
||||
// Démarré dans runDaemon (jamais dans buildApp → ne tourne pas pendant les tests unitaires).
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { archiveExpiredSessions, type Db } from '../db/index.js';
|
||||
import { recordAudit } from './audit-log.js';
|
||||
import { readRetentionDays } from './retention-settings.js';
|
||||
|
||||
/** Balayage toutes les 6 h : la rétention se compte en jours, pas besoin de plus fréquent. */
|
||||
const DEFAULT_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface SessionArchiveEvents {
|
||||
/** une session vient d'être archivée (relayée en `session_archived` par la gateway). */
|
||||
session_archived: [{ id: string; archivedAt: string }];
|
||||
}
|
||||
|
||||
export interface SessionArchiveOptions {
|
||||
db: Db;
|
||||
intervalMs?: number;
|
||||
}
|
||||
|
||||
export class SessionArchiveService extends EventEmitter<SessionArchiveEvents> {
|
||||
private readonly db: Db;
|
||||
private readonly intervalMs: number;
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(opts: SessionArchiveOptions) {
|
||||
super();
|
||||
this.db = opts.db;
|
||||
this.intervalMs = opts.intervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
this.sweep(); // passage immédiat au boot (synchrone, bon marché : un seul UPDATE borné)
|
||||
this.timer = setInterval(() => this.sweep(), this.intervalMs);
|
||||
this.timer.unref(); // ne maintient pas le process en vie
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
if (this.timer) {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Archive les sessions terminées plus anciennes que la rétention configurée. Retourne le nombre
|
||||
* archivé. Tolérant : ne lève jamais (une erreur ne doit pas tuer le scheduler). `0 jour` = OFF.
|
||||
*/
|
||||
sweep(): number {
|
||||
try {
|
||||
const days = readRetentionDays(this.db);
|
||||
if (days <= 0) return 0; // rétention désactivée
|
||||
const now = new Date();
|
||||
const archivedAt = now.toISOString();
|
||||
const cutoffIso = new Date(now.getTime() - days * MS_PER_DAY).toISOString();
|
||||
const ids = archiveExpiredSessions(this.db, archivedAt, cutoffIso);
|
||||
for (const id of ids) {
|
||||
this.emit('session_archived', { id, archivedAt });
|
||||
recordAudit(this.db, { actor: 'system', action: 'session.autoArchive', resourceId: id });
|
||||
}
|
||||
return ids.length;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Diffuse l'archivage d'une session (déjà archivée + auditée par l'appelant — ex. route manuelle). */
|
||||
emitArchived(id: string, archivedAt: string): void {
|
||||
this.emit('session_archived', { id, archivedAt });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user