feat(p11): temps réel complet (watcher checkout principal + topic settings)

P11-A — branche du checkout principal modifiée hors Arboretum :
- fs-watcher: pin « permanent » non évinçable (pinRepo/unpinRepo, repoPins dans evictIfNeeded)
- worktree-manager: armMainCheckoutWatchers() + arm/désarm sur addRepo/découverte/removeRepo/hidden
- index.ts: armMainCheckoutWatchers() dans runDaemon → git checkout CLI sur le principal → worktree_update <500ms sans watch client

P11-B — réglages en temps réel :
- protocole additif: type SettingsBroadcast (source unique, réutilisé par SettingsResponse), topic 'settings', message settings_update (validés parseClientMessage + gateway)
- core/settings-bus.ts (EventEmitter) ; routes/settings émet après PATCH ; gateway relaie aux abonnés 'settings'
- web: ws-client subscribeSettings + routage ; store settings applySettings/startRealtime ; AppShell abonne globalement ; SettingsView re-sync des drafts scalaires sans écraser une saisie en cours
- tests: protocol (topic settings) + fs-watcher (pinRepo non évincé) ; acceptance-p11.mjs (checkout principal <500ms + settings_update)
This commit is contained in:
2026-06-27 14:08:44 +02:00
parent 92670a796a
commit e8d10b7ec0
16 changed files with 304 additions and 38 deletions

View File

@@ -23,6 +23,8 @@ interface WatchEntry {
refCount: number;
/** nombre de sessions vivantes épinglant ce worktree. */
sessionPins: number;
/** épingle « permanente » (checkout principal d'un repo enregistré) — jamais évincée (P11). */
repoPins: number;
lastUsed: number;
debounce: NodeJS.Timeout | null;
/** résolue quand chokidar a fini son scan initial (les events deviennent fiables). */
@@ -91,6 +93,24 @@ export class FsWatcherService extends EventEmitter<FsWatcherEvents> {
e.lastUsed = Date.now();
}
/**
* Épingle en PERMANENCE le checkout principal d'un repo enregistré (P11) : ainsi un `git checkout`
* en CLI sur le principal est détecté et rediffusé sans qu'aucun client n'ait « regardé » ce
* worktree. Idempotent (un seul pin par repo+path conservé). Jamais évincé par la LRU.
*/
pinRepo(repoId: string, path: string): void {
const e = this.ensure(repoId, path);
e.repoPins = 1; // idempotent : on ne cumule pas (un seul checkout principal par repo)
e.lastUsed = Date.now();
}
unpinRepo(repoId: string, path: string): void {
const e = this.entries.get(this.key(repoId, path));
if (!e) return;
e.repoPins = 0;
e.lastUsed = Date.now();
}
/** Nombre de watchers actifs (test/diagnostic). */
size(): number {
return this.entries.size;
@@ -120,7 +140,7 @@ export class FsWatcherService extends EventEmitter<FsWatcherEvents> {
let resolveReady: () => void = () => {};
const ready = new Promise<void>((r) => (resolveReady = r));
watcher.once('ready', () => resolveReady());
const entry: WatchEntry = { repoId, path: abs, watcher, refCount: 0, sessionPins: 0, lastUsed: Date.now(), debounce: null, ready };
const entry: WatchEntry = { repoId, path: abs, watcher, refCount: 0, sessionPins: 0, repoPins: 0, lastUsed: Date.now(), debounce: null, ready };
const onChange = (): void => this.schedule(entry);
watcher.on('add', onChange).on('change', onChange).on('unlink', onChange).on('addDir', onChange).on('unlinkDir', onChange);
this.entries.set(key, entry);
@@ -151,7 +171,7 @@ export class FsWatcherService extends EventEmitter<FsWatcherEvents> {
private evictIfNeeded(): void {
if (this.entries.size <= this.maxWatchers) return;
const idle = [...this.entries.entries()]
.filter(([, e]) => e.refCount === 0 && e.sessionPins === 0)
.filter(([, e]) => e.refCount === 0 && e.sessionPins === 0 && e.repoPins === 0)
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
for (const [key, e] of idle) {
if (this.entries.size <= this.maxWatchers) break;

View File

@@ -0,0 +1,11 @@
// Bus d'événements des réglages (P11) : la route PATCH /settings émet le snapshot non sensible
// après une mise à jour réussie ; la gateway WS le relaie aux abonnés du topic 'settings'. Découple
// les routes de la gateway (pas de dépendance directe), comme les EventEmitter des managers.
import { EventEmitter } from 'node:events';
import type { SettingsBroadcast } from '@arboretum/shared';
export interface SettingsBusEvents {
settings_update: [SettingsBroadcast];
}
export class SettingsBus extends EventEmitter<SettingsBusEvents> {}

View File

@@ -202,9 +202,24 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
}
const summary = await this.rowToSummary(row);
this.emit('repo_update', summary);
this.armRepoWatcher(row); // P11 : temps réel du checkout principal dès l'enregistrement
return summary;
}
/**
* P11 — arme un watcher PERMANENT sur le checkout principal de chaque repo visible : un
* `git checkout`/`switch` en CLI sur le principal est ainsi rediffusé en temps réel sans qu'un
* client ne l'ait « regardé ». Appelé depuis runDaemon (jamais buildApp → pas d'effet en tests purs).
*/
armMainCheckoutWatchers(): void {
const rows = this.db.prepare('SELECT id, path FROM repos WHERE hidden = 0').all() as Array<{ id: string; path: string }>;
for (const r of rows) this.armRepoWatcher(r);
}
private armRepoWatcher(row: { id: string; path: string }): void {
this.fsWatcher?.pinRepo(row.id, resolve(row.path));
}
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
const row = this.getRepoRow(id);
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
@@ -217,12 +232,19 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
const summary = await this.rowToSummary(row);
this.emit('repo_update', summary);
// P11 : masqué → on libère le watcher permanent du principal ; ré-affiché → on le réarme.
if (patch.hidden !== undefined) {
if (row.hidden === 1) this.fsWatcher?.unpinRepo(id, resolve(row.path));
else this.armRepoWatcher(row);
}
return summary;
}
removeRepo(id: string): boolean {
const row = this.getRepoRow(id);
const res = this.db.prepare('DELETE FROM repos WHERE id = ?').run(id);
if (res.changes === 0) return false;
if (row) this.fsWatcher?.unpinRepo(id, resolve(row.path)); // P11 : libère le watcher permanent
this.factsCache.delete(id);
this.emit('repo_removed', id);
return true;
@@ -270,6 +292,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
if (res.changes === 1) {
added++;
this.emit('repo_update', await this.rowToSummary(row)); // nouveaux uniquement
this.armRepoWatcher(row); // P11 : temps réel du checkout principal du repo découvert
}
}
return { scanned: paths.length, added, durationMs: Date.now() - t0, truncated };