release: git-arboretum 3.4.0 (visibilité temps réel, historisation), desktop 0.2.0 (Windows, logo), vscode 0.4.1, site 0.4.0
CI / Build & test (Node 22) (push) Successful in 11m12s
CI / Build & test (Node 24) (push) Successful in 10m14s
CI / No em/en dashes (push) Successful in 3s
Deploy site (production) / build-and-deploy (push) Successful in 19s
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / Build & test (Node 22) (push) Successful in 11m12s
CI / Build & test (Node 24) (push) Successful in 10m14s
CI / No em/en dashes (push) Successful in 3s
Deploy site (production) / build-and-deploy (push) Successful in 19s
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
Tout est additif : PROTOCOL_VERSION inchangé, aucune rupture d'API. Temps réel réellement armé - `pinSession` n'était appelé nulle part : une session vivante épingle désormais le watcher FS de son worktree (`WorktreeManager.syncSessionPin` + `resolveWorktreeForCwd`), donc un worktree où un agent écrit se rafraîchit même si personne ne le regarde (mesuré ~350 ms). - Les abonnements `watch` sortent de `GitPanel`, démonté dès qu'on quitte son onglet, ce qui coupait le seul abonnement de toute l'app : `composables/useWatchedWorktrees.ts` (monté dans App.vue) suit le worktree actif et les dépôts dépliés, borné à 40. - Une coupure WS ne laisse plus l'UI sur des listes périmées : rechargement complet au retour. - `worktree_changes` alimente `worktrees.changeVersion`, consommé par l'arbre de fichiers, le diff (son `:version` était câblé à 0) et l'éditeur, qui recharge un tampon propre ou lève la bannière de conflit avant la sauvegarde au lieu d'attendre le 409. Corrélation session ↔ worktree par contenance (`@arboretum/shared/path-match.ts`) - Un terminal lancé dans un sous-répertoire (« Démarrer le projet ») ou une session de groupe reliée par `--add-dir` apparaissent enfin sous leur worktree ; le worktree le plus spécifique gagne. - Règle unique partagée par le daemon, le web et l'extension. Historisation - `commitLog` / `commitDiff` purs, `GET /repos/:id/worktrees/log` et `diff?commit=` (hash strictement validé, mêmes bornes que les diffs de fichiers). - `CommitHistory.vue` sous le panneau Git : commits, marquage des non poussés, diff déplié sur place. Visibilité - Compteurs git complets sur chaque worktree de l'arbre et du panneau Groupes (ils n'existaient qu'en barre de statut, pour le seul worktree actif), avec upstream et dernier commit en infobulle ; `locked`, `prunable` et un dépôt invalide sont désormais visibles. - Le panneau Groupes montre sa composition réelle (dépôts, worktrees, sessions) et teinte l'explorateur. Polish visuel - Les toasts d'erreur, persistants, s'empilaient derrière les modals : téléportés au-dessus. - Sur mobile, ouvrir un terminal ou changer d'activité n'avait aucun effet visible. - Tailles de panneaux clampées sur la fenêtre, barres d'onglets sans scrollbar parasite, états de chargement et d'erreur dans les trois panneaux, accessibilité des 11 modals centralisée dans ModalHost, splitters au clavier, numéros de diff collants, `window.confirm` remplacé. Windows (daemon et packaging) - `where.exe`, PowerShell comme shell de lancement, askpass `.cmd` (clone/push HTTPS par PAT), `taskkill /T`, `%APPDATA%`, `arboretum install` via tâche planifiée. - Scripts de build exécutables sur un hôte Windows (`npm.cmd`, extraction sans `unzip` ni `bash`). - Job CI `windows-latest` conditionné par ENABLE_WINDOWS_BUILD ; procédure runner dans docs/CI_RUNNERS.md. Logo Debian : cause racine - Une icône unique de 895×895 atterrissait dans `hicolor/895x895`, répertoire absent d'`index.theme` donc ignoré par la spécification freedesktop ; et `executableName` dérivait du nom scopé du paquet (`@arboretumdesktop`). Jeu d'icônes standard généré + `executableName: arboretum`, plus `deb.synopsis` (description courte vide dans apt) et `Section: devel`. - Runtime Node embarqué élagué : 205 → 118 Mo. - Auto-update réparé : la release flottante `desktop-latest` que les binaires interrogent n'existait pas. Doc et vitrine - README/README.fr : installation par plateforme, mode serveur web (nginx, LAN), dépannage, variables d'environnement, flags manquants. - Doc in-app réécrite (elle renvoyait aux pages Worktrees et Sessions supprimées). - Section « Accès distant » dans les Réglages ; le 403 BAD_ORIGIN nomme le flag à ajouter. - Site : prérequis et registre npm privé (le `npx` affiché renvoyait un 404), téléchargements réels par plateforme, section « trois façons de l'utiliser », navigation complétée, 16 clés i18n mortes purgées. Vérifications : 483 tests unitaires, 14 acceptances E2E vertes (dont p14/p15 nouvelles), captures de rendu sans erreur console (nouveau `verify-ui.mjs`), .deb reconstruit et contrôlé (icônes aux tailles standard, entrée .desktop valide).
This commit is contained in:
@@ -183,7 +183,12 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
||||
if (!isApi && !isWs) return; // statique : public (la SPA gère son écran de login)
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigins.has(origin)) {
|
||||
return reply.status(403).send({ error: { code: 'BAD_ORIGIN', message: `Origin not allowed: ${origin}` } });
|
||||
// Message ACTIONNABLE : c'est le premier mur de tout accès non-loopback (LAN, reverse proxy,
|
||||
// Tailscale). Un « Origin not allowed » sec laissait chercher pendant des heures, alors que la
|
||||
// correction tient en un flag. Le log serveur porte la même consigne.
|
||||
const hint = `Origin not allowed: ${origin}. Restart the daemon with --allow-origin ${origin} (repeatable) to permit it.`;
|
||||
req.log.warn({ origin, allowed: [...allowedOrigins] }, hint);
|
||||
return reply.status(403).send({ error: { code: 'BAD_ORIGIN', message: hint } });
|
||||
}
|
||||
req.authContext = authenticate(req);
|
||||
if (req.routeOptions.config.public) return;
|
||||
|
||||
@@ -12,7 +12,7 @@ import { AuthService } from '../auth/service.js';
|
||||
const SERVICE_NAME = 'arboretum';
|
||||
const LAUNCHD_LABEL = 'fr.lidge.arboretum';
|
||||
|
||||
export type SupportedPlatform = 'linux' | 'darwin';
|
||||
export type SupportedPlatform = 'linux' | 'darwin' | 'win32';
|
||||
|
||||
export interface InstallFlags {
|
||||
port?: string | undefined;
|
||||
@@ -29,15 +29,31 @@ export interface InstallFlags {
|
||||
|
||||
// ─── Fonctions pures (génération de contenu / chemins) ────────────────────────────────
|
||||
|
||||
/** macOS (launchd) et Linux (systemd) uniquement ; sinon throw avec un message pédagogique. */
|
||||
/**
|
||||
* Superviseur par plateforme : systemd (Linux), launchd (macOS), Planificateur de tâches (Windows).
|
||||
* Toujours en tant qu'utilisateur, jamais en root/SYSTEM.
|
||||
*/
|
||||
export function detectPlatform(platform: NodeJS.Platform = process.platform): SupportedPlatform {
|
||||
if (platform === 'linux' || platform === 'darwin') return platform;
|
||||
if (platform === 'linux' || platform === 'darwin' || platform === 'win32') return platform;
|
||||
throw new Error(
|
||||
`Automatic service installation is supported on Linux (systemd) and macOS (launchd) only.\n` +
|
||||
`On ${platform}, run \`arboretum\` manually or set up your own supervisor.`,
|
||||
`Automatic service installation is supported on Linux (systemd), macOS (launchd) and Windows ` +
|
||||
`(Task Scheduler) only.\nOn ${platform}, run \`arboretum\` manually or set up your own supervisor.`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Nom de la tâche planifiée Windows (visible dans taskschd.msc). */
|
||||
export const WINDOWS_TASK_NAME = 'Arboretum';
|
||||
|
||||
/**
|
||||
* Arguments `schtasks /Create` d'une tâche « au démarrage de session utilisateur ». `/RL LIMITED`
|
||||
* garde les privilèges de l'utilisateur (jamais d'élévation), `/F` rend la commande idempotente.
|
||||
* `/TR` attend UNE chaîne de commande : chaque token à espaces est donc quoté.
|
||||
*/
|
||||
export function windowsCreateArgs(input: { taskName: string; exec: string; scriptArgs: string[] }): string[] {
|
||||
const command = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
|
||||
return ['/Create', '/TN', input.taskName, '/TR', command, '/SC', 'ONLOGON', '/RL', 'LIMITED', '/F'];
|
||||
}
|
||||
|
||||
export function parseInstallArgs(argv: string[]): InstallFlags {
|
||||
const { values } = parseArgs({
|
||||
args: argv,
|
||||
@@ -207,7 +223,8 @@ export function printUsage(version: string): void {
|
||||
Usage:
|
||||
arboretum [flags] Start the daemon (default)
|
||||
arboretum serve [flags] Start the daemon (explicit alias)
|
||||
arboretum install [flags] Install & start a user service (systemd on Linux, launchd on macOS)
|
||||
arboretum install [flags] Install & start a user service (systemd on Linux, launchd on macOS,
|
||||
Task Scheduler on Windows)
|
||||
arboretum uninstall Stop & remove the user service
|
||||
arboretum status Show the service status
|
||||
arboretum help Show this help
|
||||
@@ -218,6 +235,9 @@ Daemon flags:
|
||||
--allow-origin <url> Additional allowed Origin (repeatable)
|
||||
--db <path> SQLite database path
|
||||
--vapid-contact <mailto|url> VAPID contact subject for Web Push
|
||||
--claude-home <path> Override the Claude install root (default ~/.claude)
|
||||
--print-token Print the access token on start (bootstrap it if missing)
|
||||
--no-discover Disable repository auto-discovery (startup + periodic scan)
|
||||
--i-know-this-exposes-a-terminal Acknowledge a non-loopback bind (avoid, prefer Tailscale Serve)
|
||||
|
||||
Install flags (daemon flags above are propagated to the service):
|
||||
@@ -301,6 +321,23 @@ export async function runInstall(argv: string[]): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
if (platform === 'win32') {
|
||||
// Windows : Planificateur de tâches, déclenchement à l'ouverture de session. Pas de service NT
|
||||
// (il tournerait hors session utilisateur, donc sans accès au profil ni au CLI `claude`).
|
||||
const createArgs = windowsCreateArgs({ taskName: WINDOWS_TASK_NAME, exec, scriptArgs });
|
||||
if (flags.dryRun) {
|
||||
console.log(`# commands:\nschtasks ${createArgs.join(' ')}`);
|
||||
if (!flags.noEnable) console.log(`schtasks /Run /TN ${WINDOWS_TASK_NAME}`);
|
||||
return;
|
||||
}
|
||||
bootstrapToken(serviceArgs);
|
||||
run('schtasks.exe', createArgs, { check: true });
|
||||
console.log(`Registered scheduled task "${WINDOWS_TASK_NAME}" (runs at logon).`);
|
||||
if (!flags.noEnable) run('schtasks.exe', ['/Run', '/TN', WINDOWS_TASK_NAME], { check: true });
|
||||
console.log(`\nArboretum task installed. Manage it with: schtasks /Query /TN ${WINDOWS_TASK_NAME}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// macOS (launchd)
|
||||
const logs = launchdLogPaths();
|
||||
const programArguments = [exec, ...scriptArgs];
|
||||
@@ -352,6 +389,12 @@ export async function runUninstall(argv: string[]): Promise<void> {
|
||||
console.log('Arboretum service removed.');
|
||||
return;
|
||||
}
|
||||
if (platform === 'win32') {
|
||||
run('schtasks.exe', ['/End', '/TN', WINDOWS_TASK_NAME]); // best-effort : arrête l'instance courante
|
||||
run('schtasks.exe', ['/Delete', '/TN', WINDOWS_TASK_NAME, '/F']);
|
||||
console.log('Arboretum scheduled task removed.');
|
||||
return;
|
||||
}
|
||||
const plistPath = launchAgentPlistPath(flags.label);
|
||||
const uid = process.getuid?.() ?? 0;
|
||||
run('launchctl', ['bootout', `gui/${uid}/${flags.label}`]); // best-effort
|
||||
@@ -371,6 +414,10 @@ export async function runStatus(argv: string[]): Promise<void> {
|
||||
process.exitCode = code;
|
||||
return;
|
||||
}
|
||||
if (platform === 'win32') {
|
||||
process.exitCode = run('schtasks.exe', ['/Query', '/TN', WINDOWS_TASK_NAME, '/V', '/FO', 'LIST']);
|
||||
return;
|
||||
}
|
||||
const uid = process.getuid?.() ?? 0;
|
||||
const code = run('launchctl', ['print', `gui/${uid}/${flags.label}`]);
|
||||
console.log(`\nLogs: ${launchdLogPaths().out}`);
|
||||
|
||||
@@ -25,6 +25,21 @@ export interface Config {
|
||||
autoDiscover: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Racine des données applicatives, par plateforme. `XDG_DATA_HOME` reste prioritaire partout (l'app de
|
||||
* bureau s'en sert pour isoler ses données). Sinon : `%APPDATA%` sur Windows (`~/.local/share` n'y a
|
||||
* aucun sens et n'est ni sauvegardé ni migré par l'OS), `~/.local/share` ailleurs.
|
||||
*/
|
||||
export function defaultDataRoot(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
home: string = homedir(),
|
||||
): string {
|
||||
if (env.XDG_DATA_HOME) return env.XDG_DATA_HOME;
|
||||
if (platform === 'win32') return env.APPDATA ?? join(home, 'AppData', 'Roaming');
|
||||
return join(home, '.local', 'share');
|
||||
}
|
||||
|
||||
export function loadConfig(argv = process.argv.slice(2)): Config {
|
||||
const { values } = parseArgs({
|
||||
args: argv,
|
||||
@@ -55,7 +70,7 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
||||
);
|
||||
}
|
||||
|
||||
const dataDir = join(process.env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), 'arboretum');
|
||||
const dataDir = join(defaultDataRoot(), 'arboretum');
|
||||
mkdirSync(dataDir, { recursive: true });
|
||||
// La DB contient des secrets (server_secret, clé privée VAPID, hashs de tokens) : le dossier de
|
||||
// données ne doit jamais être lisible par d'autres utilisateurs du système. chmod best-effort
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { accessSync, constants } from 'node:fs';
|
||||
import { accessSync, constants, existsSync } from 'node:fs';
|
||||
|
||||
export interface SpawnSpec {
|
||||
file: string;
|
||||
@@ -13,7 +13,7 @@ export interface SpawnOptions {
|
||||
resume?: { claudeSessionId: string; fork?: boolean };
|
||||
/** répertoires supplémentaires à relier dans une seule session (P6) : `--add-dir <path>` répété. */
|
||||
addDirs?: string[];
|
||||
/** chemin explicite du binaire `claude` (réglage UI) ; sinon résolution via PATH (`which`). */
|
||||
/** chemin explicite du binaire `claude` (réglage UI) ; sinon résolution via le PATH. */
|
||||
claudeBinPath?: string | null;
|
||||
/**
|
||||
* Lancement de projet (« Démarrer le projet ») : au lieu de `bash --norc`, lance le shell de
|
||||
@@ -22,6 +22,8 @@ export interface SpawnOptions {
|
||||
* (PATH minimal, cf. resolveClaudeBin) : sinon `npm`/`docker` seraient introuvables. Ignoré pour claude.
|
||||
*/
|
||||
login?: boolean;
|
||||
/** plateforme cible (injectable pour les tests) ; défaut `process.platform`. */
|
||||
platform?: NodeJS.Platform;
|
||||
}
|
||||
|
||||
/** Diagnostic de résolution du binaire `claude` (exposé en lecture dans Réglages). */
|
||||
@@ -36,16 +38,32 @@ export interface ClaudeBinDiagnostic {
|
||||
|
||||
let cachedClaudeBin: string | null = null;
|
||||
|
||||
/**
|
||||
* Commande de recherche dans le PATH selon la plateforme : `which` n'existe PAS sur Windows, c'est
|
||||
* `where.exe` (qui peut renvoyer plusieurs lignes, la première étant la retenue).
|
||||
*/
|
||||
export function whichCommand(platform: NodeJS.Platform = process.platform): { file: string; args: string[] } {
|
||||
return platform === 'win32' ? { file: 'where.exe', args: ['claude'] } : { file: 'which', args: ['claude'] };
|
||||
}
|
||||
|
||||
/** Recherche `claude` dans le PATH (sans throw). null si absent. */
|
||||
function findClaudeOnPath(): string | null {
|
||||
function findClaudeOnPath(platform: NodeJS.Platform = process.platform): string | null {
|
||||
const { file, args } = whichCommand(platform);
|
||||
try {
|
||||
return execFileSync('which', ['claude'], { encoding: 'utf8' }).trim() || null;
|
||||
const out = execFileSync(file, args, { encoding: 'utf8' });
|
||||
// `where.exe` liste toutes les correspondances : on garde la première.
|
||||
return out.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length > 0) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isExecutable(path: string): boolean {
|
||||
/**
|
||||
* « Est-ce lançable ? ». Sur Windows, le bit d'exécution POSIX n'a aucun sens (NTFS n'en a pas) et
|
||||
* `accessSync(X_OK)` y répond au hasard : on se contente donc de l'existence du fichier.
|
||||
*/
|
||||
function isExecutable(path: string, platform: NodeJS.Platform = process.platform): boolean {
|
||||
if (platform === 'win32') return existsSync(path);
|
||||
try {
|
||||
accessSync(path, constants.X_OK);
|
||||
return true;
|
||||
@@ -57,9 +75,9 @@ function isExecutable(path: string): boolean {
|
||||
/**
|
||||
* Résout le binaire `claude`. Si `configuredPath` est fourni (réglage UI), il est utilisé tel quel
|
||||
* (validé exécutable, message clair sinon) et JAMAIS mis en cache (modifiable à chaud). Sinon :
|
||||
* `which claude`, mis en cache. Un service systemd/launchd démarre avec un PATH minimal sans
|
||||
* ~/.local/bin → `which claude` y échoue ; d'où le réglage de chemin explicite (et le PATH figé par
|
||||
* `arboretum install`).
|
||||
* recherche dans le PATH (`which` / `where.exe`), mise en cache. Un service systemd/launchd démarre
|
||||
* avec un PATH minimal sans ~/.local/bin → la recherche y échoue ; d'où le réglage de chemin explicite
|
||||
* (et le PATH figé par `arboretum install`).
|
||||
*/
|
||||
export function resolveClaudeBin(configuredPath?: string | null): string {
|
||||
if (configuredPath) {
|
||||
@@ -92,32 +110,48 @@ export function diagnoseClaudeBin(configuredPath?: string | null): ClaudeBinDiag
|
||||
const KNOWN_LOGIN_SHELLS = new Set(['bash', 'zsh', 'fish']);
|
||||
|
||||
/**
|
||||
* Shell de login pour « Démarrer le projet » : `$SHELL` s'il est un shell interactif connu
|
||||
* (bash/zsh/fish), sinon fallback `bash`. Évite qu'un `$SHELL` exotique (dash…) sorte aussitôt
|
||||
* avec `-l -i` et laisse un terminal vide.
|
||||
* Shell interactif pour « Démarrer le projet ».
|
||||
*
|
||||
* POSIX : `$SHELL -l -i` s'il fait partie des shells connus supportant ces options (bash/zsh/fish),
|
||||
* sinon `bash` (un `$SHELL=dash` sortirait aussitôt avec `-l -i`, laissant un terminal vide).
|
||||
*
|
||||
* Windows : PowerShell, en restant attaché après la commande auto-tapée (`-NoExit`), avec repli sur
|
||||
* `cmd.exe /K`. `%COMSPEC%` n'est PAS utilisé comme shell de lancement : il pointe cmd.exe, qui ne
|
||||
* charge aucun profil utilisateur. La commande est ensuite auto-tapée par le PtyManager, exactement
|
||||
* comme sous POSIX · le mécanisme est indépendant du shell.
|
||||
*/
|
||||
function loginShell(): string {
|
||||
const shell = process.env.SHELL;
|
||||
if (shell && KNOWN_LOGIN_SHELLS.has(shell.split('/').pop() ?? '')) return shell;
|
||||
return 'bash';
|
||||
export function resolveInteractiveShell(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
): { file: string; args: string[] } {
|
||||
if (platform === 'win32') {
|
||||
const pwsh = env.ARBORETUM_SHELL ?? 'powershell.exe';
|
||||
return { file: pwsh, args: ['-NoLogo', '-NoExit'] };
|
||||
}
|
||||
const shell = env.SHELL;
|
||||
const file = shell && KNOWN_LOGIN_SHELLS.has(shell.split('/').pop() ?? '') ? shell : 'bash';
|
||||
return { file, args: ['-l', '-i'] };
|
||||
}
|
||||
|
||||
/** Shell non interactif « neutre » (terminal simple, hors lancement de projet). */
|
||||
export function resolvePlainShell(platform: NodeJS.Platform = process.platform): { file: string; args: string[] } {
|
||||
if (platform === 'win32') return { file: 'powershell.exe', args: ['-NoLogo', '-NoExit'] };
|
||||
return { file: 'bash', args: ['--norc'] };
|
||||
}
|
||||
|
||||
/** Module volontairement abstrait : le plan B « BYO API key / Agent SDK » se brancherait ici. */
|
||||
export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
||||
const platform = opts.platform ?? process.platform;
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
TERM: 'xterm-256color',
|
||||
COLORTERM: 'truecolor',
|
||||
};
|
||||
if (opts.command === 'bash') {
|
||||
// Lancement de projet : shell de login interactif de l'utilisateur (charge PATH/nvm/asdf).
|
||||
// `-l` (login) exécute les profils, `-i` (interactif) reste attaché après la commande auto-tapée.
|
||||
// On n'utilise `$SHELL` que s'il fait partie des shells interactifs connus supportant `-l -i`
|
||||
// (bash/zsh/fish) ; sinon fallback bash (ex. `$SHELL=dash` sortirait avec `-l -i`).
|
||||
if (opts.login) {
|
||||
return { file: loginShell(), args: ['-l', '-i'], env };
|
||||
}
|
||||
return { file: 'bash', args: ['--norc'], env };
|
||||
// `'bash'` désigne « le shell de la machine », pas littéralement bash : le contrat d'API reste
|
||||
// stable (claude|bash) et c'est ici qu'on choisit le shell réel par plateforme.
|
||||
const { file, args } = opts.login ? resolveInteractiveShell(platform) : resolvePlainShell(platform);
|
||||
return { file, args, env };
|
||||
}
|
||||
const args: string[] = [];
|
||||
if (opts.resume) {
|
||||
|
||||
@@ -7,9 +7,33 @@ import { resolve, sep, join } from 'node:path';
|
||||
import chokidar, { type FSWatcher } from 'chokidar';
|
||||
import { resolveGitDir } from './git.js';
|
||||
|
||||
const DEFAULT_MAX_WATCHERS = 32;
|
||||
// Plafond du pool : l'arbre de projets peut désormais « regarder » tous les worktrees des dépôts
|
||||
// dépliés (et non plus le seul worktree du panneau Git), il faut donc de la marge. Les entrées
|
||||
// épinglées (session vivante, checkout principal) ne sont jamais évincées, cf. evictIfNeeded.
|
||||
const DEFAULT_MAX_WATCHERS = 64;
|
||||
const DEBOUNCE_MS = 200;
|
||||
|
||||
/**
|
||||
* Répertoires lourds ignorés en plus de `.git` : ils concentrent l'essentiel des descripteurs inotify
|
||||
* sans jamais rien apprendre sur le statut git. Liste volontairement CONSERVATRICE (pas de `dist`,
|
||||
* `build`, `out` ni `vendor`, qui sont versionnés dans certains projets : les ignorer ferait manquer
|
||||
* un vrai changement).
|
||||
*/
|
||||
const IGNORED_DIRS = [
|
||||
'node_modules',
|
||||
'.venv',
|
||||
'venv',
|
||||
'__pycache__',
|
||||
'.turbo',
|
||||
'.cache',
|
||||
'.pnpm-store',
|
||||
'coverage',
|
||||
'.next',
|
||||
'.nuxt',
|
||||
'.output',
|
||||
'target',
|
||||
];
|
||||
|
||||
export interface FsWatcherEvents {
|
||||
/** le contenu d'un worktree surveillé a changé (édition, staging, checkout externe…). */
|
||||
worktree_fs_change: [{ repoId: string; path: string }];
|
||||
@@ -33,11 +57,14 @@ interface WatchEntry {
|
||||
|
||||
/**
|
||||
* Ignore tout sous `.git/` SAUF `HEAD` et `index` (⇒ on détecte le `git checkout` externe et le
|
||||
* staging) ainsi que `node_modules`. chokidar n'ignore pas le dossier `.git` lui-même afin de
|
||||
* pouvoir descendre jusqu'à `HEAD`/`index`, mais saute ses sous-dossiers volumineux (objects…).
|
||||
* staging) ainsi que les répertoires de `IGNORED_DIRS`. chokidar n'ignore pas le dossier `.git`
|
||||
* lui-même afin de pouvoir descendre jusqu'à `HEAD`/`index`, mais saute ses sous-dossiers
|
||||
* volumineux (objects…).
|
||||
*/
|
||||
export function isIgnoredPath(p: string): boolean {
|
||||
if (p.includes(`${sep}node_modules${sep}`) || p.endsWith(`${sep}node_modules`)) return true;
|
||||
for (const dir of IGNORED_DIRS) {
|
||||
if (p.includes(`${sep}${dir}${sep}`) || p.endsWith(`${sep}${dir}`)) return true;
|
||||
}
|
||||
if (p.includes(`${sep}.git${sep}`)) {
|
||||
return !(p.endsWith(`${sep}HEAD`) || p.endsWith(`${sep}index`));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Préparation d'un environnement d'authentification git ÉPHÉMÈRE (P12). HTTPS (pat/app_password) :
|
||||
// les identifiants sont fournis via GIT_ASKPASS (script 0o700 lisant deux variables d'env), JAMAIS
|
||||
// dans l'URL ni dans `.git/config`. GIT_TERMINAL_PROMPT=0 (pas d'invite bloquante). Le script est
|
||||
// supprimé en `finally` ; le secret ne transite que par l'env du process enfant (jamais loggé).
|
||||
// les identifiants sont fournis via GIT_ASKPASS (script à permissions restreintes lisant deux variables
|
||||
// d'env), JAMAIS dans l'URL ni dans `.git/config`. GIT_TERMINAL_PROMPT=0 (pas d'invite bloquante). Le
|
||||
// script est supprimé en `finally` ; le secret ne transite que par l'env du process enfant (jamais loggé).
|
||||
import { mkdtemp, writeFile, rm, chmod } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
@@ -11,20 +11,40 @@ import type { GitAuth } from './git-clients/index.js';
|
||||
// Identité HTTPS par défaut quand l'utilisateur n'a pas fourni de username (token-as-password).
|
||||
const SERVICE_DEFAULT_USER: Record<GitService, string> = { github: 'x-access-token', gitlab: 'oauth2', gitea: 'oauth2' };
|
||||
|
||||
const ASKPASS_SH = "#!/bin/sh\ncase \"$1\" in\n Username*) printf '%s' \"$ARB_GIT_USER\" ;;\n *) printf '%s' \"$ARB_GIT_PASS\" ;;\nesac\n";
|
||||
|
||||
// Équivalent Windows : git appelle GIT_ASKPASS avec l'invite en argument. `echo` de cmd.exe ajoute un
|
||||
// saut de ligne que git tolère (il trime la réponse). `~1` = premier argument sans les guillemets.
|
||||
const ASKPASS_CMD = [
|
||||
'@echo off',
|
||||
'echo %~1 | findstr /b /i "Username" >nul',
|
||||
'if %errorlevel%==0 (echo %ARB_GIT_USER%) else (echo %ARB_GIT_PASS%)',
|
||||
'',
|
||||
].join('\r\n');
|
||||
|
||||
/**
|
||||
* Nom et contenu du script askpass selon la plateforme. Un `.sh` avec shebang n'est PAS exécutable sur
|
||||
* Windows : sans cette variante `.cmd`, tout clone/push HTTPS par jeton y échouait silencieusement
|
||||
* (git n'obtenait aucun identifiant et abandonnait, GIT_TERMINAL_PROMPT étant à 0).
|
||||
*/
|
||||
export function askpassScript(platform: NodeJS.Platform = process.platform): { name: string; content: string; mode: number } {
|
||||
return platform === 'win32'
|
||||
? { name: 'askpass.cmd', content: ASKPASS_CMD, mode: 0o700 }
|
||||
: { name: 'askpass.sh', content: ASKPASS_SH, mode: 0o700 };
|
||||
}
|
||||
|
||||
export async function withGitAuth<T>(
|
||||
service: GitService,
|
||||
auth: GitAuth,
|
||||
fn: (env: NodeJS.ProcessEnv) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'arb-gitauth-'));
|
||||
const askpass = join(dir, 'askpass.sh');
|
||||
const script = askpassScript();
|
||||
const askpass = join(dir, script.name);
|
||||
const user = auth.username || SERVICE_DEFAULT_USER[service];
|
||||
await writeFile(
|
||||
askpass,
|
||||
"#!/bin/sh\ncase \"$1\" in\n Username*) printf '%s' \"$ARB_GIT_USER\" ;;\n *) printf '%s' \"$ARB_GIT_PASS\" ;;\nesac\n",
|
||||
{ mode: 0o700 },
|
||||
);
|
||||
await chmod(askpass, 0o700);
|
||||
await writeFile(askpass, script.content, { mode: script.mode });
|
||||
// chmod best-effort : sans effet sur NTFS (comme ailleurs dans le code, cf. config.ts).
|
||||
await chmod(askpass, script.mode).catch(() => {});
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_ASKPASS: askpass,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import { resolve, sep } from 'node:path';
|
||||
import type { WorktreeGitStatus, WorktreeBranchAction, WorktreeBranchMode, FileChange } from '@arboretum/shared';
|
||||
import type { WorktreeGitStatus, WorktreeBranchAction, WorktreeBranchMode, FileChange, CommitEntry } from '@arboretum/shared';
|
||||
|
||||
const GIT_TIMEOUT_MS = 10_000;
|
||||
// `push` peut dialoguer avec un remote (réseau) : on lui laisse une marge bien plus large.
|
||||
@@ -502,6 +502,81 @@ export async function lastCommit(worktreePath: string): Promise<{ hash: string;
|
||||
return { hash: r.stdout.slice(0, idx), subject: r.stdout.slice(idx + 1).replace(/\n$/, '') };
|
||||
}
|
||||
|
||||
const MAX_LOG_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* Hash de commit : hexadécimal, 4 à 64 caractères. Bornage strict AVANT de le passer à git · un
|
||||
* identifiant libre ouvrirait la porte à des révisions arbitraires ou à des options déguisées (`-…`).
|
||||
*/
|
||||
export function isValidCommitish(hash: string): boolean {
|
||||
return /^[0-9a-f]{4,64}$/i.test(hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Découpe la sortie de `git log -z --format=<n champs séparés par NUL>` en enregistrements. Isolée et
|
||||
* pure pour être testable sans dépôt : c'est le point délicat (avec `-z`, les séparateurs de champs et
|
||||
* d'enregistrements sont tous des NUL, il faut donc compter les champs).
|
||||
*/
|
||||
export function parseLogZ(stdout: string, fieldsPerCommit: number): string[][] {
|
||||
const fields = stdout.split('\0');
|
||||
const out: string[][] = [];
|
||||
for (let i = 0; i + fieldsPerCommit - 1 < fields.length; i += fieldsPerCommit) {
|
||||
const rec = fields.slice(i, i + fieldsPerCommit);
|
||||
if ((rec[0] ?? '').trim() === '') continue;
|
||||
out.push(rec);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Historique de la branche du worktree. `-z` + champs séparés par NUL : un sujet contenant un saut de
|
||||
* ligne ne peut pas casser le parsing. `unpushedCount` = commits de tête pas encore poussés
|
||||
* (`@{u}..HEAD`) ; `hasUpstream: false` signifie qu'AUCUN commit n'est publié (branche purement locale),
|
||||
* ce que l'UI marque en bloc plutôt que de compter tout l'historique.
|
||||
*/
|
||||
export async function commitLog(
|
||||
worktreePath: string,
|
||||
opts: { limit?: number; skip?: number } = {},
|
||||
): Promise<{ commits: CommitEntry[]; unpushedCount: number; hasUpstream: boolean }> {
|
||||
const limit = Math.min(Math.max(1, Math.trunc(opts.limit ?? 30)), MAX_LOG_LIMIT);
|
||||
const skip = Math.max(0, Math.trunc(opts.skip ?? 0));
|
||||
const r = await gitRaw(worktreePath, [
|
||||
'log',
|
||||
`--max-count=${limit}`,
|
||||
`--skip=${skip}`,
|
||||
'-z',
|
||||
'--format=%H%x00%h%x00%an%x00%aI%x00%s',
|
||||
]);
|
||||
if (r.code !== 0) return { commits: [], unpushedCount: 0, hasUpstream: false }; // dépôt sans commit
|
||||
const commits: CommitEntry[] = parseLogZ(r.stdout, 5).map((f) => ({
|
||||
hash: (f[0] ?? '').trim(),
|
||||
shortHash: f[1] ?? '',
|
||||
author: f[2] ?? '',
|
||||
date: f[3] ?? '',
|
||||
subject: (f[4] ?? '').replace(/\n$/, ''),
|
||||
}));
|
||||
const upstream = await gitRaw(worktreePath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
||||
if (upstream.code !== 0) return { commits, unpushedCount: 0, hasUpstream: false };
|
||||
const count = await gitRaw(worktreePath, ['rev-list', '--count', '@{u}..HEAD']);
|
||||
return { commits, unpushedCount: count.code === 0 ? Number(count.stdout.trim()) || 0 : 0, hasUpstream: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Diff complet d'un commit (`git show`), borné exactement comme `fileDiff` : refus des binaires,
|
||||
* troncature au-delà de MAX_DIFF_BYTES. Le résultat étant un diff unifié, il passe dans le même
|
||||
* parseur et la même vue que les diffs de fichiers.
|
||||
*/
|
||||
export async function commitDiff(worktreePath: string, hash: string): Promise<{ diff: string; binary: boolean; tooLarge: boolean }> {
|
||||
if (!isValidCommitish(hash)) throw new Error(`Invalid commit hash: ${hash}`);
|
||||
const out = await gitRaw(worktreePath, ['show', '--no-color', '--format=', hash]);
|
||||
if (out.code !== 0) throw new Error(`Unknown commit: ${hash}`);
|
||||
const raw = out.stdout;
|
||||
const binary = /^Binary files .* differ$/m.test(raw) || raw.includes('GIT binary patch');
|
||||
if (binary) return { diff: '', binary: true, tooLarge: false };
|
||||
if (raw.length > MAX_DIFF_BYTES) return { diff: raw.slice(0, MAX_DIFF_BYTES), binary: false, tooLarge: true };
|
||||
return { diff: raw, binary: false, tooLarge: false };
|
||||
}
|
||||
|
||||
/** true si le HEAD courant n'est pas encore poussé (amend autorisé). Sans upstream → true. */
|
||||
export async function isUnpushed(worktreePath: string): Promise<boolean> {
|
||||
try {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { execFile } from 'node:child_process';
|
||||
import { existsSync, statSync } from 'node:fs';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { homedir } from 'node:os';
|
||||
@@ -372,17 +373,24 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
const s = this.live.get(id);
|
||||
if (!s || s.exited) return false;
|
||||
try {
|
||||
process.kill(s.proc.pid, 'SIGTERM');
|
||||
// Windows n'a pas de signaux : node-pty traduit `kill()` en fermeture de la pseudo-console, ce
|
||||
// qui laisse échapper les petits-enfants (un `npm run dev` lancé dans le shell). Le SIGKILL
|
||||
// différé est donc remplacé par un `taskkill /T` qui tue l'ARBRE complet.
|
||||
if (process.platform === 'win32') s.proc.kill();
|
||||
else process.kill(s.proc.pid, 'SIGTERM');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
s.killTimer ??= setTimeout(() => {
|
||||
if (!s.exited) {
|
||||
try {
|
||||
if (s.exited) return;
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
execFile('taskkill.exe', ['/PID', String(s.proc.pid), '/T', '/F'], () => {});
|
||||
} else {
|
||||
process.kill(s.proc.pid, 'SIGKILL');
|
||||
} catch {
|
||||
/* déjà mort */
|
||||
}
|
||||
} catch {
|
||||
/* déjà mort */
|
||||
}
|
||||
}, KILL_GRACE_MS);
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Adaptateur serveur de la corrélation session ↔ worktree : la RÈGLE vit dans `@arboretum/shared`
|
||||
// (`path-match.ts`, partagée avec le front et l'extension) ; ici on se contente de normaliser les
|
||||
// chemins avec `resolve()` avant de la lui passer, puisque le serveur manipule des chemins venant de
|
||||
// git, de la base et de requêtes (fins de slash, `..`, chemins relatifs au cwd du process).
|
||||
import { resolve } from 'node:path';
|
||||
import {
|
||||
containsPath as sharedContains,
|
||||
findWorktreeForCwd as sharedFind,
|
||||
sessionBelongsToWorktree as sharedBelongs,
|
||||
} from '@arboretum/shared';
|
||||
|
||||
export function containsPath(parent: string, child: string): boolean {
|
||||
return sharedContains(resolve(parent), resolve(child));
|
||||
}
|
||||
|
||||
export function sessionBelongsToWorktree(
|
||||
session: { cwd: string; addedDirs?: string[] },
|
||||
worktreePath: string,
|
||||
others: string[] = [],
|
||||
): boolean {
|
||||
return sharedBelongs(
|
||||
{ cwd: resolve(session.cwd), ...(session.addedDirs ? { addedDirs: session.addedDirs.map((d) => resolve(d)) } : {}) },
|
||||
resolve(worktreePath),
|
||||
others.map((p) => resolve(p)),
|
||||
);
|
||||
}
|
||||
|
||||
export function findWorktreeForCwd<T extends { path: string }>(cwd: string, worktrees: T[]): T | null {
|
||||
// On résout une copie pour la comparaison, puis on renvoie l'objet d'origine (le chemin brut est ce
|
||||
// que le reste du code attend, notamment les clés du watcher FS).
|
||||
const normalized = worktrees.map((w) => ({ w, path: resolve(w.path) }));
|
||||
return sharedFind(resolve(cwd), normalized)?.w ?? null;
|
||||
}
|
||||
@@ -28,6 +28,8 @@ import {
|
||||
amendCommit,
|
||||
cleanFiles,
|
||||
commitAll,
|
||||
commitDiff,
|
||||
commitLog,
|
||||
commitStaged,
|
||||
defaultBranch,
|
||||
fetchRemote,
|
||||
@@ -38,6 +40,7 @@ import {
|
||||
isSafeRelativePath,
|
||||
isUnpushed,
|
||||
isValidBranchName,
|
||||
isValidCommitish,
|
||||
listBranches,
|
||||
listChanges,
|
||||
listWorktrees,
|
||||
@@ -53,7 +56,8 @@ import {
|
||||
type ParsedWorktree,
|
||||
} from './git.js';
|
||||
import type { FsWatcherService } from './fs-watcher.js';
|
||||
import type { FileChange, FileDiffResponse } from '@arboretum/shared';
|
||||
import { findWorktreeForCwd, sessionBelongsToWorktree } from './session-match.js';
|
||||
import type { CommitDiffResponse, FileChange, FileDiffResponse, WorktreeLogResponse } from '@arboretum/shared';
|
||||
|
||||
const FACTS_TTL_MS = 2500;
|
||||
const HOOK_TIMEOUT_MS = 5 * 60_000;
|
||||
@@ -153,6 +157,8 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
private readonly locks = new Map<string, Promise<unknown>>();
|
||||
/** Scan de découverte en cours : coalesce boot + bouton + périodique sur un seul scan. */
|
||||
private scanInFlight: Promise<DiscoverReposResponse> | null = null;
|
||||
/** Worktree épinglé au watcher FS pour chaque session vivante (clé = id de session). */
|
||||
private readonly pinnedSessions = new Map<string, { repoId: string; path: string }>();
|
||||
|
||||
constructor(
|
||||
private readonly db: Db,
|
||||
@@ -170,6 +176,46 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
if (row) void this.emitWorktree(row, path).catch(() => {});
|
||||
this.emit('worktree_changes', { repoId, path });
|
||||
});
|
||||
// Une session vivante rend son worktree « actif » : on épingle son watcher FS pour que les
|
||||
// compteurs git restent temps réel même si aucun client ne regarde ce worktree. C'est le cas
|
||||
// nominal du travail en CLI : l'agent écrit dans un worktree de feature pendant qu'on regarde
|
||||
// ailleurs. Sans cette épingle, le point « modifié » de l'arbre restait figé sur le dernier
|
||||
// listing REST.
|
||||
this.ptyManager.on('session_update', (s) => {
|
||||
void this.syncSessionPin(s).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
/** Épingle (session vivante) ou libère (session terminée) le watcher FS du worktree d'une session. */
|
||||
private async syncSessionPin(s: SessionSummary): Promise<void> {
|
||||
if (!this.fsWatcher) return;
|
||||
const pinned = this.pinnedSessions.get(s.id);
|
||||
if (!s.live) {
|
||||
if (!pinned) return;
|
||||
this.pinnedSessions.delete(s.id);
|
||||
this.fsWatcher.unpinSession(pinned.repoId, pinned.path);
|
||||
return;
|
||||
}
|
||||
if (pinned) return; // déjà épinglé : `session_update` bat au rythme de l'activité
|
||||
const target = await this.resolveWorktreeForCwd(s.cwd);
|
||||
if (!target) return; // session hors de tout repo enregistré
|
||||
this.pinnedSessions.set(s.id, target);
|
||||
this.fsWatcher.pinSession(target.repoId, target.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Worktree connu (tous repos non masqués) contenant ce cwd, le plus spécifique. Un worktree lié vit
|
||||
* souvent HORS de l'arborescence de son repo : on ne peut donc pas écarter un repo sur son seul
|
||||
* chemin, il faut ses worktrees réels (servis par le cache court partagé avec les listings).
|
||||
*/
|
||||
private async resolveWorktreeForCwd(cwd: string): Promise<{ repoId: string; path: string } | null> {
|
||||
const rows = this.db.prepare('SELECT id, path FROM repos WHERE hidden = 0').all() as unknown as Array<{ id: string; path: string }>;
|
||||
const candidates: Array<{ repoId: string; path: string }> = [];
|
||||
for (const row of rows) {
|
||||
const facts = await this.repoFacts(row).catch(() => []);
|
||||
for (const f of facts) candidates.push({ repoId: row.id, path: f.w.path });
|
||||
}
|
||||
return findWorktreeForCwd(cwd, candidates);
|
||||
}
|
||||
|
||||
// ---- repos ----
|
||||
@@ -336,20 +382,28 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
// ---- worktrees ----
|
||||
|
||||
/**
|
||||
* Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree.
|
||||
* Sessions (managées + découvertes) rattachées à ce worktree : cwd dans le worktree (y compris un
|
||||
* sous-répertoire de « Démarrer le projet ») ou worktree relié en `--add-dir` par une session de
|
||||
* groupe · voir `sessionBelongsToWorktree`. `siblings` = les autres worktrees du repo, indispensables
|
||||
* pour qu'un worktree imbriqué ne voie pas ses sessions attribuées aussi au checkout principal.
|
||||
* Les sessions explicitement masquées (`hidden`) sont exclues, cohérent avec `/api/v1/sessions`
|
||||
* (sans quoi le masquage était ignoré dans les fiches worktree). Le tri managées/externes est laissé
|
||||
* au client (interrupteur « afficher les externes »), qui dispose du champ `source`. La garde de
|
||||
* suppression réclame en revanche TOUTES les sessions vivantes (`includeHidden`) pour rester sûre.
|
||||
*/
|
||||
private sessionsForCwd(path: string, opts?: { includeHidden?: boolean }): SessionSummary[] {
|
||||
const rp = resolve(path);
|
||||
private sessionsForCwd(path: string, opts?: { includeHidden?: boolean; siblings?: string[] }): SessionSummary[] {
|
||||
return mergeSessions(this.ptyManager.list(), this.discovery.list())
|
||||
.filter((s) => resolve(s.cwd) === rp)
|
||||
.filter((s) => sessionBelongsToWorktree(s, path, opts?.siblings ?? []))
|
||||
.filter((s) => opts?.includeHidden || !s.hidden);
|
||||
}
|
||||
|
||||
private toSummary(repoId: string, repoPath: string, w: ParsedWorktree, status: WorktreeGitStatus): WorktreeSummary {
|
||||
private toSummary(
|
||||
repoId: string,
|
||||
repoPath: string,
|
||||
w: ParsedWorktree,
|
||||
status: WorktreeGitStatus,
|
||||
siblings: string[] = [],
|
||||
): WorktreeSummary {
|
||||
return {
|
||||
repoId,
|
||||
path: w.path,
|
||||
@@ -360,11 +414,11 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
prunable: w.prunable,
|
||||
isMain: resolve(w.path) === resolve(repoPath),
|
||||
git: status,
|
||||
sessions: this.sessionsForCwd(w.path),
|
||||
sessions: this.sessionsForCwd(w.path, { siblings }),
|
||||
};
|
||||
}
|
||||
|
||||
private async repoFacts(row: RepoRow, noCache = false): Promise<Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>> {
|
||||
private async repoFacts(row: { id: string; path: string }, noCache = false): Promise<Array<{ w: ParsedWorktree; status: WorktreeGitStatus }>> {
|
||||
const cached = this.factsCache.get(row.id);
|
||||
if (!noCache && cached && Date.now() - cached.at < FACTS_TTL_MS) return cached.facts;
|
||||
const parsed = (await listWorktrees(row.path)).filter((w) => !w.bare);
|
||||
@@ -377,7 +431,8 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
const row = this.getRepoRow(repoId);
|
||||
if (!row) return [];
|
||||
const facts = await this.repoFacts(row, noCache);
|
||||
return facts.map(({ w, status }) => this.toSummary(row.id, row.path, w, status));
|
||||
const paths = facts.map(({ w }) => w.path);
|
||||
return facts.map(({ w, status }) => this.toSummary(row.id, row.path, w, status, paths));
|
||||
}
|
||||
|
||||
async listAllWorktrees(): Promise<WorktreeSummary[]> {
|
||||
@@ -411,9 +466,19 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
}
|
||||
|
||||
private async emitWorktree(row: RepoRow, path: string): Promise<WorktreeSummary | null> {
|
||||
const w = await this.findWorktree(row, path);
|
||||
// On liste tous les worktrees du repo (et pas seulement celui visé) pour désambiguïser la
|
||||
// corrélation des sessions entre worktrees imbriqués (cf. sessionsForCwd).
|
||||
const all = (await listWorktrees(row.path)).filter((w) => !w.bare);
|
||||
const rp = resolve(path);
|
||||
const w = all.find((x) => resolve(x.path) === rp);
|
||||
if (!w) return null;
|
||||
const summary = this.toSummary(row.id, row.path, w, await worktreeStatus(w.path));
|
||||
const summary = this.toSummary(
|
||||
row.id,
|
||||
row.path,
|
||||
w,
|
||||
await worktreeStatus(w.path),
|
||||
all.map((x) => x.path),
|
||||
);
|
||||
this.emit('worktree_update', { repoId: row.id, worktree: summary });
|
||||
return summary;
|
||||
}
|
||||
@@ -520,6 +585,25 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
return listChanges(w.path);
|
||||
}
|
||||
|
||||
/** Historique de la branche du worktree (lecture, hors lock) : « ce qui a déjà été acté ». */
|
||||
async getWorktreeLog(repoId: string, path: string, opts: { limit?: number; skip?: number }): Promise<WorktreeLogResponse> {
|
||||
const { w } = await this.requireWorktree(repoId, path);
|
||||
const { commits, unpushedCount, hasUpstream } = await commitLog(w.path, opts);
|
||||
return { repoId, path: w.path, commits, unpushedCount, hasUpstream };
|
||||
}
|
||||
|
||||
/** Diff unifié complet d'un commit (lecture, hors lock). Le hash est validé par la couche git. */
|
||||
async getCommitDiff(repoId: string, path: string, hash: string): Promise<CommitDiffResponse> {
|
||||
const { w } = await this.requireWorktree(repoId, path);
|
||||
if (!isValidCommitish(hash)) throw httpError(400, 'BAD_COMMIT', 'Invalid commit hash');
|
||||
try {
|
||||
const d = await commitDiff(w.path, hash);
|
||||
return { path: w.path, commit: hash, binary: d.binary, tooLarge: d.tooLarge, diff: d.diff };
|
||||
} catch (err) {
|
||||
throw httpError(404, 'NOT_FOUND', (err as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Diff unifié d'un fichier (détecte untracked → `git diff --no-index`). Lecture, hors lock. */
|
||||
async getFileDiff(repoId: string, path: string, file: string, staged: boolean): Promise<FileDiffResponse> {
|
||||
const { w } = await this.requireWorktree(repoId, path);
|
||||
@@ -813,8 +897,10 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
const w = await this.findWorktree(row, path);
|
||||
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'Cannot remove the main worktree');
|
||||
// garde-fou : une session vivante tourne dans ce worktree → exiger une confirmation explicite.
|
||||
if (!force && this.sessionsForCwd(w.path, { includeHidden: true }).some((s) => s.live)) {
|
||||
// garde-fou : une session vivante tourne dans ce worktree (ou dans un de ses sous-répertoires, ou
|
||||
// le relie en `--add-dir`) → exiger une confirmation explicite.
|
||||
const siblings = (await listWorktrees(row.path)).map((x) => x.path);
|
||||
if (!force && this.sessionsForCwd(w.path, { includeHidden: true, siblings }).some((s) => s.live)) {
|
||||
throw httpError(409, 'SESSION_LIVE_IN_WORKTREE', 'A live session runs in this worktree: pass force to delete anyway');
|
||||
}
|
||||
return this.withLock(repoId, async () => {
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type {
|
||||
WorktreeChangesResponse,
|
||||
CommitDiffResponse,
|
||||
FileDiffResponse,
|
||||
WorktreeLogResponse,
|
||||
WorktreeFilesRequest,
|
||||
DiscardFilesRequest,
|
||||
FetchWorktreeRequest,
|
||||
@@ -33,12 +35,48 @@ export function registerGitRoutes(app: FastifyInstance, wt: WorktreeManager, db:
|
||||
}
|
||||
});
|
||||
|
||||
// Diff unifié d'un fichier (staged ou non ; untracked détecté côté manager).
|
||||
// Historique de la branche du worktree (« ce qui a déjà été acté », + ce qui n'est pas poussé).
|
||||
app.get('/api/v1/repos/:id/worktrees/log', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const q = req.query as { path?: string; limit?: string; skip?: string };
|
||||
if (typeof q.path !== 'string' || q.path === '') {
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||
}
|
||||
// Bornes appliquées côté couche git (limite dure) : ici on se contente de convertir.
|
||||
const limit = q.limit !== undefined ? Number(q.limit) : undefined;
|
||||
const skip = q.skip !== undefined ? Number(q.skip) : undefined;
|
||||
if ((limit !== undefined && !Number.isFinite(limit)) || (skip !== undefined && !Number.isFinite(skip))) {
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'limit and skip must be numbers' } });
|
||||
}
|
||||
try {
|
||||
const res = await wt.getWorktreeLog(id, q.path, {
|
||||
...(limit !== undefined ? { limit } : {}),
|
||||
...(skip !== undefined ? { skip } : {}),
|
||||
});
|
||||
return reply.send(res satisfies WorktreeLogResponse);
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
}
|
||||
});
|
||||
|
||||
// Diff unifié : d'un fichier (`file`), ou d'un commit entier (`commit`). Les deux formes renvoient un
|
||||
// diff unifié, donc le même parseur et la même vue côté client.
|
||||
app.get('/api/v1/repos/:id/worktrees/diff', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const q = req.query as { path?: string; file?: string; staged?: string };
|
||||
if (typeof q.path !== 'string' || q.path === '' || typeof q.file !== 'string' || q.file === '') {
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and file are required' } });
|
||||
const q = req.query as { path?: string; file?: string; staged?: string; commit?: string };
|
||||
if (typeof q.path !== 'string' || q.path === '') {
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||
}
|
||||
if (typeof q.commit === 'string' && q.commit !== '') {
|
||||
try {
|
||||
const res = await wt.getCommitDiff(id, q.path, q.commit);
|
||||
return reply.send(res satisfies CommitDiffResponse);
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
}
|
||||
}
|
||||
if (typeof q.file !== 'string' || q.file === '') {
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'file or commit is required' } });
|
||||
}
|
||||
const staged = q.staged === '1' || q.staged === 'true';
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user