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

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:
2026-08-04 13:02:11 +02:00
parent a7e04278fd
commit 63f2697745
127 changed files with 4232 additions and 577 deletions
+55
View File
@@ -0,0 +1,55 @@
# Changelog
Notable changes to the Arboretum desktop app (`packages/desktop`). The daemon and the VS Code
extension keep their own changelogs in `packages/server/CHANGELOG.md` and
`packages/vscode/CHANGELOG.md`.
## 0.2.0
Distribution release: the Linux launcher icon finally shows up, Windows becomes a first-class target,
and the embedded runtime loses a third of its weight.
- **Launcher icon fixed (Linux).** Earlier packages installed a single 895×895 icon. That size is not
declared in `hicolor/index.theme`, so by the freedesktop spec every desktop environment ignored it and
the launcher fell back to a generic icon. The build now generates the standard set (16 → 512) plus a
proper `.ico` for Windows, and forces `executableName: arboretum` (the scoped package name was
producing `@arboretumdesktop` as binary, `.desktop` file and icon name).
- **Package metadata.** A non-empty short description in `apt show` (`deb.synopsis` was missing),
`Section: devel` instead of `default`, a single-line `Comment` in the desktop entry (it was multi-line,
hence invalid), plus `GenericName` and `Keywords` for search.
- **Windows.** Build scripts run on a Windows host again (`npm`/`npx` are `.cmd` shims that
`execFileSync` cannot resolve; the Node extraction used `unzip` and `bash -c cp/rm`, none of which
exist there). The daemon side gained what it needed to actually work: `where.exe` to find the Claude
CLI, PowerShell as the launch shell, a `.cmd` askpass so HTTPS clone/push with a token works, and
`taskkill /T` so stopping a terminal takes its whole process tree down. CI has a `windows-latest` job,
enabled by the `ENABLE_WINDOWS_BUILD` repository variable, see `docs/CI_RUNNERS.md`.
- **Auto-update repaired.** Shipped binaries point at a `desktop-latest` release that never existed, so
no client could ever see an update. The release workflow now recreates that floating release on every
version and attaches the `latest*.yml` files and installers to it, with `.blockmap`s for differential
updates and `SHA256SUMS`.
- **Smaller download.** The bundled Node runtime is pruned to the binary and its licence (no headers, no
docs, no `npm`/`corepack`): ~205 MB → ~118 MB. Nothing at runtime used them, the daemon's dependencies
being installed at build time.
- **macOS integration.** An application menu (without it ⌘C / ⌘V / ⌘A were not bound anywhere in the
app), `app.on('activate')` so the Dock icon brings back a hidden window, and a monochrome template tray
icon that follows the menu-bar theme.
- **PATH enrichment on Windows.** `%LOCALAPPDATA%\Programs` and `%APPDATA%\npm` are added to the daemon's
PATH, where the Claude CLI and global npm binaries live (this was POSIX-only).
## 0.1.3
Ships the 3.3.0 daemon ("Start the project": launch commands and multi-terminal boot).
## 0.1.2
Ships the 3.2.0 daemon (Emerald visual overhaul, light and dark themes).
## 0.1.1
- Fixed the missing window/launcher logo under Debian and Wayland by pinning the runtime app id
(`app.setName('Arboretum')`) to the `StartupWMClass` written in the desktop entry.
## 0.1.0
First desktop release: an Electron shell that runs the daemon as a child process and opens its UI
already authenticated, with a bundled Node runtime, a tray icon, launch-at-login and auto-update.
+51 -13
View File
@@ -15,7 +15,8 @@ not by the main `npm run build`.
2. The daemon mints a fresh token and writes `{token, url}` on file descriptor 3 (private stdio pipe).
3. The shell posts that token to `/api/v1/auth/login` from the window's session (server to server),
which drops the `arb_session` cookie into the session jar, then loads the SPA on `127.0.0.1`.
4. On quit, the daemon child gets `SIGTERM` (then `SIGKILL` after a grace delay).
4. On quit, the daemon child is asked to stop (`SIGTERM` on POSIX, `taskkill /T` on Windows, which
Windows requires to take the whole process tree down rather than leaving PTY grandchildren behind).
A standalone Node runtime (pinned, >= 22.16) is bundled instead of reusing Electron's Node, so
`node:sqlite` works without a flag and the `node-pty` prebuild keeps the `node.` ABI prefix.
@@ -56,24 +57,61 @@ Fully supported. `dist:linux` runs on a Linux host or the Gitea CI runner.
### Windows
Build on a Windows host (recommended): the `node-pty` win32 native binary and the installer
(`makensis`) are most reliable there. Cross-building from Linux via Wine is a best-effort fallback.
The app uses ConPTY (Windows 10 1809+). The installer is not code-signed yet, so SmartScreen shows
**Must be built on a Windows host.** Cross-building from Linux (including via Wine) does not work, and
the option has been removed from this document to stop people losing time on it:
- `node-pty`'s `check-prebuild.js` exits successfully as soon as the *host* binary exists, so
`prebuild-install` never runs and no win32 binary is fetched (its published tarball only ships
`prebuilds/linux-*`);
- its `post-install.js` copies `conpty.dll` and `OpenConsole.exe` **only when the build platform is
win32**. Without them there is no ConPTY, hence no terminal at all.
In CI this is a dedicated job on a `windows-latest` runner, enabled by the `ENABLE_WINDOWS_BUILD`
repository variable. Full procedure to register such a runner: [`docs/CI_RUNNERS.md`](../../docs/CI_RUNNERS.md).
The app requires Windows 10 1809+ (ConPTY). The installer is not code-signed, so SmartScreen shows
"unknown publisher": choose "More info" then "Run anyway".
### macOS (best-effort)
Build on a Mac (`dmg`/`zip` cannot be produced elsewhere). The app is **not** signed or notarized,
so Gatekeeper blocks the first launch: right-click the app then "Open", or run
`xattr -dr com.apple.quarantine /Applications/Arboretum.app`.
Build on a Mac (`dmg`/`zip` cannot be produced elsewhere); there is no macOS runner, so it is a manual
step. The app is **not** signed or notarized, so Gatekeeper blocks the first launch: right-click the app
then "Open", or run `xattr -dr com.apple.quarantine /Applications/Arboretum.app`.
## What the shell adds beyond the window
- **Tray icon** (`src/main/tray.ts`): open the window, toggle launch-at-login, quit. On macOS it uses a
monochrome *template* image so it follows the menu-bar theme.
- **Application menu** (`src/main/app-menu.ts`): required on macOS, where without it ⌘C / ⌘V / ⌘A are not
bound anywhere in the app. Closing the window hides it; `app.on('activate')` brings it back from the Dock.
- **Launch at login** (`src/main/autostart.ts`): a `.desktop` file under `~/.config/autostart` on Linux,
`app.setLoginItemSettings` on Windows/macOS.
- **Auto-update** (`src/main/updater.ts`): see below.
- **PATH enrichment** (`src/main/env.ts`): a GUI app starts with a minimal PATH. On POSIX we add
`/usr/local/bin`, `/opt/homebrew/bin`, `~/.local/bin`; on Windows `%LOCALAPPDATA%\Programs` and
`%APPDATA%\npm`, where the Claude CLI and global npm binaries actually live.
## Auto-update
electron-builder emits `latest*.yml` next to the artifacts; `electron-updater` (wired in a later
change) points at the Gitea release assets. Auto-update works for Windows (NSIS) and Linux
(AppImage); macOS updates are manual while the app is unsigned.
electron-builder emits `latest*.yml` next to the artifacts and `electron-updater` reads them from a
**floating `desktop-latest` release** on Gitea, which the release workflow recreates on every version
(that URL is baked into shipped binaries, so it must always exist). Auto-update covers Windows (NSIS)
and Linux (AppImage); macOS updates are manual while the app is unsigned.
## Icon
## Bundled Node runtime
`resources/icon.png` (square, >= 512px) is the single source; electron-builder derives every
platform icon from it.
`scripts/fetch-node.mjs` downloads a pinned Node (SHA256 verified) and **prunes it** to the binary and
its licence: headers, docs and `npm`/`corepack` are removed, since the daemon's dependencies are
installed at build time, never at runtime. That takes the embedded runtime from ~205 MB to ~118 MB.
## Icons
Generated by `python3 brand/build-assets.py` from the source logo, into `resources/`:
- `icons/{16,24,32,48,64,128,256,512}x*.png` : the Linux set, at **standard hicolor sizes**. This is not
cosmetic: with a single non-standard size (the old 895×895), the directory is not declared in
`hicolor/index.theme` and the freedesktop spec makes desktops ignore it, so the launcher showed no
icon at all.
- `icon.png` (1024) : macOS source and generic fallback.
- `icon.ico` : Windows (NSIS installer and window).
- `trayTemplate.png` (+`@2x`) : monochrome macOS menu-bar icon.
+49 -6
View File
@@ -21,27 +21,59 @@ extraResources:
to: node
- from: resources/icon.png
to: icon.png
- from: resources/trayTemplate.png
to: trayTemplate.png
- from: resources/trayTemplate@2x.png
to: trayTemplate@2x.png
# Icône : electron-builder dérive toutes les tailles/formats par OS depuis resources/icon.png
# (buildResources), pas besoin de .ico/.icns séparés.
# Icônes : générées par `python3 brand/build-assets.py` depuis le logo source.
# - `resources/icons/` : jeu Linux aux TAILLES STANDARD hicolor (16→512). Indispensable : sans lui,
# electron-builder installe l'unique taille du PNG source (895x895), or `hicolor/index.theme` ne
# déclare pas ce répertoire, donc la spécification freedesktop l'ignore et AUCUN logo n'apparaît
# au lanceur (c'était le bug du .deb 0.1.x).
# - `resources/icon.png` (1024) : source macOS et dérivations.
# - `resources/icon.ico` : Windows (installeur NSIS + fenêtre).
linux:
target: [AppImage, deb]
category: Development
icon: resources/icons
# `executableName` explicite : sinon electron-builder le dérive du `name` SCOPÉ du package
# (@arboretum/desktop → « @arboretumdesktop »), qui se retrouvait dans /usr/bin, le .desktop et son
# `Icon=` · un nom d'icône commençant par « @ » n'est pas résoluble.
executableName: arboretum
artifactName: ${productName}-${version}-${arch}.${ext}
synopsis: Self-hosted multi-project AI IDE for git worktrees
# Entrée .desktop (forme plate, mergée telle quelle par electron-builder 25). StartupWMClass DOIT
# correspondre à l'app_id runtime (posé par app.setName('Arboretum') dans src/main/main.ts) pour
# que GNOME/Wayland associe la fenêtre au lanceur et affiche le logo. Redondant avec le défaut
# (productName) mais explicite et robuste à un futur changement de productName.
desktop:
StartupWMClass: Arboretum
# Note : le .deb installe l'icône et rafraîchit le cache (postinst electron-builder). L'AppImage,
# lui, n'installe aucun .desktop sans intégration (appimaged) : sur Debian, préférer le .deb.
GenericName: AI IDE for git worktrees
Keywords: git;worktree;claude;ide;terminal;
# Pas de `Comment` ici : electron-builder l'écrase systématiquement après la surcharge
# (LinuxTargetHelper : desktopMeta.Comment = deb.description || package.json description). C'est
# donc la description du package.json qui fait foi, et elle DOIT rester sur une seule ligne : un
# texte multi-lignes produirait une entrée .desktop invalide (lignes suivantes lues comme clés).
# Note : avec des tailles standard, GTK/KDE résolvent l'icône même sans cache d'icônes rafraîchi
# (le postinst d'electron-builder n'appelle pas gtk-update-icon-cache). L'AppImage, lui, n'installe
# aucun .desktop sans intégration (appimaged) : sur Debian, préférer le .deb.
deb:
# git est requis pour les operations de worktree ; claude n'est pas dans les depots (documente).
depends: [git]
# Mainteneur .deb explicite (electron-builder l'exige ; sinon derive de author.email du package.json).
maintainer: Johan LEROY <contact@johanleroy.fr>
# `synopsis` alimente la description COURTE du paquet : sans lui, `apt show` affichait une ligne
# vide (electron-builder concatène `synopsis || ''` puis la description longue).
# `synopsis` = description COURTE du paquet : sans elle, `apt show` affichait une ligne vide
# (electron-builder concatène `synopsis || ''` puis la description longue). La description longue
# reste celle du package.json, volontairement sur une seule ligne (cf. note sur Comment ci-dessus).
synopsis: Self-hosted multi-project AI IDE for git worktrees
# electron-builder nomme ce champ `packageCategory` (et non `section`) : il alimente le champ
# Section: du paquet, qui valait « default » jusqu'ici.
packageCategory: devel
priority: optional
win:
target:
@@ -49,22 +81,33 @@ win:
arch: [x64]
- target: portable
arch: [x64]
icon: resources/icon.ico
# Affiché par SmartScreen et dans les métadonnées de l'exécutable. Le binaire n'est PAS signé :
# SmartScreen montrera « éditeur inconnu » (documenté dans le README).
publisherName: Johan LEROY
artifactName: ${productName}-${version}-${arch}.${ext}
nsis:
oneClick: false
perMachine: false
allowToChangeInstallationDirectory: true
shortcutName: Arboretum
uninstallDisplayName: Arboretum ${version}
createDesktopShortcut: true
license: ../../LICENSE
mac:
target: [dmg, zip]
icon: resources/icon.png
category: public.app-category.developer-tools
# macOS best-effort : non signe (documente : clic droit -> Ouvrir, ou xattr -dr com.apple.quarantine)
identity: null
hardenedRuntime: false
# Auto-update (electron-updater, cable en C5) : provider generic pointant sur les assets de release
# Gitea. Genere latest*.yml a cote des artefacts.
# Auto-update (electron-updater) : provider generic pointant sur un tag FLOTTANT `desktop-latest`,
# que la CI recrée à chaque release en y attachant les installeurs et les `latest*.yml`. Ce tag doit
# exister, sinon l'updater reçoit un 404 (c'était le cas jusqu'en 0.1.3) : voir
# .gitea/workflows/desktop-release.yml, étape « Publish floating desktop-latest release ».
publish:
provider: generic
url: https://git.lidge.fr/johanleroy/arboretum/releases/download/desktop-latest
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@arboretum/desktop",
"version": "0.1.3",
"version": "0.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@arboretum/desktop",
"version": "0.1.3",
"version": "0.2.0",
"license": "MIT",
"devDependencies": {
"@types/node": "^22.10.0",
+18 -2
View File
@@ -1,9 +1,25 @@
{
"name": "@arboretum/desktop",
"private": true,
"version": "0.1.3",
"description": "Arboretum desktop app: Electron shell that runs the daemon and shows its web UI",
"version": "0.2.0",
"description": "Self-hosted multi-project AI IDE for git worktrees and Claude Code sessions",
"homepage": "https://git-arboretum.com",
"repository": {
"type": "git",
"url": "git+https://git.lidge.fr/johanleroy/arboretum.git"
},
"bugs": {
"url": "https://git.lidge.fr/johanleroy/arboretum/issues"
},
"keywords": [
"arboretum",
"git",
"worktree",
"claude",
"ide",
"electron",
"desktop"
],
"license": "MIT",
"author": {
"name": "Johan LEROY",
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 184 KiB

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 650 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 433 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+42 -6
View File
@@ -2,7 +2,7 @@
// SHA256. Le daemon tourne SUR ce Node (pas celui d'Electron) pour garantir node:sqlite sans flag
// et l'ABI node-pty attendue (prefixe `node.`). Options : --platform / --arch (défaut : hôte).
import { execFileSync } from 'node:child_process';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { cpSync, existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -41,9 +41,45 @@ if (expected !== actual) throw new Error(`SHA256 mismatch pour ${name}.${ext}`);
const archive = join(BUILD, `${name}.${ext}`);
writeFileSync(archive, tarball);
if (ext === 'zip') execFileSync('unzip', ['-q', archive, '-d', BUILD], { stdio: 'inherit' });
else execFileSync('tar', ['-xJf', archive, '-C', BUILD], { stdio: 'inherit' });
// aplatir node-vX-os-arch/ -> build/node/
execFileSync('bash', ['-c', `cp -R "${join(BUILD, name)}/." "${NODE_DIR}/" && rm -rf "${join(BUILD, name)}" "${archive}"`], { stdio: 'inherit' });
// `tar` de Windows 10+ (bsdtar) lit aussi les .zip : une seule commande pour les trois plateformes,
// là où `unzip` n'existe pas sur un Windows standard.
execFileSync('tar', [ext === 'zip' ? '-xf' : '-xJf', archive, '-C', BUILD], { stdio: 'inherit' });
console.log(`fetch-node: Node ${NODE_VERSION} (${OS}-${arch}) -> build/node`);
// Aplatir node-vX-os-arch/ -> build/node/ avec l'API Node (l'ancien `bash -c 'cp -R … && rm -rf …'`
// rendait ce script inexécutable sur Windows, où il n'y a ni bash, ni cp, ni rm).
const extracted = join(BUILD, name);
cpSync(extracted, NODE_DIR, { recursive: true });
rmSync(extracted, { recursive: true, force: true });
rmSync(archive, { force: true });
// --- élagage ---------------------------------------------------------------------------------
// On n'embarque QUE de quoi exécuter le daemon. La distribution complète pèse ~205 Mo, dont l'essentiel
// est inutile ici : en-têtes de compilation, docs, et surtout npm/corepack (le `npm install --omit=dev`
// du daemon a lieu au BUILD, jamais au runtime).
const PRUNE = ['include', 'share', 'lib', 'CHANGELOG.md', 'README.md'];
for (const rel of PRUNE) rmSync(join(NODE_DIR, rel), { recursive: true, force: true });
// les shims npm/npx/corepack (POSIX : bin/, Windows : racine)
for (const shim of ['npm', 'npx', 'corepack', 'npm.cmd', 'npx.cmd', 'corepack.cmd', 'npm.ps1', 'npx.ps1', 'corepack.ps1']) {
rmSync(join(NODE_DIR, 'bin', shim), { force: true });
rmSync(join(NODE_DIR, shim), { force: true });
}
// Garde-fou : le binaire doit avoir survécu à l'élagage.
const nodeBin = platform === 'win32' ? join(NODE_DIR, 'node.exe') : join(NODE_DIR, 'bin', 'node');
if (!existsSync(nodeBin)) throw new Error(`binaire Node introuvable apres extraction: ${nodeBin}`);
console.log(`fetch-node: Node ${NODE_VERSION} (${OS}-${arch}) -> build/node (${duMb(NODE_DIR)} Mo)`);
/** Taille approximative d'un dossier, en Mo (diagnostic de l'élagage). */
function duMb(dir) {
let total = 0;
const walk = (d) => {
for (const entry of readdirSync(d, { withFileTypes: true })) {
const p = join(d, entry.name);
if (entry.isDirectory()) walk(p);
else if (entry.isFile()) total += statSync(p).size;
}
};
walk(dir);
return Math.round(total / 1024 / 1024);
}
+5 -1
View File
@@ -20,8 +20,12 @@ const arg = (name) => args.find((a) => a.startsWith(`--${name}=`))?.split('=')[1
const platform = arg('platform');
const arch = arg('arch');
// Sur Windows, `npm`/`npx` sont des shims `.cmd` : `execFileSync` ne les résout pas (ENOENT), il faut
// leur nom complet. Sans ça, tout le chemin de build documenté échouait sur un hôte Windows.
const winShim = (cmd) => (process.platform === 'win32' && (cmd === 'npm' || cmd === 'npx') ? `${cmd}.cmd` : cmd);
const run = (cmd, cmdArgs, cwd, env) =>
execFileSync(cmd, cmdArgs, { cwd, stdio: 'inherit', env: { ...process.env, ...env } });
execFileSync(winShim(cmd), cmdArgs, { cwd, stdio: 'inherit', env: { ...process.env, ...env } });
rmSync(SERVER_DIR, { recursive: true, force: true });
mkdirSync(SERVER_DIR, { recursive: true });
+82
View File
@@ -0,0 +1,82 @@
import { app, Menu, shell, type MenuItemConstructorOptions } from 'electron';
/**
* Menu applicatif. Sur macOS il n'est PAS optionnel : sans lui, aucun raccourci d'édition n'est
* enregistré et ⌘C / ⌘V / ⌘A / ⌘Z ne fonctionnent nulle part dans l'app (y compris dans les terminaux
* et l'éditeur). Sur Linux/Windows on garde un menu minimal, masqué par défaut (`setMenuBarVisibility`
* côté fenêtre) mais qui enregistre quand même les accélérateurs standard.
*/
export function installAppMenu(opts: { url: string; onQuit: () => void }): void {
const isMac = process.platform === 'darwin';
const macAppMenu: MenuItemConstructorOptions[] = isMac
? [
{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ label: 'Quit Arboretum', accelerator: 'Command+Q', click: opts.onQuit },
],
},
]
: [];
const template: MenuItemConstructorOptions[] = [
...macAppMenu,
{
label: 'File',
submenu: isMac ? [{ role: 'close' }] : [{ label: 'Quit', accelerator: 'Ctrl+Q', click: opts.onQuit }],
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'selectAll' },
],
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' },
{ role: 'toggleDevTools' },
],
},
{
label: 'Window',
submenu: isMac ? [{ role: 'minimize' }, { role: 'zoom' }, { type: 'separator' }, { role: 'front' }] : [{ role: 'minimize' }],
},
{
role: 'help',
submenu: [
{ label: 'Open in browser', click: () => void shell.openExternal(opts.url) },
{ label: 'Website', click: () => void shell.openExternal('https://git-arboretum.com') },
],
},
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
app.setAboutPanelOptions({
applicationName: 'Arboretum',
applicationVersion: app.getVersion(),
copyright: 'Copyright © 2026 Johan Leroy',
website: 'https://git-arboretum.com',
});
}
+22 -2
View File
@@ -6,10 +6,30 @@ import { homedir } from 'node:os';
// `claude`. Le réglage `claude_bin_path` (UI) reste le filet de secours.
export function buildChildEnv(extra: Record<string, string>): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env, ...extra };
if (process.platform !== 'win32') {
const extras = ['/usr/local/bin', '/opt/homebrew/bin', join(homedir(), '.local', 'bin'), '/usr/bin', '/bin'];
const extras = pathExtras(process.platform, env);
if (extras.length > 0) {
const current = env.PATH ? env.PATH.split(delimiter) : [];
env.PATH = [...new Set([...extras, ...current])].join(delimiter);
}
return env;
}
/**
* Répertoires à ajouter au PATH du daemon, par plateforme. Windows était entièrement ignoré : or
* l'installeur natif de Claude Code se pose dans %LOCALAPPDATA%\Programs et npm global dans
* %APPDATA%\npm, deux emplacements absents du PATH d'une app lancée depuis le menu Démarrer.
*/
export function pathExtras(platform: NodeJS.Platform, env: NodeJS.ProcessEnv = process.env): string[] {
const home = env.USERPROFILE ?? homedir();
if (platform === 'win32') {
const local = env.LOCALAPPDATA ?? join(home, 'AppData', 'Local');
const roaming = env.APPDATA ?? join(home, 'AppData', 'Roaming');
return [
join(local, 'Programs'),
join(local, 'Programs', 'claude'),
join(roaming, 'npm'),
join(home, '.local', 'bin'),
];
}
return ['/usr/local/bin', '/opt/homebrew/bin', join(home, '.local', 'bin'), '/usr/bin', '/bin'];
}
+6
View File
@@ -4,6 +4,7 @@ import { startDaemon, type DaemonHandle } from './daemon';
import { seedSessionCookie } from './auth';
import { loadWindowState, saveWindowState } from './window-state';
import { createTray } from './tray';
import { installAppMenu } from './app-menu';
import { initUpdater } from './updater';
import { resolveIconPath } from './paths';
@@ -39,10 +40,15 @@ async function bootstrap(): Promise<void> {
daemon = await startDaemon({ dataDir, port: PORT, onLog: (l) => process.stdout.write(l) });
await seedSessionCookie(PARTITION, daemon.url, daemon.token);
createWindow(daemon.url);
installAppMenu({ url: daemon.url, onQuit: quitApp });
tray = createTray({ show: showWindow, quit: quitApp });
initUpdater();
}
// macOS : la fenêtre est cachée (pas détruite) à la fermeture. Sans ce handler, cliquer l'icône du
// Dock ne la ramenait jamais et l'app paraissait bloquée en arrière-plan.
app.on('activate', showWindow);
function showWindow(): void {
if (!win) return;
if (win.isMinimized()) win.restore();
+14
View File
@@ -1,5 +1,6 @@
import { app } from 'electron';
import { join } from 'node:path';
import { existsSync } from 'node:fs';
// Résolution des chemins runtime : dev (depuis le repo) vs packagé (extraResources).
// __dirname pointe sur dist/ (bundle esbuild) une fois construit.
@@ -23,6 +24,19 @@ export function resolveIconPath(): string {
: join(__dirname, '..', 'resources', 'icon.png');
}
/**
* Icône de barre système. macOS exige une image « template » (monochrome) dans la barre de menus ;
* ailleurs on retombe sur le logo couleur. `null` si l'asset n'est pas présent (build sans
* régénération des icônes) : l'appelant utilise alors resolveIconPath().
*/
export function resolveTrayIconPath(): string | null {
if (process.platform !== 'darwin') return null;
const path = app.isPackaged
? join(process.resourcesPath, 'trayTemplate.png')
: join(__dirname, '..', 'resources', 'trayTemplate.png');
return existsSync(path) ? path : null;
}
/** Binaire Node qui exécute le daemon (>= 22.16 : node:sqlite + ABI node-pty maîtrisé). */
export function resolveNodeBin(): string {
if (app.isPackaged) {
+9 -3
View File
@@ -1,11 +1,17 @@
import { Menu, Tray, nativeImage } from 'electron';
import { isAutoStartEnabled, setAutoStart } from './autostart';
import { resolveIconPath } from './paths';
import { resolveIconPath, resolveTrayIconPath } from './paths';
/** Icône de barre système : ouvrir la fenêtre, basculer le lancement au login, quitter. */
export function createTray(opts: { show: () => void; quit: () => void }): Tray {
const image = nativeImage.createFromPath(resolveIconPath());
const tray = new Tray(image.isEmpty() ? nativeImage.createEmpty() : image.resize({ width: 18, height: 18 }));
// macOS exige une image TEMPLATE (monochrome + alpha) dans la barre de menus : elle s'inverse
// automatiquement selon le thème système. Une icône couleur y est illisible. Windows attend 16px.
const trayPath = resolveTrayIconPath() ?? resolveIconPath();
const raw = nativeImage.createFromPath(trayPath);
const size = process.platform === 'darwin' ? 16 : process.platform === 'win32' ? 16 : 18;
const image = raw.isEmpty() ? nativeImage.createEmpty() : raw.resize({ width: size, height: size });
if (process.platform === 'darwin' && !image.isEmpty()) image.setTemplateImage(true);
const tray = new Tray(image);
tray.setToolTip('Arboretum');
const buildMenu = (): void => {
+38
View File
@@ -3,6 +3,44 @@
Notable changes to `@johanleroy/git-arboretum` (the Arboretum daemon). The VS Code
extension keeps its own changelog in `packages/vscode/CHANGELOG.md`.
## 3.4.0
Visibility release: the real-time machinery is now actually armed, worktrees show what they are worth,
and history is served. Fully additive, no protocol version bump.
- **Real-time that no longer depends on which panel is open.** A live session now pins the FS watcher of
its worktree, so a worktree an agent is writing into refreshes on its own even when nobody is looking at
it (`pinSession` existed but was never called). On the client side, `watch` subscriptions moved out of
the Git panel, which was unmounted as soon as you left its tab, taking the app's only subscription with
it; they now follow what you actually look at (active worktree plus expanded repositories).
- **Reconnection no longer loses state.** The protocol replays nothing, so every event missed during a
WebSocket outage was lost for good. The client reloads repos, worktrees, sessions and settings whenever
the connection comes back.
- **Session correlation by containment.** A terminal started in a *subdirectory* of a worktree (which
"Start the project" allows) and a group session covering a worktree through `--add-dir` are now listed
under that worktree, instead of vanishing from the tree. The rule lives in `@arboretum/shared`, shared by
the daemon, the web UI and the VS Code extension; the most specific worktree wins.
- **History API.** `GET /api/v1/repos/:id/worktrees/log` serves the branch commits with the count of
unpushed ones, and `GET .../worktrees/diff?commit=<hash>` the full diff of a commit (hash strictly
validated, same size limits as file diffs). The UI unfolds them in place under the Git panel.
- **Full git counters where they matter.** `ahead`/`behind`, staged, unstaged and conflict counts were
only visible in the status bar, for the active worktree. They are now on every worktree row of the tree
and of the Groups panel, with upstream and last commit in the tooltip. `locked`, `prunable` and an
invalid repository are surfaced too.
- **Groups show their composition.** A group lists its repositories with their worktrees and git state,
its sessions (live and recent) and the directories a group session spans. Its colour tints those repos
in the explorer.
- **Actionable `403 BAD_ORIGIN`.** The error now names the exact `--allow-origin` flag to add, and logs
it. It is the first wall of any LAN or reverse-proxy access.
- **Windows support in the daemon.** `where.exe` for CLI discovery, PowerShell as the project launch
shell, a `.cmd` askpass so token-based HTTPS clone/push works, `taskkill /T` for process-tree
termination, `%APPDATA%` for the data directory, and `arboretum install` registering a scheduled task.
- **UI fixes.** Error toasts were painted behind modals (they are sticky, so they piled up invisible);
on mobile, opening a terminal or switching activity had no visible effect; the dock could push the
status bar out of the viewport; panels showed "nothing here" instead of a loading or error state;
modals had no dialog role, focus trap or focus restore; the splitters are now keyboard operable; diff
line numbers stay pinned while scrolling.
## 3.3.0
"Start the project": boot a project's long-running commands (dev server, API, database) in one click. Fully additive, no protocol or API change.
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@johanleroy/git-arboretum",
"version": "3.3.0",
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
"version": "3.4.0",
"description": "Self-hosted multi-project AI IDE for git worktrees and the Claude Code sessions running on them",
"license": "MIT",
"type": "module",
"author": "Johan LEROY <contact@johanleroy.fr>",
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env node
// Acceptation P14 (sans navigateur, sans quota Claude) : temps réel « armé ». Vrai daemon + vrai repo
// git tmp + vrai client WS. Couvre les trois trous de visibilité corrigés :
// 1. une session vivante épingle le watcher FS de SON worktree → les compteurs git d'un worktree
// secondaire restent temps réel même si AUCUN client ne le regarde (avant : point « modifié » figé
// sur le dernier listing REST) ;
// 2. corrélation par contenance : un terminal lancé dans un SOUS-répertoire du worktree y est
// rattaché (« Démarrer le projet »), et pas au checkout principal ;
// 3. `watch` explicite → `worktree_changes` ciblé sur ce worktree secondaire.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync, appendFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const WebSocket = require('ws');
const PORT = 7554;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok, detail });
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p14-'));
const repo = join(tmp, 'demo-repo');
mkdirSync(repo, { recursive: true });
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
mkdirSync(join(repo, 'packages', 'api'), { recursive: true });
writeFileSync(join(repo, 'README.md'), '# demo\n');
writeFileSync(join(repo, 'packages', 'api', 'index.js'), 'console.log(1)\n');
git('add', '-A');
git('commit', '-m', 'init');
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';
srv.stdout.on('data', (d) => (srvOut += d));
srv.stderr.on('data', (d) => (srvOut += d));
function wsClient(cookie) {
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
const state = { msgs: [] };
ws.on('message', (data, isBinary) => {
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
});
const waitMsg = async (pred, timeout = 8000) => {
const t0 = Date.now();
while (Date.now() - t0 < timeout) {
const m = state.msgs.find(pred);
if (m) return m;
await sleep(50);
}
return null;
};
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
}
const j = (path, method, cookie, body) =>
fetch(`${ORIGIN}${path}`, {
method,
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
try {
await sleep(1500);
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
check('boot + token bootstrap', !!token);
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
body: JSON.stringify({ token }),
});
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
check('login → cookie', login.status === 200);
const c = wsClient(cookie);
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
c.send({ type: 'hello', protocol: 1 });
await c.waitMsg((m) => m.type === 'hello_ok');
c.send({ type: 'sub', topics: ['worktrees', 'sessions'] });
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
const repoId = (await addRepo.json()).repo.id;
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
// ---- worktree secondaire (feature) avec un sous-répertoire ----
const created = await j(`/api/v1/repos/${repoId}/worktrees`, 'POST', cookie, { branch: 'feature/live', runHooks: false });
const wtPath = (await created.json()).worktree?.path;
check('POST /worktrees → worktree secondaire créé', created.status === 201 && !!wtPath);
const subDir = join(wtPath, 'packages', 'api');
// ---- 2. corrélation par contenance : session lancée DANS un sous-répertoire ----
const sess = await j('/api/v1/sessions', 'POST', cookie, { cwd: subDir, command: 'bash' });
const session = (await sess.json()).session;
check('POST /sessions (cwd = sous-répertoire) → 201', sess.status === 201 && !!session?.id);
await sleep(600);
const list = await (await j('/api/v1/worktrees', 'GET', cookie)).json();
const secondary = (list.worktrees ?? []).find((w) => w.path === wtPath);
const main = (list.worktrees ?? []).find((w) => w.isMain);
check(
'la session du sous-répertoire est rattachée au worktree secondaire',
(secondary?.sessions ?? []).some((s) => s.id === session.id),
`sessions=${(secondary?.sessions ?? []).length}`,
);
check(
'elle n’est PAS rattachée au checkout principal (désambiguïsation)',
!(main?.sessions ?? []).some((s) => s.id === session.id),
);
// ---- 1. session vivante → watcher épinglé SANS aucun watch client ----
// Aucun `watch` n'a été envoyé : seul `pinSession` peut produire cet événement.
await sleep(900); // laisse chokidar finir son scan initial
c.state.msgs.length = 0;
const t0 = Date.now();
appendFileSync(join(wtPath, 'README.md'), 'edited by the agent\n');
const upd = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === wtPath && m.worktree?.git?.dirtyCount > 0, 6000);
check('worktree secondaire non regardé : worktree_update reçu (pinSession)', !!upd, upd ? `${Date.now() - t0}ms` : 'timeout');
check('les compteurs git du worktree secondaire sont frais', (upd?.worktree?.git?.unstagedCount ?? 0) >= 1);
// ---- pas de worktree_changes sans watch (le détail reste ciblé) ----
const changesWithoutWatch = c.state.msgs.find((m) => m.type === 'worktree_changes');
check('sans watch : aucun worktree_changes (push ciblé préservé)', !changesWithoutWatch);
// ---- 3. watch explicite → worktree_changes ciblé ----
c.send({ type: 'watch', repoId, path: wtPath });
await sleep(900);
c.state.msgs.length = 0;
writeFileSync(join(wtPath, 'live.txt'), 'live\n');
const changesMsg = await c.waitMsg((m) => m.type === 'worktree_changes' && m.path === wtPath, 6000);
check('watch → worktree_changes ciblé sur le worktree secondaire', !!changesMsg);
c.send({ type: 'unwatch', repoId, path: wtPath });
await j(`/api/v1/sessions/${session.id}`, 'DELETE', cookie);
await sleep(500);
// ---- contraposée : le temps réel reste PILOTÉ (ni session, ni watch → pas de surveillance) ----
// Un watcher déjà ouvert est volontairement conservé en cache (évincé par la LRU) : on vérifie donc
// sur un worktree neuf, jamais épinglé ni regardé, qu'aucun événement n'est émis.
const idle = await j(`/api/v1/repos/${repoId}/worktrees`, 'POST', cookie, { branch: 'feature/idle', runHooks: false });
const idlePath = (await idle.json()).worktree?.path;
check('POST /worktrees → second worktree (sans session)', idle.status === 201 && !!idlePath);
await sleep(700);
c.state.msgs.length = 0;
writeFileSync(join(idlePath, 'unwatched.txt'), 'x\n');
const idleMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === idlePath, 2500);
check('worktree sans session ni watch → aucune surveillance (coût piloté par l’attention)', !idleMsg);
c.ws.close();
} catch (err) {
check('exception', false, String(err));
} finally {
srv.kill('SIGTERM');
await sleep(1500);
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
console.log(failed.length === 0 ? '\nACCEPTANCE P14: ALL GREEN' : `\nACCEPTANCE P14: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env node
// Acceptation P15 (sans navigateur, sans quota Claude) : historisation. Vrai daemon + vrai repo git
// tmp. Couvre GET /worktrees/log (ordre, champs, limit/skip, marquage non poussé) et la forme
// `diff?commit=` (diff unifié complet d'un commit, hash invalide et inconnu rejetés).
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync, appendFileSync, mkdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const PORT = 7555;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok, detail });
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p15-'));
const repo = join(tmp, 'demo-repo');
mkdirSync(repo, { recursive: true });
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
writeFileSync(join(repo, 'README.md'), '# demo\n');
git('add', '-A');
git('commit', '-m', 'init');
// un sujet contenant un guillemet et un caractère accentué : piège classique de parsing
appendFileSync(join(repo, 'README.md'), 'deuxième ligne\n');
git('commit', '-am', 'ajoute la « deuxième » ligne');
writeFileSync(join(repo, 'feature.txt'), 'contenu de la feature\n');
git('add', '-A');
git('commit', '-m', 'ajoute feature.txt');
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';
srv.stdout.on('data', (d) => (srvOut += d));
srv.stderr.on('data', (d) => (srvOut += d));
const j = (path, method, cookie, body) =>
fetch(`${ORIGIN}${path}`, {
method,
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
try {
await sleep(1500);
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
check('boot + token bootstrap', !!token);
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
body: JSON.stringify({ token }),
});
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
check('login → cookie', login.status === 200);
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
const repoId = (await addRepo.json()).repo.id;
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
const enc = encodeURIComponent(repo);
// ---- GET /log : ordre, champs, sujet non trivial ----
const log = await (await j(`/api/v1/repos/${repoId}/worktrees/log?path=${enc}`, 'GET', cookie)).json();
const subjects = (log.commits ?? []).map((c) => c.subject);
check('GET /log : 3 commits, du plus récent au plus ancien', subjects.length === 3 && subjects[0] === 'ajoute feature.txt' && subjects[2] === 'init');
check('GET /log : sujet accentué et guillemets préservés', subjects[1] === 'ajoute la « deuxième » ligne');
const head = log.commits?.[0];
check('GET /log : champs hash/shortHash/auteur/date remplis', /^[0-9a-f]{40}$/.test(head?.hash ?? '') && (head?.shortHash?.length ?? 0) >= 7 && head?.author === 'Test' && !Number.isNaN(Date.parse(head?.date ?? '')));
check('GET /log : branche locale sans remote → hasUpstream=false', log.hasUpstream === false && log.unpushedCount === 0);
// ---- limit / skip ----
const page = await (await j(`/api/v1/repos/${repoId}/worktrees/log?path=${enc}&limit=1&skip=1`, 'GET', cookie)).json();
check('GET /log : limit + skip bornent la fenêtre', page.commits?.length === 1 && page.commits[0].subject === 'ajoute la « deuxième » ligne');
const bad = await j(`/api/v1/repos/${repoId}/worktrees/log?path=${enc}&limit=abc`, 'GET', cookie);
check('GET /log : limit non numérique → 400', bad.status === 400);
const noPath = await j(`/api/v1/repos/${repoId}/worktrees/log`, 'GET', cookie);
check('GET /log : path manquant → 400', noPath.status === 400);
// ---- diff d'un commit ----
const cd = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&commit=${head.hash}`, 'GET', cookie)).json();
check('GET /diff?commit= : diff unifié du commit', typeof cd.diff === 'string' && cd.diff.includes('feature.txt') && cd.diff.includes('+contenu de la feature'));
check('GET /diff?commit= : ni binaire ni tronqué', cd.binary === false && cd.tooLarge === false);
const shortHash = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&commit=${head.shortHash}`, 'GET', cookie)).json();
check('GET /diff?commit= : hash court accepté', typeof shortHash.diff === 'string' && shortHash.diff.includes('feature.txt'));
const invalid = await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&commit=${encodeURIComponent('--upload-pack=x')}`, 'GET', cookie);
check('GET /diff?commit= : révision non hexadécimale refusée', invalid.status === 400);
const unknown = await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&commit=deadbeef`, 'GET', cookie);
check('GET /diff?commit= : commit inconnu → 404', unknown.status === 404);
const neither = await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}`, 'GET', cookie);
check('GET /diff : ni file ni commit → 400', neither.status === 400);
// ---- la forme fichier reste intacte (non-régression P7/P9) ----
appendFileSync(join(repo, 'README.md'), 'travail en cours\n');
const fileDiff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
check('GET /diff?file= : toujours fonctionnel', typeof fileDiff.diff === 'string' && fileDiff.diff.includes('+travail en cours'));
} catch (err) {
check('exception', false, String(err));
} finally {
srv.kill('SIGTERM');
await sleep(1500);
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
console.log(failed.length === 0 ? '\nACCEPTANCE P15: ALL GREEN' : `\nACCEPTANCE P15: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env node
// Vérification VISUELLE de la SPA authentifiée, sans Playwright : daemon temporaire isolé + Chromium
// headless piloté en CDP + cookie de session injecté. Produit des captures PNG (thème sombre et clair,
// largeurs desktop et mobile) et échoue si une erreur console / exception Vue survient.
//
// Usage : node packages/server/scripts/verify-ui.mjs [dossier-de-sortie]
// Prérequis : `npm run build` puis `node packages/server/scripts/copy-web.mjs` (le daemon sert la SPA
// depuis packages/server/public, que le build NE rafraîchit PAS).
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname, resolve as resolvePath } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const WebSocket = require('ws');
const PORT = 7998;
const CDP_PORT = 9333;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const outDir = resolvePath(process.argv[2] ?? join(serverDir, '..', '..', '.ui-shots'));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok, detail });
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
function findChromium() {
for (const bin of ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']) {
try {
return execFileSync('which', [bin]).toString().trim();
} catch {
/* essai suivant */
}
}
return null;
}
/** Client CDP minimal : un seul socket, corrélation par id, sessionId pour la cible attachée. */
function cdp(url) {
const ws = new WebSocket(url, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
let nextId = 1;
const pending = new Map();
const events = [];
ws.on('message', (raw) => {
const msg = JSON.parse(String(raw));
if (msg.id && pending.has(msg.id)) {
const { resolve, reject } = pending.get(msg.id);
pending.delete(msg.id);
msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result);
return;
}
if (msg.method) events.push(msg);
});
const ready = new Promise((res, rej) => (ws.on('open', res), ws.on('error', rej)));
const send = (method, params = {}, sessionId) =>
new Promise((resolve, reject) => {
const id = nextId++;
pending.set(id, { resolve, reject });
ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
setTimeout(() => pending.has(id) && (pending.delete(id), reject(new Error(`CDP timeout: ${method}`))), 30_000);
});
return { ws, ready, send, events };
}
const tmp = mkdtempSync(join(tmpdir(), 'arb-verify-ui-'));
mkdirSync(outDir, { recursive: true });
let srv = null;
let browser = null;
try {
// La SPA servie vient de packages/server/public : garde-fou contre la vérification d'un ancien build.
const publicIndex = join(serverDir, 'public', 'index.html');
check('SPA copiée dans packages/server/public', existsSync(publicIndex), publicIndex);
// --- dépôt de démonstration : un checkout principal, un worktree de feature, du travail en cours ---
const repo = join(tmp, 'demo-repo');
mkdirSync(repo, { recursive: true });
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
writeFileSync(join(repo, 'README.md'), '# demo\n');
mkdirSync(join(repo, 'src'), { recursive: true });
writeFileSync(join(repo, 'src', 'app.ts'), 'export const version = 1\n');
git('add', '-A');
git('commit', '-m', 'commit initial');
writeFileSync(join(repo, 'src', 'app.ts'), 'export const version = 2\n');
srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 't.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
{ env: { ...process.env, XDG_DATA_HOME: join(tmp, 'xdg'), ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
);
let srvOut = '';
srv.stdout.on('data', (d) => (srvOut += d));
srv.stderr.on('data', (d) => (srvOut += d));
for (let i = 0; i < 60 && !/arb_[0-9a-f]{16,}/.test(srvOut); i++) await sleep(150);
const token = /arb_[0-9a-f]{16,}/.exec(srvOut)?.[0];
check('daemon temporaire démarré + token', !!token);
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
body: JSON.stringify({ token }),
});
const setCookie = login.headers.getSetCookie?.() ?? [];
const sessionCookie = setCookie.map((c) => c.split(';')[0]).find((c) => c.startsWith('arb_session='));
check('login → cookie de session', !!sessionCookie);
const cookieValue = sessionCookie?.slice('arb_session='.length) ?? '';
const j = (path, method, body) =>
fetch(`${ORIGIN}${path}`, {
method,
headers: { Origin: ORIGIN, Cookie: sessionCookie ?? '', ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
const repoId = (await (await j('/api/v1/repos', 'POST', { path: repo })).json()).repo?.id;
check('dépôt de démonstration enregistré', !!repoId);
const wtRes = await (await j(`/api/v1/repos/${repoId}/worktrees`, 'POST', { branch: 'feature/demo', runHooks: false })).json();
check('worktree de feature créé', !!wtRes.worktree?.path);
// du travail non commité dans le worktree de feature, pour peupler les compteurs git de l'arbre
if (wtRes.worktree?.path) writeFileSync(join(wtRes.worktree.path, 'wip.txt'), 'travail en cours\n');
const groupRes = await (await j('/api/v1/groups', 'POST', { label: 'Démo', color: '#34d399', repoIds: [repoId] })).json();
check('groupe de démonstration créé', !!groupRes.group?.id);
const sess = await (await j('/api/v1/sessions', 'POST', { cwd: repo, command: 'bash' })).json();
check('session bash de démonstration', !!sess.session?.id);
// --- Chromium headless en CDP ---
const chromeBin = findChromium();
check('Chromium disponible', !!chromeBin, chromeBin ?? 'introuvable');
if (!chromeBin) throw new Error('Chromium introuvable : impossible de vérifier le rendu');
browser = spawn(
chromeBin,
[
'--headless=new',
`--remote-debugging-port=${CDP_PORT}`,
`--user-data-dir=${join(tmp, 'chrome')}`,
'--no-first-run',
'--no-default-browser-check',
'--disable-gpu',
'--hide-scrollbars',
],
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
let wsUrl = null;
for (let i = 0; i < 80 && !wsUrl; i++) {
await sleep(200);
try {
wsUrl = (await (await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`)).json()).webSocketDebuggerUrl;
} catch {
/* pas encore prêt */
}
}
check('Chromium en écoute CDP', !!wsUrl);
const client = cdp(wsUrl);
await client.ready;
// État de vue injecté avant le premier paint : on veut des captures qui MONTRENT le contenu
// (arbre déplié, worktree actif), pas un IDE vide.
const expanded = JSON.stringify(JSON.stringify([repoId]));
const context = JSON.stringify(JSON.stringify({ repoId, wtPath: repo }));
const seedExplorer = `localStorage.setItem('arb.ide.expandedRepos', ${expanded});localStorage.setItem('arb.ide.context', ${context});`;
const seedGit = `${seedExplorer}localStorage.setItem('arb.ide.activity', '"git"');localStorage.setItem('arb.history.open', 'true');`;
const shots = [
{ name: 'ide-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedExplorer },
{ name: 'ide-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedExplorer },
{ name: 'git-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedGit },
{ name: 'git-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedGit },
{ name: 'ide-dark-mobile', theme: 'dark', width: 390, height: 844, seed: seedExplorer },
{ name: 'ide-light-mobile', theme: 'light', width: 390, height: 844, seed: seedExplorer },
{ name: 'dashboard-dark-mobile', theme: 'dark', width: 390, height: 844, path: '/dashboard' },
];
for (const shot of shots) {
const { targetId } = await client.send('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await client.send('Target.attachToTarget', { targetId, flatten: true });
await client.send('Runtime.enable', {}, sessionId);
await client.send('Log.enable', {}, sessionId);
await client.send('Network.enable', {}, sessionId);
await client.send('Emulation.setDeviceMetricsOverride', { width: shot.width, height: shot.height, deviceScaleFactor: 1, mobile: shot.width < 500 }, sessionId);
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
// Thème : la SPA lit `arb.theme` avant le premier paint (script anti-FOUC).
await client.send('Page.enable', {}, sessionId);
await client.send(
'Page.addScriptToEvaluateOnNewDocument',
{ source: `localStorage.setItem('arb.theme', ${JSON.stringify(JSON.stringify(shot.theme))});${shot.seed ?? ''}` },
sessionId,
);
const before = client.events.length;
await client.send('Page.navigate', { url: `${ORIGIN}${shot.path ?? '/ide'}` }, sessionId);
await sleep(3500); // laisse le temps au bootstrap REST + WS et au rendu
const text = await client.send('Runtime.evaluate', { expression: 'document.body.innerText', returnByValue: true }, sessionId);
const rendered = String(text.result?.value ?? '');
check(`${shot.name} : page rendue`, rendered.length > 20, `${rendered.length} caractères`);
const errs = client.events
.slice(before)
.filter((e) => e.sessionId === sessionId)
.filter((e) => (e.method === 'Runtime.consoleAPICalled' && e.params?.type === 'error') || e.method === 'Runtime.exceptionThrown')
.map((e) => e.params?.exceptionDetails?.text ?? (e.params?.args ?? []).map((a) => a.value ?? a.description).join(' '))
// Les erreurs réseau des favicons/manifest en headless ne concernent pas l'app.
.filter((m) => m && !/favicon|manifest\.webmanifest/i.test(m));
check(`${shot.name} : aucune erreur console`, errs.length === 0, errs.slice(0, 3).join(' | '));
const { data } = await client.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, sessionId);
const file = join(outDir, `${shot.name}.png`);
writeFileSync(file, Buffer.from(data, 'base64'));
check(`${shot.name} : capture écrite`, true, file);
await client.send('Target.closeTarget', { targetId });
}
client.ws.close();
} catch (err) {
check('exception', false, String(err));
} finally {
browser?.kill('SIGTERM');
srv?.kill('SIGTERM');
await sleep(1200);
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
console.log(failed.length === 0 ? `\nVERIFY UI: ALL GREEN (captures dans ${outDir})` : `\nVERIFY UI: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+6 -1
View File
@@ -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;
+53 -6
View File
@@ -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}`);
+16 -1
View File
@@ -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
+57 -23
View File
@@ -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) {
+31 -4
View File
@@ -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`));
}
+30 -10
View File
@@ -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,
+76 -1
View File
@@ -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 {
+13 -5
View File
@@ -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;
+33
View File
@@ -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;
}
+99 -13
View File
@@ -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 () => {
+42 -4
View File
@@ -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 {
+31 -2
View File
@@ -12,6 +12,7 @@ import {
xmlEscape,
systemdUnitPath,
launchAgentPlistPath,
windowsCreateArgs,
} from '../src/cli/install.js';
describe('cli install · detectPlatform', () => {
@@ -20,9 +21,10 @@ describe('cli install · detectPlatform', () => {
expect(detectPlatform('darwin')).toBe('darwin');
});
it('rejette les autres plateformes avec un message clair', () => {
expect(() => detectPlatform('win32')).toThrow(/Linux \(systemd\) and macOS \(launchd\)/);
it('rejette les plateformes sans superviseur connu, avec un message clair', () => {
// win32 est désormais SUPPORTÉ (Planificateur de tâches) : cf. la suite dédiée plus bas.
expect(() => detectPlatform('freebsd')).toThrow(/freebsd/);
expect(() => detectPlatform('aix')).toThrow(/Task Scheduler/);
});
});
@@ -192,3 +194,30 @@ describe('cli install · chemins', () => {
);
});
});
describe('P14 · Windows (Planificateur de tâches)', () => {
it('detectPlatform accepte win32', () => {
expect(detectPlatform('win32')).toBe('win32');
expect(() => detectPlatform('freebsd')).toThrow(/Task Scheduler/);
});
it('windowsCreateArgs : tâche à l’ouverture de session, sans élévation, idempotente', () => {
const args = windowsCreateArgs({
taskName: 'Arboretum',
exec: 'C:\\Program Files\\nodejs\\node.exe',
scriptArgs: ['C:\\app\\dist\\index.js', '--port', '7317'],
});
expect(args).toEqual([
'/Create',
'/TN',
'Arboretum',
'/TR',
'"C:\\Program Files\\nodejs\\node.exe" C:\\app\\dist\\index.js --port 7317',
'/SC',
'ONLOGON',
'/RL',
'LIMITED',
'/F',
]);
});
});
+80
View File
@@ -32,6 +32,10 @@ import {
amendCommit,
lastCommit,
isUnpushed,
commitLog,
commitDiff,
isValidCommitish,
parseLogZ,
} from '../src/core/git.js';
import { appendFileSync } from 'node:fs';
@@ -318,3 +322,79 @@ describe('addWorktree : résolution auto (créer / réutiliser)', () => {
await expect(addWorktree(repo, { path: wt, branch: 'dup', mode: 'create' })).rejects.toBeDefined();
});
});
describe('P14 · historique (commitLog / commitDiff)', () => {
it('parseLogZ : découpe par paquets de champs et tolère un sujet multi-lignes', () => {
const stdout = ['h1', 's1', 'auteur', '2026-01-01T00:00:00Z', 'sujet\navec saut', 'h2', 's2', 'a2', 'd2', 'sujet 2'].join('\0');
const recs = parseLogZ(stdout, 5);
expect(recs).toHaveLength(2);
expect(recs[0]?.[4]).toBe('sujet\navec saut');
expect(recs[1]?.[0]).toBe('h2');
});
it('parseLogZ : ignore un enregistrement final vide (NUL de fin)', () => {
expect(parseLogZ(['h', 's', 'a', 'd', 'sub', ''].join('\0'), 5)).toHaveLength(1);
});
it('isValidCommitish : hex 4-64 uniquement (refuse une option déguisée)', () => {
expect(isValidCommitish('abc1234')).toBe(true);
expect(isValidCommitish('ABCDEF12')).toBe(true);
expect(isValidCommitish('abc')).toBe(false);
expect(isValidCommitish('--upload-pack=x')).toBe(false);
expect(isValidCommitish('HEAD')).toBe(false);
expect(isValidCommitish('main..HEAD')).toBe(false);
});
it('commitLog : ordre récent → ancien, champs remplis, sans upstream tout est local', async () => {
const repo = makeTmpRepo();
appendFileSync(join(repo, 'README.md'), 'second\n');
await commitAll(repo, 'deuxième commit');
const { commits, hasUpstream, unpushedCount } = await commitLog(repo);
expect(commits).toHaveLength(2);
expect(commits[0]?.subject).toBe('deuxième commit');
expect(commits[1]?.subject).toBe('init');
expect(commits[0]?.hash).toMatch(/^[0-9a-f]{40}$/);
expect(commits[0]?.shortHash.length).toBeGreaterThanOrEqual(7);
expect(commits[0]?.author).toBe('Test');
expect(Number.isNaN(Date.parse(commits[0]?.date ?? ''))).toBe(false);
// branche locale sans remote : aucun commit n'est publié
expect(hasUpstream).toBe(false);
expect(unpushedCount).toBe(0);
});
it('commitLog : limit et skip bornent la fenêtre', async () => {
const repo = makeTmpRepo();
for (const n of [1, 2, 3]) {
appendFileSync(join(repo, 'README.md'), `line ${n}\n`);
await commitAll(repo, `commit ${n}`);
}
expect((await commitLog(repo, { limit: 2 })).commits.map((c) => c.subject)).toEqual(['commit 3', 'commit 2']);
expect((await commitLog(repo, { limit: 1, skip: 2 })).commits.map((c) => c.subject)).toEqual(['commit 1']);
});
it('commitLog : dépôt sans aucun commit → liste vide, pas d’exception', async () => {
const dir = mkdtempSync(join(tmpdir(), 'arb-git-empty-'));
dirs.push(dir);
execFileSync('git', ['init', '-b', 'main'], { cwd: dir, stdio: 'pipe' });
const res = await commitLog(dir);
expect(res.commits).toEqual([]);
expect(res.hasUpstream).toBe(false);
});
it('commitDiff : diff unifié du commit demandé, hash invalide et inconnu rejetés', async () => {
const repo = makeTmpRepo();
writeFileSync(join(repo, 'nouveau.txt'), 'contenu\n');
await commitAll(repo, 'ajout fichier');
const [head] = (await commitLog(repo)).commits;
const d = await commitDiff(repo, head?.hash ?? '');
expect(d.binary).toBe(false);
expect(d.tooLarge).toBe(false);
expect(d.diff).toContain('nouveau.txt');
expect(d.diff).toContain('+contenu');
await expect(commitDiff(repo, 'HEAD')).rejects.toThrow(/Invalid commit hash/);
await expect(commitDiff(repo, 'deadbeef')).rejects.toThrow(/Unknown commit/);
});
});
@@ -0,0 +1,79 @@
import { describe, expect, it } from 'vitest';
import { containsPath, findWorktreeForCwd, sessionBelongsToWorktree } from '../src/core/session-match.js';
describe('containsPath', () => {
it('vrai pour le répertoire lui-même', () => {
expect(containsPath('/p/repo', '/p/repo')).toBe(true);
});
it('vrai pour un descendant', () => {
expect(containsPath('/p/repo', '/p/repo/packages/api')).toBe(true);
});
it('compare par segment, pas par préfixe de chaîne', () => {
// /p/repo ne contient PAS /p/repo-wt-feature (piège du startsWith nu)
expect(containsPath('/p/repo', '/p/repo-wt-feature')).toBe(false);
});
it('faux pour un ancêtre', () => {
expect(containsPath('/p/repo/api', '/p/repo')).toBe(false);
});
it('normalise les chemins non résolus', () => {
expect(containsPath('/p/repo', '/p/repo/./api/../api')).toBe(true);
});
});
describe('sessionBelongsToWorktree', () => {
it('rattache une session lancée à la racine du worktree', () => {
expect(sessionBelongsToWorktree({ cwd: '/p/repo' }, '/p/repo')).toBe(true);
});
it('rattache une session lancée dans un sous-répertoire (« Démarrer le projet »)', () => {
// LaunchCommand.cwd autorise un sous-dossier : le terminal doit rester visible sous son worktree.
expect(sessionBelongsToWorktree({ cwd: '/p/repo/packages/api' }, '/p/repo')).toBe(true);
});
it('ne rattache pas une session d’un worktree frère', () => {
expect(sessionBelongsToWorktree({ cwd: '/p/repo-wt-feat' }, '/p/repo')).toBe(false);
});
it('donne un worktree imbriqué au plus spécifique, pas au principal', () => {
const session = { cwd: '/p/repo/.worktrees/feat/src' };
const all = ['/p/repo', '/p/repo/.worktrees/feat'];
expect(sessionBelongsToWorktree(session, '/p/repo/.worktrees/feat', all)).toBe(true);
expect(sessionBelongsToWorktree(session, '/p/repo', all)).toBe(false);
});
it('rattache une session de groupe via ses répertoires reliés', () => {
// cwd = parent commun (hors des repos), les worktrees couverts vivent dans addedDirs.
const session = { cwd: '/p', addedDirs: ['/p/api', '/p/web'] };
expect(sessionBelongsToWorktree(session, '/p/api')).toBe(true);
expect(sessionBelongsToWorktree(session, '/p/web')).toBe(true);
expect(sessionBelongsToWorktree(session, '/p/docs')).toBe(false);
});
it('ignore un addedDirs absent', () => {
expect(sessionBelongsToWorktree({ cwd: '/p/api' }, '/p/api', [])).toBe(true);
});
});
describe('findWorktreeForCwd', () => {
const worktrees = [
{ repoId: 'r1', path: '/p/api' },
{ repoId: 'r1', path: '/p/api-wt-feat' },
{ repoId: 'r2', path: '/p/api/vendor/web' },
];
it('choisit le worktree le plus spécifique', () => {
expect(findWorktreeForCwd('/p/api/vendor/web/src', worktrees)?.repoId).toBe('r2');
});
it('choisit le worktree frère exact et non le préfixe de chaîne', () => {
expect(findWorktreeForCwd('/p/api-wt-feat/src', worktrees)?.path).toBe('/p/api-wt-feat');
});
it('renvoie null hors de tout worktree connu', () => {
expect(findWorktreeForCwd('/tmp/ailleurs', worktrees)).toBeNull();
});
});
@@ -0,0 +1,94 @@
// Support Windows du daemon : helpers purs, testés avec la plateforme INJECTÉE (ils doivent donc être
// vérifiables depuis Linux). Chacun corrige un point qui rendait le daemon inutilisable sur Windows.
import { describe, expect, it } from 'vitest';
import { buildSpawnSpec, resolveInteractiveShell, resolvePlainShell, whichCommand } from '../src/core/claude-launcher.js';
import { askpassScript } from '../src/core/git-auth.js';
import { defaultDataRoot } from '../src/config.js';
describe('recherche du binaire claude dans le PATH', () => {
it('utilise where.exe sur Windows, which ailleurs', () => {
expect(whichCommand('win32')).toEqual({ file: 'where.exe', args: ['claude'] });
expect(whichCommand('linux')).toEqual({ file: 'which', args: ['claude'] });
expect(whichCommand('darwin').file).toBe('which');
});
});
describe('shell de lancement', () => {
it('POSIX : $SHELL connu en login interactif, sinon bash', () => {
expect(resolveInteractiveShell('linux', { SHELL: '/usr/bin/zsh' })).toEqual({ file: '/usr/bin/zsh', args: ['-l', '-i'] });
expect(resolveInteractiveShell('linux', { SHELL: '/bin/dash' })).toEqual({ file: 'bash', args: ['-l', '-i'] });
expect(resolveInteractiveShell('linux', {})).toEqual({ file: 'bash', args: ['-l', '-i'] });
});
it('Windows : PowerShell qui reste attaché après la commande auto-tapée', () => {
const shell = resolveInteractiveShell('win32', {});
expect(shell.file).toBe('powershell.exe');
expect(shell.args).toContain('-NoExit');
});
it('Windows : le shell est surchargeable par ARBORETUM_SHELL', () => {
expect(resolveInteractiveShell('win32', { ARBORETUM_SHELL: 'pwsh.exe' }).file).toBe('pwsh.exe');
});
it('terminal simple : bash --norc sur POSIX, PowerShell sur Windows', () => {
expect(resolvePlainShell('linux')).toEqual({ file: 'bash', args: ['--norc'] });
expect(resolvePlainShell('win32').file).toBe('powershell.exe');
});
});
describe('buildSpawnSpec · plateforme injectée', () => {
it('command=bash sur Windows lance PowerShell (le contrat d’API reste claude|bash)', () => {
const spec = buildSpawnSpec({ command: 'bash', platform: 'win32' });
expect(spec.file).toBe('powershell.exe');
expect(spec.env.TERM).toBe('xterm-256color');
});
it('command=bash avec login sur Windows reste attaché', () => {
expect(buildSpawnSpec({ command: 'bash', login: true, platform: 'win32' }).args).toContain('-NoExit');
});
it('command=bash sur Linux inchangé', () => {
expect(buildSpawnSpec({ command: 'bash', platform: 'linux' })).toMatchObject({ file: 'bash', args: ['--norc'] });
});
});
describe('script askpass git', () => {
it('Windows : .cmd (un .sh à shebang n’y est pas exécutable)', () => {
const s = askpassScript('win32');
expect(s.name).toBe('askpass.cmd');
expect(s.content).toContain('@echo off');
expect(s.content).toContain('ARB_GIT_USER');
expect(s.content).toContain('ARB_GIT_PASS');
});
it('POSIX : .sh avec shebang', () => {
const s = askpassScript('linux');
expect(s.name).toBe('askpass.sh');
expect(s.content.startsWith('#!/bin/sh')).toBe(true);
expect(s.mode).toBe(0o700);
});
it('les deux variantes distinguent Username du mot de passe', () => {
for (const p of ['win32', 'linux'] as const) {
const c = askpassScript(p).content;
expect(c).toMatch(/Username/i);
}
});
});
describe('racine des données', () => {
it('XDG_DATA_HOME est prioritaire partout (l’app de bureau s’en sert pour isoler)', () => {
expect(defaultDataRoot('win32', { XDG_DATA_HOME: '/iso' }, '/home/u')).toBe('/iso');
expect(defaultDataRoot('linux', { XDG_DATA_HOME: '/iso' }, '/home/u')).toBe('/iso');
});
it('Windows : %APPDATA%, avec repli sur AppData/Roaming', () => {
expect(defaultDataRoot('win32', { APPDATA: 'C:\\Users\\u\\AppData\\Roaming' }, 'C:\\Users\\u')).toBe('C:\\Users\\u\\AppData\\Roaming');
expect(defaultDataRoot('win32', {}, '/home/u')).toBe('/home/u/AppData/Roaming');
});
it('POSIX : ~/.local/share', () => {
expect(defaultDataRoot('linux', {}, '/home/u')).toBe('/home/u/.local/share');
expect(defaultDataRoot('darwin', {}, '/Users/u')).toBe('/Users/u/.local/share');
});
});
+31
View File
@@ -237,6 +237,37 @@ export interface FileDiffResponse {
/** texte du diff unifié git (vide si binaire ou tooLarge). */
diff: string;
}
/** Un commit de l'historique d'un worktree (GET .../worktrees/log). */
export interface CommitEntry {
/** hash complet (clé stable, utilisée pour demander le diff du commit). */
hash: string;
/** hash court tel que git l'abrège (affichage). */
shortHash: string;
author: string;
/** date d'auteur ISO 8601 (%aI). */
date: string;
subject: string;
}
/**
* GET /api/v1/repos/:id/worktrees/log?path=&limit=&skip= : historique de la branche du worktree.
* `unpushedCount` compte les commits de tête pas encore poussés ; `hasUpstream: false` signifie qu'aucun
* commit n'est publié (branche purement locale) et que TOUS sont donc à considérer comme non poussés.
*/
export interface WorktreeLogResponse {
repoId: string;
path: string;
commits: CommitEntry[];
unpushedCount: number;
hasUpstream: boolean;
}
/** GET /api/v1/repos/:id/worktrees/diff?path=&commit= : diff unifié complet d'un commit. */
export interface CommitDiffResponse {
path: string;
commit: string;
binary: boolean;
tooLarge: boolean;
diff: string;
}
/** GET /api/v1/repos/:id/files/content?wt=&path= : contenu d'un fichier (pour l'éditeur Monaco). */
export interface FileContentResponse {
/** chemin relatif au worktree (POSIX). */
+1
View File
@@ -1,3 +1,4 @@
export * from './protocol.js';
export * from './api.js';
export * from './wt-key.js';
export * from './path-match.js';
+71
View File
@@ -0,0 +1,71 @@
// Corrélation session ↔ worktree par contenance de chemin. Source unique partagée par le daemon, le
// front web et l'extension VS Code : la règle doit être identique partout, sinon un terminal apparaît
// sous un worktree côté serveur et sous un autre côté UI.
//
// Historiquement la corrélation était une égalité stricte `session.cwd === worktree.path`. Deux cas
// réels y échappent :
// 1. « Démarrer le projet » autorise un sous-répertoire par commande (`LaunchCommand.cwd`, borné par
// `resolveLaunchSubdir`) : le terminal tourne DANS le worktree, mais pas à sa racine ;
// 2. une session de groupe (P6) couvre plusieurs repos via `--add-dir` : son cwd est le parent commun
// et les worktrees couverts n'apparaissent que dans `addedDirs`.
// Dans les deux cas la session appartient bel et bien au worktree.
//
// Aucune dépendance à `node:path` (le front tourne dans un navigateur) : la comparaison se fait par
// segments, en tolérant les deux séparateurs pour rester correcte sur Windows. La comparaison reste
// SENSIBLE à la casse : les chemins comparés viennent tous de la même source (git et la base), et
// insensibiliser casserait deux répertoires ne différant que par la casse sous Linux.
/** Segments non vides d'un chemin, séparateurs POSIX et Windows confondus. */
function segments(p: string): string[] {
return p.split(/[\\/]+/).filter((s) => s.length > 0 && s !== '.');
}
/** true si `child` est `parent` lui-même ou un descendant. */
export function containsPath(parent: string, child: string): boolean {
const p = segments(parent);
const c = segments(child);
if (c.length < p.length) return false;
return p.every((seg, i) => c[i] === seg);
}
/** Répertoires qu'une session occupe : son cwd, plus les répertoires reliés d'une session de groupe. */
export function sessionDirs(session: { cwd: string; addedDirs?: string[] }): string[] {
return [session.cwd, ...(session.addedDirs ?? [])];
}
/**
* Attribue une session au worktree `worktreePath`. `others` = les autres worktrees connus (au moins
* ceux du même repo) : sans eux, une session lancée dans un worktree imbriqué (`repo/.worktrees/x`)
* serait aussi listée sous le checkout principal `repo`. Le worktree le plus spécifique gagne.
*/
export function sessionBelongsToWorktree(
session: { cwd: string; addedDirs?: string[] },
worktreePath: string,
others: string[] = [],
): boolean {
const depth = segments(worktreePath).length;
return sessionDirs(session).some((dir) => {
if (!containsPath(worktreePath, dir)) return false;
// un autre worktree plus profond contient aussi ce répertoire → il est le propriétaire légitime.
return !others.some((o) => segments(o).length > depth && containsPath(o, dir));
});
}
/**
* Worktree auquel rattacher un répertoire, parmi une liste hétérogène (tous repos confondus) : le plus
* spécifique qui le contient. Sert à épingler le watcher FS du worktree d'une session vivante et à
* étiqueter un terminal.
*/
export function findWorktreeForCwd<T extends { path: string }>(cwd: string, worktrees: T[]): T | null {
let best: T | null = null;
let bestDepth = -1;
for (const w of worktrees) {
if (!containsPath(w.path, cwd)) continue;
const depth = segments(w.path).length;
if (depth > bestDepth) {
best = w;
bestDepth = depth;
}
}
return best;
}
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest';
import { containsPath, findWorktreeForCwd, sessionBelongsToWorktree } from '../src/path-match.js';
describe('containsPath', () => {
it('vrai pour le répertoire lui-même et ses descendants', () => {
expect(containsPath('/p/repo', '/p/repo')).toBe(true);
expect(containsPath('/p/repo', '/p/repo/packages/api')).toBe(true);
});
it('compare par segment, pas par préfixe de chaîne', () => {
// piège du startsWith nu : /p/repo n'est pas le parent de /p/repo-wt-feature
expect(containsPath('/p/repo', '/p/repo-wt-feature')).toBe(false);
});
it('faux pour un ancêtre', () => {
expect(containsPath('/p/repo/api', '/p/repo')).toBe(false);
});
it('tolère les deux séparateurs (chemins Windows)', () => {
expect(containsPath('C:\\dev\\repo', 'C:\\dev\\repo\\packages\\api')).toBe(true);
expect(containsPath('C:\\dev\\repo', 'C:/dev/repo/packages')).toBe(true);
expect(containsPath('C:\\dev\\repo', 'C:\\dev\\repo2')).toBe(false);
});
it('reste sensible à la casse', () => {
expect(containsPath('/p/Repo', '/p/repo/api')).toBe(false);
});
it('ignore les séparateurs redondants et un slash final', () => {
expect(containsPath('/p/repo/', '/p//repo/api')).toBe(true);
});
});
describe('sessionBelongsToWorktree', () => {
it('rattache une session lancée dans un sous-répertoire', () => {
expect(sessionBelongsToWorktree({ cwd: '/p/repo/packages/api' }, '/p/repo')).toBe(true);
});
it('donne un worktree imbriqué au plus spécifique, pas au principal', () => {
const session = { cwd: '/p/repo/.worktrees/feat/src' };
const all = ['/p/repo', '/p/repo/.worktrees/feat'];
expect(sessionBelongsToWorktree(session, '/p/repo/.worktrees/feat', all)).toBe(true);
expect(sessionBelongsToWorktree(session, '/p/repo', all)).toBe(false);
});
it('rattache une session de groupe via ses répertoires reliés', () => {
const session = { cwd: '/p', addedDirs: ['/p/api', '/p/web'] };
expect(sessionBelongsToWorktree(session, '/p/api')).toBe(true);
expect(sessionBelongsToWorktree(session, '/p/docs')).toBe(false);
});
it('ne rattache pas une session d’un worktree frère', () => {
expect(sessionBelongsToWorktree({ cwd: '/p/repo-wt-feat' }, '/p/repo')).toBe(false);
});
});
describe('findWorktreeForCwd', () => {
const worktrees = [
{ repoId: 'r1', path: '/p/api' },
{ repoId: 'r1', path: '/p/api-wt-feat' },
{ repoId: 'r2', path: '/p/api/vendor/web' },
];
it('choisit le worktree le plus spécifique', () => {
expect(findWorktreeForCwd('/p/api/vendor/web/src', worktrees)?.repoId).toBe('r2');
});
it('choisit le worktree frère exact', () => {
expect(findWorktreeForCwd('/p/api-wt-feat/src', worktrees)?.path).toBe('/p/api-wt-feat');
});
it('renvoie null hors de tout worktree connu', () => {
expect(findWorktreeForCwd('/tmp/ailleurs', worktrees)).toBeNull();
});
});
+2 -2
View File
@@ -5,12 +5,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark" />
<meta name="theme-color" content="#09090b" />
<!-- Anti-FOUC : applique la préférence de thème (arb-theme) avant le premier paint.
<!-- Anti-FOUC : applique la préférence de thème (arb.theme, même clé que l'app) avant le premier paint.
Doit rester inline/synchrone. Synchronisé avec src/lib/theme.ts. -->
<script>
(function () {
try {
var mode = localStorage.getItem('arb-theme') || 'dark';
var mode = localStorage.getItem('arb.theme') || 'dark';
var dark = mode === 'dark' || (mode === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
var theme = dark ? 'dark' : 'light';
var bg = dark ? '#09090b' : '#fafafa';
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@arboretum/site",
"private": true,
"version": "0.3.0",
"version": "0.4.0",
"type": "module",
"scripts": {
"dev": "vite",
+1 -1
View File
@@ -2,7 +2,7 @@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://git-arboretum.com/</loc>
<lastmod>2026-06-19</lastmod>
<lastmod>2026-08-04</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
+2
View File
@@ -9,6 +9,7 @@ import ShowcaseSection from './components/ShowcaseSection.vue';
import WorkspaceShowcase from './components/WorkspaceShowcase.vue';
import LaunchShowcase from './components/LaunchShowcase.vue';
import DownloadSection from './components/DownloadSection.vue';
import AccessSection from './components/AccessSection.vue';
import RemoteGitSection from './components/RemoteGitSection.vue';
import WorkGroupsSection from './components/WorkGroupsSection.vue';
import HowItWorksSection from './components/HowItWorksSection.vue';
@@ -71,6 +72,7 @@ const glowStyle = {
<WorkspaceShowcase />
<LaunchShowcase />
<DownloadSection />
<AccessSection />
<RemoteGitSection />
<WorkGroupsSection />
<HowItWorksSection />
@@ -0,0 +1,74 @@
<script setup lang="ts">
// Les trois façons d'utiliser Arboretum. Le « mode serveur web » (le daemon servi à ses propres
// appareils) n'était décrit nulle part sur le site, alors que c'est l'usage central du produit ; et
// l'extension VS Code n'avait qu'une carte de fonctionnalité, sans lien ni mode d'emploi.
import { useI18n } from 'vue-i18n';
import { DOWNLOADS, DESKTOP_SRC } from '../lib/links';
const { t } = useI18n();
const ways = [
{
key: 'wayDesktop',
body: 'wayDesktopBody',
code: null,
link: { href: DOWNLOADS.deb, label: 'wayDesktopLink' },
},
{
key: 'wayServer',
body: 'wayServerBody',
code: 'tailscale serve --bg 7317',
link: null,
},
{
key: 'wayVscode',
body: 'wayVscodeBody',
code: null,
link: { href: DOWNLOADS.vsix, label: 'wayVscodeLink' },
},
] as const;
</script>
<template>
<section id="access" class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 pb-[100px]">
<div v-reveal class="mb-[40px] max-w-[720px]">
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-accent">{{ t('wayKicker') }}</div>
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,38px)] font-semibold leading-[1.15] tracking-[-0.025em] text-fg">
{{ t('wayTitle') }}
</h2>
<p class="m-0 text-[16.5px] leading-[1.6] text-fg-muted">{{ t('wayBody') }}</p>
</div>
<div v-reveal class="grid gap-4 md:grid-cols-3">
<div
v-for="w in ways"
:key="w.key"
class="flex flex-col gap-3 rounded-[14px] border border-border bg-surface-0 p-5 shadow-card"
>
<h3 class="m-0 text-[15px] font-semibold text-fg">{{ t(w.key) }}</h3>
<p class="m-0 flex-1 text-[14px] leading-[1.55] text-fg-muted">{{ t(w.body) }}</p>
<code
v-if="w.code"
class="block overflow-x-auto whitespace-nowrap rounded-lg border border-border bg-surface-1 px-3 py-2 font-mono text-[12.5px] text-fg"
>
<span class="text-accent">$ </span>{{ w.code }}
</code>
<a
v-if="w.link"
:href="w.link.href"
class="text-[13.5px] font-medium text-accent no-underline hover:underline"
>
{{ t(w.link.label) }} →
</a>
</div>
</div>
<p v-reveal class="mt-6 max-w-[760px] text-[13.5px] leading-[1.6] text-fg-subtle">{{ t('wayOriginNote') }}</p>
<p v-reveal class="mt-2 max-w-[760px] text-[13.5px] leading-[1.6] text-fg-subtle">
{{ t('wayBuildNote') }}
<a :href="DESKTOP_SRC" target="_blank" rel="noopener" class="text-fg-muted underline decoration-border underline-offset-2 hover:text-accent">
packages/desktop
</a>
</p>
</section>
</template>
+5 -1
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { INSTALL_COMMAND } from '../composables/useCopy';
import { REPO, LICENSE, COFFEE } from '../lib/links';
import { COFFEE, LICENSE, REPO, VERSIONS } from '../lib/links';
import IconGitea from './icons/IconGitea.vue';
import CopyButton from './CopyButton.vue';
@@ -44,6 +44,10 @@ const { t } = useI18n();
<code class="font-mono text-[12.5px] text-fg-subtle">{{ INSTALL_COMMAND }}</code>
<CopyButton variant="icon" :text="INSTALL_COMMAND" :label="t('copyCommand')" />
</div>
<!-- Versions publiées : le site n'en affichait aucune, impossible de savoir ce qu'il décrit. -->
<span class="font-mono text-[12px] text-fg-subtle">
daemon {{ VERSIONS.daemon }} · desktop {{ VERSIONS.desktop }} · vscode {{ VERSIONS.vscode }}
</span>
</div>
</div>
</footer>
@@ -7,9 +7,13 @@ import IconGitea from './icons/IconGitea.vue';
const { t } = useI18n();
// Les sections #launch (« Démarrer le projet ») et #remotegit (services git distants) existaient sans
// aucun lien de navigation : elles n'étaient atteignables qu'en scrollant à l'aveugle.
const navLinks = [
{ href: '#features', key: 'navFeatures' },
{ href: '#workspace', key: 'navWorkspace' },
{ href: '#launch', key: 'navLaunch' },
{ href: '#remotegit', key: 'navRemoteGit' },
{ href: '#download', key: 'navDownload' },
{ href: '#how', key: 'navHow' },
{ href: '#security', key: 'navSecurity' },
@@ -1,13 +1,17 @@
<script setup lang="ts">
// Téléchargements réels : chaque plateforme porte son lien direct vers l'asset de la release flottante
// `desktop-latest` (le tag est recréé par la CI à chaque version, les URL restent donc valables).
// Avant, les trois cartes étaient décoratives et un unique bouton renvoyait vers la page des releases.
import { useI18n } from 'vue-i18n';
import { RELEASES, DESKTOP_SRC } from '../lib/links';
import { DOWNLOADS, DESKTOP_SRC, RELEASES, VERSIONS } from '../lib/links';
const { t } = useI18n();
const platforms = [
{ key: 'dlLinux', hint: 'dlLinuxHint' },
{ key: 'dlWin', hint: 'dlWinHint' },
{ key: 'dlMac', hint: 'dlMacHint' },
{ key: 'dlLinux', hint: 'dlLinuxHint', href: DOWNLOADS.deb },
{ key: 'dlWin', hint: 'dlWinHint', href: DOWNLOADS.windows },
// macOS n'est pas buildé par la CI (aucun runner) : la carte renvoie donc vers les sources.
{ key: 'dlMac', hint: 'dlMacHint', href: DESKTOP_SRC },
] as const;
const bullets = ['dlNoNode', 'dlBundled', 'dlAutoUpdate'] as const;
@@ -21,22 +25,39 @@ const bullets = ['dlNoNode', 'dlBundled', 'dlAutoUpdate'] as const;
{{ t('dlTitle') }}
</h2>
<p class="m-0 text-[16.5px] leading-[1.6] text-fg-muted">{{ t('dlBody') }}</p>
<p class="mt-2 font-mono text-[12.5px] text-fg-subtle">{{ t('dlVersion', { version: VERSIONS.desktop }) }}</p>
</div>
<div v-reveal class="grid gap-4 md:grid-cols-3">
<div
<a
v-for="p in platforms"
:key="p.key"
class="flex flex-col gap-1 rounded-[14px] border border-border bg-surface-0 p-5 shadow-card"
:href="p.href"
class="group flex flex-col gap-1 rounded-[14px] border border-border bg-surface-0 p-5 no-underline shadow-card transition-colors hover:border-accent/50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent/70"
>
<div class="flex items-center gap-2 text-fg">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-accent" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" x2="12" y1="15" y2="3" /></svg>
<span class="text-[15px] font-semibold">{{ t(p.key) }}</span>
<span class="text-[15px] font-semibold group-hover:text-accent">{{ t(p.key) }}</span>
</div>
<span class="pl-[26px] font-mono text-[12.5px] text-fg-subtle">{{ t(p.hint) }}</span>
</div>
</a>
</div>
<p v-reveal class="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-[13px] text-fg-subtle">
<a
:href="DOWNLOADS.appImage"
class="text-fg-muted underline decoration-border underline-offset-2 hover:text-accent"
>
{{ t('dlLinuxAlt') }}
</a>
<a :href="RELEASES" target="_blank" rel="noopener" class="text-fg-muted underline decoration-border underline-offset-2 hover:text-accent">
{{ t('dlAllAssets') }}
</a>
<a :href="DESKTOP_SRC" target="_blank" rel="noopener" class="text-fg-muted underline decoration-border underline-offset-2 hover:text-accent">
{{ t('dlSource') }}
</a>
</p>
<ul v-reveal class="mt-6 flex flex-wrap gap-x-6 gap-y-2">
<li v-for="b in bullets" :key="b" class="flex items-center gap-2 text-[14px] text-fg-muted">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" class="text-accent" aria-hidden="true"><path d="M20 6 9 17l-5-5" /></svg>
@@ -44,25 +65,9 @@ const bullets = ['dlNoNode', 'dlBundled', 'dlAutoUpdate'] as const;
</li>
</ul>
<div v-reveal class="mt-7 flex flex-wrap items-center gap-3">
<a
:href="RELEASES"
target="_blank"
rel="noopener"
class="inline-flex items-center gap-2 rounded-lg bg-accent-solid px-4 py-2.5 text-[14.5px] font-semibold text-white no-underline transition-colors hover:bg-accent-hover focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent/70"
>
{{ t('dlGet') }}
</a>
<a
:href="DESKTOP_SRC"
target="_blank"
rel="noopener"
class="inline-flex items-center gap-2 rounded-lg border border-border px-4 py-2.5 text-[14.5px] font-medium text-fg-muted no-underline transition-colors hover:border-accent/50 hover:text-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent/70"
>
{{ t('dlSource') }}
</a>
</div>
<p v-reveal class="mt-4 max-w-[720px] text-[13.5px] leading-[1.55] text-fg-subtle">{{ t('dlNote') }}</p>
<!-- Premier lancement : ni l'installeur Windows ni l'app macOS ne sont signés. Le dire ICI évite
qu'un visiteur conclue à un binaire cassé. -->
<p v-reveal class="mt-6 max-w-[720px] text-[13.5px] leading-[1.55] text-fg-subtle">{{ t('dlUnsigned') }}</p>
<p v-reveal class="mt-2 max-w-[720px] text-[13.5px] leading-[1.55] text-fg-subtle">{{ t('dlNote') }}</p>
</section>
</template>
@@ -127,6 +127,20 @@ const { t } = useI18n();
</template>
{{ t('feat16Desc') }}
</FeatureCard>
<FeatureCard :title="t('feat17Title')">
<template #icon>
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 3v5h5" /><path d="M3.05 13A9 9 0 1 0 6 5.3L3 8" /><path d="M12 7v5l4 2" /></svg>
</template>
{{ t('feat17Desc') }}
</FeatureCard>
<FeatureCard :title="t('feat18Title')">
<template #icon>
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z" /><path d="M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z" /><path d="M12 2v2" /><path d="M12 20v2" /><path d="m4.93 4.93 1.41 1.41" /><path d="m17.66 17.66 1.41 1.41" /><path d="M2 12h2" /><path d="M20 12h2" /></svg>
</template>
{{ t('feat18Desc') }}
</FeatureCard>
</div>
</section>
</template>
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { INSTALL_COMMAND } from '../composables/useCopy';
import { NPMRC_LINE } from '../lib/links';
import CopyButton from './CopyButton.vue';
const { t } = useI18n();
@@ -15,6 +16,20 @@ const LOCAL_URL = 'http://localhost:7317';
<h2 class="m-0 text-[clamp(28px,3.4vw,40px)] font-semibold tracking-[-0.025em] text-fg">{{ t('howTitle') }}</h2>
</div>
<!-- Prérequis : le paquet vit sur un registre npm PRIVÉ. Sans cette ligne dans ~/.npmrc, le `npx`
de l'étape 1 renvoie un 404. C'était le premier mur pour tout nouvel arrivant. -->
<div v-reveal class="mb-4 rounded-xl border border-border bg-surface-1/50 p-[26px]">
<h3 class="m-0 mb-2.5 text-lg font-semibold text-fg">{{ t('prereqTitle') }}</h3>
<p class="m-0 mb-4 text-[14.5px] leading-[1.55] text-fg-muted">{{ t('prereqDesc') }}</p>
<div class="flex items-center gap-2 rounded-lg border border-border bg-surface-0 p-[11px]">
<code class="min-w-0 flex-1 overflow-x-auto whitespace-nowrap font-mono text-[12.5px] text-fg">
{{ NPMRC_LINE }}
</code>
<CopyButton variant="icon" :text="NPMRC_LINE" :label="t('copyCommand')" />
</div>
<p class="m-0 mt-3 text-[13.5px] leading-[1.55] text-fg-subtle">{{ t('prereqNote') }}</p>
</div>
<div v-reveal class="grid grid-cols-[repeat(auto-fit,minmax(280px,1fr))] gap-4">
<div class="rounded-xl border border-border bg-surface-1/50 p-[26px]">
<div class="mb-[18px] font-mono text-[13px] text-accent">01</div>
@@ -61,6 +61,10 @@ function marker(type: DiffLine['type']): string {
<span class="flex h-9 w-9 items-center justify-center rounded-lg" :title="t('wsTerminal')">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7 11 2-2-2-2" /><path d="M11 13h4" /><rect width="18" height="18" x="3" y="3" rx="2" /></svg>
</span>
<!-- 4e onglet : Groupes (l'app en a quatre, le mockup n'en montrait que trois) -->
<span class="flex h-9 w-9 items-center justify-center rounded-lg" :title="t('wsGroups')">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7.5 4.27 9 5.15" /><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z" /><path d="m3.3 7 8.7 5 8.7-5" /><path d="M12 22V12" /></svg>
</span>
</nav>
<!-- arbre unifie : plusieurs projets a la fois -->
@@ -77,6 +81,12 @@ function marker(type: DiffLine['type']): string {
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-fg-subtle" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--color-accent)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0" aria-hidden="true"><line x1="6" x2="6" y1="3" y2="15" /><circle cx="18" cy="6" r="3" /><circle cx="6" cy="18" r="3" /><path d="M18 9a9 9 0 0 1-9 9" /></svg>
<span class="truncate text-accent">feat/auth</span>
<!-- compteurs git compacts : ahead / indexés / non indexés, comme dans l'app -->
<span class="ml-auto flex shrink-0 items-center gap-1 text-[11px]">
<span class="text-accent">↑2</span>
<span class="text-accent">●1</span>
<span class="text-warn">○1</span>
</span>
</div>
<!-- session claude corrélée -->
<div class="flex items-center gap-1.5 rounded py-0.5 pr-2 pl-[38px] text-fg-muted">
@@ -94,6 +104,7 @@ function marker(type: DiffLine['type']): string {
<div class="flex items-center gap-1 rounded py-0.5 pr-2 pl-1.5 text-fg-muted">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-fg-subtle" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
<span class="font-medium">web</span>
<span class="ml-auto shrink-0 text-[11px] text-warn">○3</span>
</div>
<div class="flex items-center gap-1 rounded py-0.5 pr-2 pl-1.5 text-fg-muted">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-fg-subtle" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
+2 -2
View File
@@ -31,7 +31,7 @@ export const FAQS: Record<AppLocale, FaqItem[]> = {
},
{
q: 'Can I edit files directly?',
a: 'Yes. The /workspace view is a real IDE: a file tree, a full Monaco editor with inline diffs, and the correlated session terminal. Stage changes file by file, write a commit message, amend, then push, all from the browser, on any device.',
a: 'Yes. The /ide view is a real IDE: a file tree, a full Monaco editor with inline diffs, and the correlated session terminal. Stage changes file by file, write a commit message, amend, then push, all from the browser, on any device.',
},
{
q: 'Can I connect GitHub, GitLab or Gitea and clone?',
@@ -65,7 +65,7 @@ export const FAQS: Record<AppLocale, FaqItem[]> = {
},
{
q: 'Puis-je éditer les fichiers directement ?',
a: "Oui. La vue /workspace est un vrai IDE : un arbre de fichiers, un éditeur Monaco complet avec les diffs inline, et le terminal de la session corrélée. Indexez les changements fichier par fichier, rédigez un message de commit, amendez, puis poussez, le tout depuis le navigateur, sur n'importe quel appareil.",
a: "Oui. La vue /ide est un vrai IDE : un arbre de fichiers, un éditeur Monaco complet avec les diffs inline, et le terminal de la session corrélée. Indexez les changements fichier par fichier, rédigez un message de commit, amendez, puis poussez, le tout depuis le navigateur, sur n'importe quel appareil.",
},
{
q: 'Puis-je connecter GitHub, GitLab ou Gitea et cloner ?',
+38 -19
View File
@@ -2,6 +2,8 @@
export default {
navFeatures: 'Features',
navWorkspace: 'IDE',
navLaunch: 'Start project',
navRemoteGit: 'Git services',
navDownload: 'Download',
navHow: 'How it works',
navSecurity: 'Security',
@@ -41,6 +43,10 @@ export default {
feat10Desc: 'Create a project folder anywhere (optional git init) and start a Claude session in it, from any device.',
feat16Title: 'Start your project',
feat16Desc: 'Define your dev commands once (dev server, API, database), then launch each in its own terminal in a single click.',
feat17Title: 'Branch history',
feat17Desc: 'See what is already committed, which commits are not pushed yet, and unfold the full diff of any of them, right next to what is still uncommitted.',
feat18Title: 'Git state at a glance',
feat18Desc: 'Every worktree row carries its own counters: ahead/behind, staged, unstaged, conflicts. They refresh on their own while an agent works, no click needed.',
scAKicker: 'Session supervision',
scATitle: 'See what needs you, before anything stalls',
scABody:
@@ -58,6 +64,11 @@ export default {
grpTitle: 'Drive every repo from one Claude session',
grpBody:
'Group the repos that move together: a service, its client, its docs. Launch a single Claude session that spans all of them at once: one conversation, one shared context working across every repo, instead of juggling one agent per repo.',
prereqTitle: 'Prerequisites',
prereqDesc:
'Arboretum is published on a private npm registry. Declare its scope once in your ~/.npmrc, otherwise npm answers 404.',
prereqNote:
'You also need Node 22.16 or newer (the daemon uses node:sqlite) and the Claude Code CLI on your PATH. The desktop app needs neither: it bundles its own runtime.',
howKicker: 'How it works',
howTitle: 'Zero install. Three steps.',
step1Title: 'Launch the daemon',
@@ -84,20 +95,13 @@ export default {
footTag: 'a garden of branches, one pane of glass.',
license: 'MIT License',
coffee: 'Buy me a coffee',
mIde: 'IDE',
mProjects: 'Projects',
mWorktrees: 'Worktrees',
mExplorer: 'Explorer',
mEditor: 'Editor',
mTerminal: 'Terminal',
mGit: 'Git',
mSessions: 'Sessions',
mGroups: 'Groups',
mSettings: 'Settings',
mHelp: 'Help',
mGitea: 'Gitea',
mMore: 'More',
mSearch: 'Search',
mAttn: 'Needs attention',
waiting: 'waiting',
busy: 'busy',
@@ -139,16 +143,9 @@ export default {
wsDiff: 'Diff',
wsFiles: 'Files',
wsChanges: 'Changes',
wsStaged: 'Staged',
wsTerminal: 'Terminal',
wsCommitMsg: 'Implement token refresh',
wsCommitPlaceholder: 'Commit message…',
wsAmend: 'Amend last commit',
wsGroups: 'Groups',
wsCommitBtn: 'Commit',
wsPushBtn: 'Push',
wsStage: 'Stage',
wsUnstage: 'Unstage',
wsDiscard: 'Discard',
// « Start the project » : lancement multi-terminaux
launchScKicker: 'Start the project',
@@ -168,7 +165,6 @@ export default {
rgTested: 'tested',
rgAddConnection: 'Add connection',
rgEncrypted: 'Encrypted at rest',
rgCloning: 'Cloning',
rgCloneReceiving: 'Receiving objects',
// Security pillar (encrypted secrets)
@@ -176,20 +172,43 @@ export default {
sec5Desc: 'Remote git credentials are encrypted at rest (AES-256-GCM) and never returned in clear by the API.',
// Desktop app (download)
wayKicker: 'Three ways to run it',
wayTitle: 'Desktop app, web server, or inside VS Code',
wayBody:
'The same daemon powers all three. Pick the one that fits the machine you are on, they share the same data.',
wayDesktop: 'Desktop app',
wayDesktopBody:
'A native window that starts the daemon for you, already signed in, with a tray icon and launch-at-login. Nothing to install beyond the app itself.',
wayDesktopLink: 'Download',
wayServer: 'Self-hosted web server',
wayServerBody:
'Run the daemon on your workstation and reach its UI from any device you own: laptop, tablet, phone. Tailscale Serve gives you HTTPS inside your tailnet without opening a port, which is also what enables push notifications and PWA install.',
wayVscode: 'VS Code extension',
wayVscodeBody:
'A native extension (not a webview) that connects to the same daemon: live tree of repos, worktrees and sessions, native terminals, a waiting counter with notifications, and git actions.',
wayVscodeLink: 'Get the VSIX',
wayOriginNote:
'One rule to remember when serving it beyond localhost: the daemon rejects any address it was not told about, with a 403. Start it with --allow-origin <your URL> (repeatable) and it is settled. Binding beyond loopback also requires an explicit acknowledgement flag, on purpose.',
wayBuildNote: 'Build the desktop app yourself from',
dlKicker: 'Native desktop app',
dlTitle: 'Download Arboretum for your desktop',
dlBody:
'A native app for Linux, Windows and macOS. It bundles the daemon and its Node runtime, so there is nothing else to install: launch it and your multi-project IDE opens, already signed in. Tray, launch at login and auto-update included. Prefer the terminal? Keep running it in the browser with a single command.',
dlLinux: 'Linux',
dlLinuxHint: 'AppImage and .deb',
dlLinuxHint: '.deb (Debian, Ubuntu)',
dlLinuxAlt: 'AppImage (other distributions)',
dlWin: 'Windows',
dlWinHint: 'NSIS installer and portable',
dlMac: 'macOS',
dlMacHint: 'dmg (best-effort, unsigned)',
dlMacHint: 'build from source (unsigned)',
dlNoNode: 'No Node install needed',
dlBundled: 'Daemon and runtime bundled',
dlAutoUpdate: 'Auto-update on Windows and Linux',
dlVersion: 'Latest desktop release: {version}',
dlAllAssets: 'All release assets',
dlUnsigned:
'The binaries are not code-signed. On Windows, SmartScreen shows "unknown publisher": choose More info, then Run anyway. On macOS, right-click the app then Open.',
dlGet: 'Get the app',
dlSource: 'Build from source',
dlNote: 'Installers are published on the releases page once a desktop build is tagged. Until then, build it from source (see packages/desktop).',
dlNote: 'macOS builds are produced on demand (no macOS CI runner): build them with npm run dist:mac, or ask for one.',
};
+38 -19
View File
@@ -2,6 +2,8 @@
export default {
navFeatures: 'Fonctionnalités',
navWorkspace: 'IDE',
navLaunch: 'Démarrer',
navRemoteGit: 'Services git',
navDownload: 'Télécharger',
navHow: 'Comment ça marche',
navSecurity: 'Sécurité',
@@ -41,6 +43,10 @@ export default {
feat10Desc: "Créez un dossier de projet où vous voulez (git init optionnel) et lancez-y une session Claude, depuis n'importe quel appareil.",
feat16Title: 'Démarrez votre projet',
feat16Desc: 'Définissez vos commandes de démarrage une fois (serveur de dev, API, base de données), puis lancez chacune dans son terminal en un seul clic.',
feat17Title: 'Historique de branche',
feat17Desc: 'Voyez ce qui est déjà commité, quels commits ne sont pas encore poussés, et dépliez le diff complet de n’importe lequel, juste à côté de ce qui n’est pas commité.',
feat18Title: 'État git d’un coup d’œil',
feat18Desc: 'Chaque worktree porte ses compteurs : avance/retard, indexés, non indexés, conflits. Ils se rafraîchissent seuls pendant qu’un agent travaille, sans un clic.',
scAKicker: 'Supervision des sessions',
scATitle: 'Voyez ce qui vous attend, avant que ça ne bloque',
scABody:
@@ -58,6 +64,11 @@ export default {
grpTitle: 'Pilotez tous vos repos depuis une seule session Claude',
grpBody:
'Regroupez les repos qui avancent ensemble : un service, son client, sa doc. Lancez une seule session Claude qui les couvre tous à la fois : une conversation, un contexte partagé travaillant à travers chaque repo, au lieu de jongler avec un agent par repo.',
prereqTitle: 'Prérequis',
prereqDesc:
'Arboretum est publié sur un registre npm privé. Déclarez son scope une fois dans votre ~/.npmrc, sinon npm répond 404.',
prereqNote:
'Il vous faut aussi Node 22.16 ou plus récent (le daemon utilise node:sqlite) et le CLI Claude Code dans votre PATH. L’app de bureau n’a besoin d’aucun des deux : elle embarque son runtime.',
howKicker: 'Comment ça marche',
howTitle: 'Zéro install. Trois étapes.',
step1Title: 'Lancez le daemon',
@@ -84,20 +95,13 @@ export default {
footTag: 'un jardin de branches, une seule vitre.',
license: 'Licence MIT',
coffee: 'Paye-moi un café',
mIde: 'IDE',
mProjects: 'Projets',
mWorktrees: 'Worktrees',
mExplorer: 'Explorateur',
mEditor: 'Éditeur',
mTerminal: 'Terminal',
mGit: 'Git',
mSessions: 'Sessions',
mGroups: 'Groupes',
mSettings: 'Réglages',
mHelp: 'Aide',
mGitea: 'Gitea',
mMore: 'Plus',
mSearch: 'Rechercher',
mAttn: 'À traiter',
waiting: 'en attente',
busy: 'occupée',
@@ -139,16 +143,9 @@ export default {
wsDiff: 'Diff',
wsFiles: 'Fichiers',
wsChanges: 'Changements',
wsStaged: 'Indexés',
wsTerminal: 'Terminal',
wsCommitMsg: 'Implémente le rafraîchissement du token',
wsCommitPlaceholder: 'Message de commit…',
wsAmend: 'Amender le dernier commit',
wsGroups: 'Groupes',
wsCommitBtn: 'Commit',
wsPushBtn: 'Push',
wsStage: 'Indexer',
wsUnstage: 'Désindexer',
wsDiscard: 'Annuler',
// « Démarrer le projet » : lancement multi-terminaux
launchScKicker: 'Démarrer le projet',
@@ -168,7 +165,6 @@ export default {
rgTested: 'testée',
rgAddConnection: 'Ajouter une connexion',
rgEncrypted: 'Chiffré au repos',
rgCloning: 'Clonage',
rgCloneReceiving: 'Réception des objets',
// Pilier sécurité (secrets chiffrés)
@@ -176,20 +172,43 @@ export default {
sec5Desc: "Les identifiants git distants sont chiffrés au repos (AES-256-GCM) et jamais renvoyés en clair par l'API.",
// App de bureau (téléchargement)
wayKicker: 'Trois façons de l’utiliser',
wayTitle: 'App de bureau, serveur web, ou dans VS Code',
wayBody:
'Le même daemon alimente les trois. Choisissez celle qui correspond à la machine où vous êtes : elles partagent les mêmes données.',
wayDesktop: 'Application de bureau',
wayDesktopBody:
'Une fenêtre native qui démarre le daemon pour vous, déjà connectée, avec icône de barre système et lancement au démarrage. Rien à installer d’autre que l’app.',
wayDesktopLink: 'Télécharger',
wayServer: 'Serveur web auto-hébergé',
wayServerBody:
'Faites tourner le daemon sur votre poste et ouvrez son interface depuis n’importe quel appareil qui vous appartient : portable, tablette, téléphone. Tailscale Serve fournit HTTPS dans votre tailnet sans ouvrir de port, ce qui active aussi les notifications et l’installation PWA.',
wayVscode: 'Extension VS Code',
wayVscodeBody:
'Une extension native (pas un webview) connectée au même daemon : arbre temps réel des dépôts, worktrees et sessions, terminaux natifs, compteur de sessions en attente avec notifications, et actions git.',
wayVscodeLink: 'Obtenir le VSIX',
wayOriginNote:
'Une règle à retenir dès qu’on sort de localhost : le daemon rejette toute adresse dont on ne lui a pas parlé, avec un 403. Démarrez-le avec --allow-origin <votre URL> (répétable) et c’est réglé. Sortir de la boucle locale demande en outre un flag d’acquittement explicite, volontairement.',
wayBuildNote: 'Buildez l’app de bureau vous-même depuis',
dlKicker: 'App de bureau native',
dlTitle: 'Téléchargez Arboretum pour votre bureau',
dlBody:
"Une app native pour Linux, Windows et macOS. Elle embarque le daemon et son runtime Node : rien d'autre à installer, lancez-la et votre IDE multi-projet s'ouvre, déjà authentifié. Tray, lancement au login et auto-update inclus. Vous préférez le terminal ? Continuez à la lancer dans le navigateur en une commande.",
dlLinux: 'Linux',
dlLinuxHint: 'AppImage et .deb',
dlLinuxHint: '.deb (Debian, Ubuntu)',
dlLinuxAlt: 'AppImage (autres distributions)',
dlWin: 'Windows',
dlWinHint: 'Installeur NSIS et portable',
dlMac: 'macOS',
dlMacHint: 'dmg (best-effort, non signé)',
dlMacHint: 'à builder depuis les sources (non signé)',
dlNoNode: "Pas besoin d'installer Node",
dlBundled: 'Daemon et runtime embarqués',
dlAutoUpdate: 'Auto-update sur Windows et Linux',
dlVersion: 'Dernière version desktop : {version}',
dlAllAssets: 'Tous les fichiers de la release',
dlUnsigned:
'Les binaires ne sont pas signés. Sous Windows, SmartScreen affiche « éditeur inconnu » : choisissez Informations complémentaires, puis Exécuter quand même. Sous macOS, clic droit sur l’app puis Ouvrir.',
dlGet: "Obtenir l'app",
dlSource: 'Builder depuis les sources',
dlNote: 'Les installeurs sont publiés sur la page des releases dès qu\'un build desktop est taggé. En attendant, buildez depuis les sources (voir packages/desktop).',
dlNote: 'Les builds macOS sont produits à la demande (pas de runner macOS en CI) : construisez-les avec npm run dist:mac, ou demandez-en un.',
};
+24
View File
@@ -8,3 +8,27 @@ export const COFFEE = 'https://buymeacoffee.com/johanleroy';
// et sources du paquet Electron pour un build local.
export const RELEASES = `${REPO}/releases`;
export const DESKTOP_SRC = `${REPO}/src/branch/main/packages/desktop`;
// Versions publiées, source unique du site (affichées et utilisées pour construire les liens d'assets).
// À bumper avec les tags de release correspondants.
export const VERSIONS = {
daemon: '3.4.0',
desktop: '0.2.0',
vscode: '0.4.1',
} as const;
/**
* Lien direct d'un asset de release desktop. Le canal `desktop-latest` est un tag FLOTTANT recréé par la
* CI à chaque version : ces URL restent donc valides sans être rééditées à chaque release.
*/
const DESKTOP_LATEST = `${REPO}/releases/download/desktop-latest`;
export const DOWNLOADS = {
deb: `${DESKTOP_LATEST}/Arboretum-${VERSIONS.desktop}-amd64.deb`,
appImage: `${DESKTOP_LATEST}/Arboretum-${VERSIONS.desktop}-x86_64.AppImage`,
windows: `${DESKTOP_LATEST}/Arboretum-${VERSIONS.desktop}-x64.exe`,
vsix: `${REPO}/releases/tag/vscode-v${VERSIONS.vscode}`,
} as const;
/** Registre npm privé à déclarer avant tout `npx` : sans lui, npm renvoie un 404. */
export const NPM_REGISTRY = 'https://git.lidge.fr/api/packages/johanleroy/npm/';
export const NPMRC_LINE = '@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/';
+4 -2
View File
@@ -1,12 +1,14 @@
// Thème clair / sombre du site vitrine (aligné sur l'app : lib/theme.ts de packages/web).
// Singleton module Vue : `themeMode` (persisté en localStorage, clé `arb-theme`), `resolvedTheme`
// Singleton module Vue : `themeMode` (persisté en localStorage, clé `arb.theme`), `resolvedTheme`
// (résout `system` via prefers-color-scheme), application au <html> (dataset.theme + metas).
import { computed, ref, watch, type ComputedRef } from 'vue';
export type ThemeMode = 'dark' | 'light' | 'system';
export type ResolvedTheme = 'dark' | 'light';
const STORAGE_KEY = 'arb-theme';
// MÊME clé que l'app (packages/web/src/lib/theme.ts) : le site se présente comme aligné sur elle, et
// un visiteur qui bascule le thème ici retrouve le même sur son instance.
const STORAGE_KEY = 'arb.theme';
// Doit rester synchronisé avec --color-surface-0 (style.css) : fond du <html> + metas.
const BG: Record<ResolvedTheme, string> = { dark: '#09090b', light: '#fafafa' };
+6
View File
@@ -1,5 +1,11 @@
# Changelog
## 0.4.1
- Marketplace metadata completed: a PNG icon (required to publish anywhere), gallery banner, homepage,
issue tracker, and an explicit untrusted-workspace declaration (the extension only talks to your
daemon over HTTP/WS, it never executes workspace code).
## 0.4.0
Reflects the daemon's **"Start the project"** milestone in supervision (no editor duplicated here).
+2 -2
View File
@@ -53,13 +53,13 @@ The extension is bundled with esbuild (`@arboretum/shared` is inlined → the VS
npm install
npm run build:vscode # builds @arboretum/shared then bundles the extension
cd packages/vscode && npx @vscode/vsce package --no-dependencies
# → git-arboretum-0.3.0.vsix
# → git-arboretum-<version>.vsix
```
Install it with **Extensions: Install from VSIX…** in the Command Palette, or:
```bash
code --install-extension git-arboretum-0.3.0.vsix # also: codium / cursor
code --install-extension git-arboretum-<version>.vsix # also: codium / cursor
```
### Other distribution channels (optional)
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

+23 -7
View File
@@ -2,7 +2,7 @@
"name": "git-arboretum",
"displayName": "Arboretum",
"description": "Pilot your git worktrees and Claude Code sessions from VS Code: native terminals, live tree, waiting alerts.",
"version": "0.4.0",
"version": "0.4.1",
"private": true,
"publisher": "johanleroy",
"license": "MIT",
@@ -121,7 +121,7 @@
},
{
"command": "arboretum.answerSession",
"title": "Answer Prompt…",
"title": "Answer Prompt\u2026",
"category": "Arboretum",
"icon": "$(comment-discussion)"
},
@@ -151,13 +151,13 @@
},
{
"command": "arboretum.createWorktree",
"title": "Create Worktree…",
"title": "Create Worktree\u2026",
"category": "Arboretum",
"icon": "$(add)"
},
{
"command": "arboretum.commitWorktree",
"title": "Commit…",
"title": "Commit\u2026",
"category": "Arboretum",
"icon": "$(git-commit)"
},
@@ -175,7 +175,7 @@
},
{
"command": "arboretum.pullWorktree",
"title": "Pull…",
"title": "Pull\u2026",
"category": "Arboretum",
"icon": "$(arrow-down)"
},
@@ -199,7 +199,7 @@
},
{
"command": "arboretum.startGroupSession",
"title": "Start Group Session…",
"title": "Start Group Session\u2026",
"category": "Arboretum",
"icon": "$(play)"
},
@@ -222,7 +222,7 @@
},
{
"command": "arboretum.createWorktreeHere",
"title": "Create Worktree for Current Folder…",
"title": "Create Worktree for Current Folder\u2026",
"category": "Arboretum"
},
{
@@ -465,5 +465,21 @@
"esbuild": "^0.21.0",
"typescript": "^5.7.0",
"ws": "^8.18.0"
},
"icon": "media/icon.png",
"galleryBanner": {
"color": "#09090b",
"theme": "dark"
},
"homepage": "https://git-arboretum.com",
"bugs": {
"url": "https://git.lidge.fr/johanleroy/arboretum/issues"
},
"qna": false,
"capabilities": {
"untrustedWorkspaces": {
"supported": true,
"description": "The extension only talks to your Arboretum daemon over HTTP/WS; it never executes workspace code."
}
}
}
+77 -4
View File
@@ -1,15 +1,88 @@
{
"id": "/",
"name": "Arboretum",
"short_name": "Arboretum",
"description": "A self-hosted dashboard for your git worktrees and Claude Code sessions.",
"description": "Self-hosted multi-project AI IDE for your git worktrees and Claude Code sessions.",
"lang": "en",
"dir": "ltr",
"categories": [
"developer",
"productivity",
"utilities"
],
"start_url": "/",
"scope": "/",
"display": "standalone",
"display_override": [
"window-controls-overlay",
"standalone"
],
"orientation": "any",
"background_color": "#09090b",
"theme_color": "#09090b",
"launch_handler": {
"client_mode": "focus-existing"
},
"icons": [
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" },
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
{
"src": "/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"screenshots": [
{
"src": "/screenshot-ide-dark.png",
"type": "image/png",
"sizes": "2340x1196",
"form_factor": "wide",
"label": "Multi-project IDE, dark theme"
},
{
"src": "/screenshot-ide-light.png",
"type": "image/png",
"sizes": "2340x1196",
"form_factor": "wide",
"label": "Multi-project IDE, light theme"
}
],
"shortcuts": [
{
"name": "IDE",
"url": "/ide"
},
{
"name": "Sessions",
"url": "/sessions"
},
{
"name": "Settings",
"url": "/settings"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

+3
View File
@@ -12,6 +12,7 @@
import { computed } from 'vue';
import { wsClient } from './lib/ws-client';
import { useRealtimeBootstrap } from './composables/useRealtimeBootstrap';
import { useWatchedWorktrees } from './composables/useWatchedWorktrees';
import WsBanner from './components/layout/WsBanner.vue';
import ToastContainer from './components/ToastContainer.vue';
import CommandPalette from './components/CommandPalette.vue';
@@ -21,4 +22,6 @@ const wsReconnecting = computed(() => wsClient.status.value === 'reconnecting');
// Propriétaire unique du chargement initial + temps réel : hissé ici (App.vue toujours monté)
// pour couvrir l'IDE plein écran comme le login.
useRealtimeBootstrap();
// Idem pour les abonnements ciblés `watch` : ils doivent survivre au démontage des panneaux.
useWatchedWorktrees();
</script>
@@ -102,7 +102,7 @@ const basename = (p: string): string => p.split('/').filter(Boolean).pop() ?? p;
const items = computed<PaletteItem[]>(() => {
const out: PaletteItem[] = [];
for (const r of worktrees.repos) {
for (const r of worktrees.visibleRepos) {
out.push({ id: `repo-${r.id}`, type: 'repo', label: r.label, sublabel: r.path, icon: GitBranch as Component, keywords: `${r.label} ${r.path}`.toLowerCase(), run: () => revealRepo(r.id) });
out.push({
id: `launch-${r.id}`,
+26 -21
View File
@@ -1,26 +1,31 @@
<template>
<div class="pointer-events-none fixed inset-x-0 bottom-0 z-50 flex flex-col items-end gap-2 p-4 sm:bottom-4 sm:right-4 sm:left-auto sm:p-0">
<TransitionGroup name="toast">
<div
v-for="toast in store.toasts"
:key="toast.id"
class="pointer-events-auto flex w-full max-w-sm items-start gap-2 rounded-lg border px-3 py-2 shadow-pop"
:class="toneClass(toast.kind)"
:role="toast.kind === 'error' ? 'alert' : 'status'"
:aria-live="toast.kind === 'error' ? 'assertive' : 'polite'"
>
<component :is="icon(toast.kind)" :size="16" class="mt-0.5 shrink-0" />
<span class="min-w-0 flex-1 break-words text-sm">{{ toast.message }}</span>
<button
class="shrink-0 rounded p-0.5 opacity-70 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong/50"
:aria-label="t('toast.dismiss')"
@click="store.dismiss(toast.id)"
<!-- Téléporté dans body et au-dessus des modals (z-60) : rendu dans #app au même z-50 qu'eux, il
passait DERRIÈRE leur backdrop, puisque les nœuds téléportés sont insérés après #app. Or les
toasts d'erreur sont persistants : ils s'empilaient invisibles pendant qu'un modal était ouvert. -->
<Teleport to="body">
<div class="pointer-events-none fixed inset-x-0 bottom-0 z-60 flex flex-col items-end gap-2 p-4 sm:bottom-4 sm:right-4 sm:left-auto sm:p-0">
<TransitionGroup name="toast">
<div
v-for="toast in store.toasts"
:key="toast.id"
class="pointer-events-auto flex w-full max-w-sm items-start gap-2 rounded-lg border px-3 py-2 shadow-pop"
:class="toneClass(toast.kind)"
:role="toast.kind === 'error' ? 'alert' : 'status'"
:aria-live="toast.kind === 'error' ? 'assertive' : 'polite'"
>
<X :size="14" />
</button>
</div>
</TransitionGroup>
</div>
<component :is="icon(toast.kind)" :size="16" class="mt-0.5 shrink-0" />
<span class="min-w-0 flex-1 break-words text-sm">{{ toast.message }}</span>
<button
class="shrink-0 rounded p-0.5 opacity-70 transition-opacity hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong/50"
:aria-label="t('toast.dismiss')"
@click="store.dismiss(toast.id)"
>
<X :size="14" />
</button>
</div>
</TransitionGroup>
</div>
</Teleport>
</template>
<script setup lang="ts">
+41 -2
View File
@@ -42,8 +42,8 @@
:wt="activeTab.wtPath"
:file="activeTab.file"
:staged="!!activeTab.diffStaged"
:version="0"
class="h-full overflow-auto"
:version="activeVersion"
class="h-full"
/>
</div>
</template>
@@ -61,6 +61,7 @@ import { useI18n } from 'vue-i18n';
import { FileCode, Save, TriangleAlert } from '@lucide/vue';
import type * as Monaco from 'monaco-editor';
import { useIdeStore, type EditorTab } from '../../stores/ide';
import { useWorktreesStore } from '../../stores/worktrees';
import { gitApi } from '../../lib/git-api';
import { ApiError } from '../../lib/api';
import { loadMonaco } from '../../composables/useMonaco';
@@ -79,6 +80,7 @@ interface ModelEntry {
const { t } = useI18n();
const ide = useIdeStore();
const worktrees = useWorktreesStore();
const host = useTemplateRef<HTMLDivElement>('host');
const ready = ref(false);
@@ -94,6 +96,12 @@ let shownTabId: string | null = null;
let disposed = false;
const activeTab = computed(() => ide.activeTab);
// Jeton d'invalidation du worktree de l'onglet actif : alimente le diff (qui ne se rafraîchissait
// jamais, la version étant câblée à 0) et la synchronisation disque de l'éditeur.
const activeVersion = computed(() => {
const tab = activeTab.value;
return tab ? worktrees.changeVersion(tab.repoId, tab.wtPath) : 0;
});
const viewOptions = computed(() => [
{ value: 'editor', label: t('workspace.editor') },
{ value: 'diff', label: t('workspace.diff') },
@@ -225,6 +233,37 @@ async function reload(): Promise<void> {
}
}
/**
* Le worktree de l'onglet actif a bougé sur le disque (agent, git checkout, build) : on aligne le
* buffer AVANT que l'utilisateur ne s'en aperçoive. Buffer propre → rechargement silencieux ; buffer
* modifié → bannière de conflit, jamais d'écrasement d'une saisie en cours. Auparavant le conflit
* n'apparaissait qu'au moment de la sauvegarde (409 STALE_FILE), donc trop tard.
*/
async function syncActiveTabFromDisk(): Promise<void> {
const tab = activeTab.value;
if (!tab || tab.view !== 'editor' || saving.value) return;
const entry = entries.get(tab.id);
if (!entry) return;
try {
const res = await gitApi.readFile(tab.repoId, tab.wtPath, tab.file);
if (res.mtime === entry.baseMtime || res.content === entry.savedContent) return; // ce fichier-là n'a pas changé
if (ide.isDirty(tab.id)) {
conflict.value = true;
return;
}
entry.model.setValue(res.content);
entry.baseMtime = res.mtime;
entry.savedContent = res.content;
ide.setTabDirty(tab.id, false);
} catch {
/* fichier supprimé ou illisible : on laisse l'onglet en place, la sauvegarde tranchera */
}
}
watch(activeVersion, () => {
if (ready.value) void syncActiveTabFromDisk();
});
// changement d'onglet actif -> affiche le bon modèle (si vue éditeur).
watch(
() => [activeTab.value?.id, activeTab.value?.view] as const,
@@ -1,5 +1,5 @@
<template>
<div class="flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
<div class="no-scrollbar flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
<div
v-for="tab in ide.editorTabs"
:key="tab.id"
Binary file not shown.
+98 -16
View File
@@ -8,14 +8,27 @@
</div>
<div class="min-h-0 flex-1 overflow-auto px-1 pb-2">
<p v-if="groups.groups.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('groups.empty') }}</p>
<!-- chargement / échec / vide distingués (cf. ProjectTree) -->
<SkeletonRow v-if="groups.loading && groups.groups.length === 0" :count="3" :height="22" class="px-2 py-1" />
<div v-else-if="groups.loadError" class="px-2 py-1 text-xs">
<p class="text-danger">{{ groups.loadError }}</p>
<button type="button" class="mt-1 rounded px-1 text-accent hover:bg-surface-2" @click="groups.fetchGroups()">
{{ t('common.retry') }}
</button>
</div>
<p v-else-if="groups.groups.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('groups.empty') }}</p>
<div v-for="g in groups.groups" :key="g.id">
<div
class="group flex items-center rounded text-xs text-fg-muted hover:bg-surface-2/60"
@contextmenu.prevent="openGroupMenu($event, g)"
>
<button type="button" class="flex min-w-0 flex-1 items-center gap-1.5 px-2 py-1 text-left" @click="toggleExpand(g.id)">
<button
type="button"
class="flex min-w-0 flex-1 items-center gap-1.5 px-2 py-1 text-left"
:title="groupTitle(g)"
@click="ide.toggleGroup(g.id)"
>
<component :is="isExpanded(g.id) ? ChevronDown : ChevronRight" :size="14" class="shrink-0 text-fg-subtle" />
<Boxes
:size="13"
@@ -36,17 +49,50 @@
</button>
</div>
<div v-if="isExpanded(g.id)" class="pl-6">
<div v-if="isExpanded(g.id)" class="pl-4">
<!-- Composition réelle du groupe : chaque dépôt membre avec SES worktrees et leur statut git.
Répond enfin à « quels worktrees existent dans ce groupe et lesquels sont actifs », qui
exigeait auparavant d'ouvrir le modal d'édition puis de déplier l'autre panneau. -->
<p v-if="groups.reposInGroup(g.id).length === 0" class="px-2 py-0.5 text-[11px] text-fg-subtle">
{{ t('groups.noRepos') }}
</p>
<div v-for="repo in groups.reposInGroup(g.id)" :key="repo.id">
<div class="flex items-center gap-1 px-2 py-0.5 text-[11px] text-fg-muted">
<FolderGit2 :size="11" class="shrink-0 text-fg-subtle" />
<span class="min-w-0 truncate" :title="repo.path">{{ repo.label }}</span>
</div>
<button
v-for="wt in worktrees.worktreesForRepo(repo.id)"
:key="wt.path"
type="button"
class="flex w-full items-center gap-1 rounded py-0.5 pr-2 pl-5 text-left text-[11px] hover:bg-surface-2/60"
:class="isActiveWt(wt) ? 'bg-surface-2 text-fg' : 'text-fg-muted'"
@click="reveal(wt)"
>
<component :is="wt.isMain ? Home : GitBranch" :size="11" class="shrink-0 text-fg-subtle" />
<span class="min-w-0 truncate font-mono" :title="wt.branch ?? wt.head">{{ wt.branch ?? wt.head.slice(0, 7) }}</span>
<span v-if="sessionCount(wt) > 0" class="shrink-0 text-fg-subtle" :title="t('groups.sessionCount', sessionCount(wt))">
<SquareTerminal :size="11" />
</span>
<GitStatusBadge :git="wt.git" :branch="wt.branch" dense class="ml-auto shrink-0 pl-1" />
</button>
</div>
<!-- sessions du groupe (une session de groupe couvre plusieurs dépôts : elle n'appartient à
aucun worktree en particulier) -->
<p v-if="groupSessions(g.id).length > 0" class="px-2 pt-1 text-[10px] text-fg-subtle">{{ t('groups.sessions') }}</p>
<button
v-for="s in liveSessionsFor(g.id)"
v-for="s in groupSessions(g.id)"
:key="s.id"
type="button"
class="flex w-full items-center gap-1.5 rounded px-2 py-0.5 text-left text-[11px]"
:class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted hover:bg-surface-2/60'"
:title="sessionTitle(s)"
@click="ide.openTerminal(s.id)"
>
<SessionStateBadge :session="s" />
<span class="truncate font-mono">{{ sessionLabel(s, worktrees) }}</span>
<span class="min-w-0 truncate font-mono" :class="s.live ? '' : 'text-fg-subtle'">{{ sessionLabel(s, worktrees) }}</span>
<span v-if="s.addedDirs?.length" class="shrink-0 text-[10px] text-fg-subtle">·{{ s.addedDirs.length }}</span>
</button>
<button
type="button"
@@ -65,10 +111,22 @@
<script setup lang="ts">
// Panneau Groupes de l'IDE : création, composition, lancement d'une session de groupe et ouverture
// des sessions du groupe dans le dock. Tout via le store groups / modals ; aucune navigation.
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Boxes, ChevronDown, ChevronRight, Combine, MoreVertical, Pencil, Plus, Trash2 } from '@lucide/vue';
import type { GroupSummary } from '@arboretum/shared';
import {
Boxes,
ChevronDown,
ChevronRight,
Combine,
FolderGit2,
GitBranch,
Home,
MoreVertical,
Pencil,
Plus,
SquareTerminal,
Trash2,
} from '@lucide/vue';
import type { GroupSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
import { useGroupsStore } from '../../stores/groups';
import { useWorktreesStore } from '../../stores/worktrees';
import { useSessionsStore } from '../../stores/sessions';
@@ -77,6 +135,8 @@ import { useModalsStore } from '../../stores/modals';
import { useToastsStore } from '../../stores/toasts';
import { useContextMenu, type ContextMenuItem } from '../../composables/useContextMenu';
import { sessionLabel } from '../../lib/session-label';
import GitStatusBadge from '../workspace/GitStatusBadge.vue';
import SkeletonRow from '../ui/SkeletonRow.vue';
import SessionStateBadge from '../SessionStateBadge.vue';
import GroupSessionModal from '../GroupSessionModal.vue';
import GroupCreateModal from './modals/GroupCreateModal.vue';
@@ -92,18 +152,40 @@ const modals = useModalsStore();
const toasts = useToastsStore();
const ctx = useContextMenu();
const expanded = ref<string[]>([]);
const isExpanded = (id: string): boolean => expanded.value.includes(id);
function toggleExpand(id: string): void {
expanded.value = isExpanded(id) ? expanded.value.filter((x) => x !== id) : [...expanded.value, id];
}
// L'expansion vit dans le store IDE (persistée, comme celle des dépôts) : ce panneau est démonté à
// chaque changement d'onglet de l'ActivityBar, un état local était donc perdu à chaque aller-retour.
const isExpanded = (id: string): boolean => ide.expandedGroupIds.includes(id);
// sessions vivantes du groupe, en version live (store sessions).
function liveSessionsFor(id: string) {
const isActiveWt = (wt: WorktreeSummary): boolean =>
ide.activeContext?.repoId === wt.repoId && ide.activeContext?.wtPath === wt.path;
/** Sessions du groupe, résolues sur le store sessions (vivantes d'abord, puis les terminées). */
function groupSessions(id: string): SessionSummary[] {
return groups
.sessionsInGroup(id)
.map((s) => sessions.sessions.find((x) => x.id === s.id) ?? s)
.filter((s) => s.live);
.sort((a, b) => Number(b.live) - Number(a.live) || b.createdAt.localeCompare(a.createdAt));
}
const sessionCount = (wt: WorktreeSummary): number => wt.sessions.filter((s) => s.live).length;
/** Infobulle du groupe : sa description (jamais affichée jusqu'ici) et le nombre de worktrees. */
function groupTitle(g: GroupSummary): string {
const lines = [g.label];
if (g.description) lines.push(g.description);
lines.push(t('groups.worktreeCount', groups.worktreesInGroup(g.id).length));
return lines.join('\n');
}
function sessionTitle(s: SessionSummary): string {
const lines = [s.title ? `${s.title} (${s.command})` : s.command, s.cwd];
if (s.addedDirs?.length) lines.push(`--add-dir : ${s.addedDirs.join(', ')}`);
return lines.join('\n');
}
/** Rend le worktree actif et visible dans l'explorateur (déplie son dépôt). */
function reveal(wt: WorktreeSummary): void {
ide.revealWorktree(wt.repoId, wt.path);
}
function openNewGroup(): void {
+16 -2
View File
@@ -2,11 +2,13 @@
<div class="flex h-dvh min-h-0 flex-col bg-surface-0 text-fg">
<div v-if="isMobile" class="flex min-h-0 flex-1 flex-col">
<header class="flex items-center gap-2 border-b border-border px-3 py-2">
<span class="min-w-0 flex-1 truncate text-sm font-medium">{{ mobileTitle }}</span>
<span class="min-w-0 flex-1 truncate text-sm font-medium" :title="mobileTitle">{{ mobileTitle }}</span>
<button type="button" class="rounded p-1 text-fg-muted hover:bg-surface-2 hover:text-fg" :title="t('common.settings')" @click="openMobileMenu">
<MoreVertical :size="18" />
</button>
</header>
<!-- « À traiter » visible quel que soit le panneau mobile actif (cf. PrimarySidebar côté desktop) -->
<AttentionList />
<div class="min-h-0 flex-1 overflow-hidden">
<ProjectTree v-if="ide.mobilePanel === 'explorer'" />
<GitPanel v-else-if="ide.mobilePanel === 'git'" />
@@ -15,6 +17,9 @@
<GroupsPanel v-else-if="ide.mobilePanel === 'groups'" />
<EditorArea v-else />
</div>
<!-- Barre de statut aussi sur mobile : c'est le seul endroit qui donne l'état de la connexion WS
et le statut git fin du worktree actif, jusqu'ici réservés au desktop. -->
<StatusBar />
<nav class="flex shrink-0 border-t border-border">
<button
v-for="p in mobilePanels"
@@ -86,6 +91,7 @@ import ProjectTree from './ProjectTree.vue';
import GitPanel from './GitPanel.vue';
import SessionsPanel from './SessionsPanel.vue';
import GroupsPanel from './GroupsPanel.vue';
import AttentionList from './AttentionList.vue';
import ModalHost from './ModalHost.vue';
import ContextMenu from './ContextMenu.vue';
@@ -115,12 +121,20 @@ let mql: MediaQueryList | null = null;
const syncMobile = (): void => {
isMobile.value = !!mql?.matches;
};
// Les tailles de panneaux sont persistées : une fenêtre plus petite qu'à la session précédente
// pouvait faire sortir la barre de statut du cadre. On reclampe au montage et à chaque resize.
const clampPanels = (): void => ide.clampToViewport(window.innerWidth, window.innerHeight);
onMounted(() => {
mql = window.matchMedia('(max-width: 767px)');
syncMobile();
mql.addEventListener('change', syncMobile);
clampPanels();
window.addEventListener('resize', clampPanels);
});
onBeforeUnmount(() => {
mql?.removeEventListener('change', syncMobile);
window.removeEventListener('resize', clampPanels);
});
onBeforeUnmount(() => mql?.removeEventListener('change', syncMobile));
const mobilePanels = computed(() => [
{ key: 'explorer', icon: FolderTree, label: t('ide.activity.explorer') },
+73 -9
View File
@@ -1,28 +1,92 @@
<template>
<Teleport to="body">
<component
:is="entry.component"
<!-- Un conteneur par entrée : il porte la sémantique de dialogue et le piège de focus, ce qui
évite de la dupliquer (et de l'oublier) dans chacun des modals. -->
<div
v-for="entry in modals.stack"
:key="entry.id"
v-bind="entry.props"
@close="modals.close(entry.id)"
/>
ref="hosts"
role="dialog"
aria-modal="true"
@keydown="onTrapKey"
>
<component :is="entry.component" v-bind="entry.props" @close="modals.close(entry.id)" />
</div>
</Teleport>
</template>
<script setup lang="ts">
// Hôte de la pile de modals : rend chaque entrée via <component :is>. Les modals fournissent
// eux-mêmes leur backdrop plein écran (fixed inset-0 z-50), donc l'hôte ne dessine rien. Escape
// ferme le sommet de la pile. Monté une seule fois par IdeShell (via Teleport, l'emplacement dans
// le template importe peu, mais l'hôte doit rester monté tant que l'IDE vit).
import { onBeforeUnmount, onMounted } from 'vue';
// eux-mêmes leur backdrop plein écran (fixed inset-0 z-50), donc l'hôte ne dessine rien. Monté une
// seule fois par IdeShell (via Teleport, l'emplacement dans le template importe peu, mais l'hôte doit
// rester monté tant que l'IDE vit).
//
// L'accessibilité est traitée ICI pour couvrir les 11 modals d'un coup : rôle de dialogue, focus
// initial sur le premier élément focusable, piège de Tab (sinon le focus part derrière le backdrop,
// dans l'IDE qui reste visible), restauration du focus à la fermeture, et Escape.
import { nextTick, onBeforeUnmount, onMounted, ref, useTemplateRef, watch } from 'vue';
import { useModalsStore } from '../../stores/modals';
const modals = useModalsStore();
const hosts = useTemplateRef<HTMLElement[]>('hosts');
/** Élément qui avait le focus avant l'ouverture du premier modal de la pile. */
const focusBeforeOpen = ref<HTMLElement | null>(null);
const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
function topHost(): HTMLElement | null {
const list = hosts.value;
return list && list.length > 0 ? (list[list.length - 1] ?? null) : null;
}
function focusables(host: HTMLElement): HTMLElement[] {
return [...host.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => el.offsetParent !== null || el === document.activeElement);
}
function onKey(e: KeyboardEvent): void {
if (e.key === 'Escape' && modals.stack.length > 0) modals.close();
}
/** Tab / Shift+Tab cyclent dans le modal du sommet, jamais en dehors. */
function onTrapKey(e: KeyboardEvent): void {
if (e.key !== 'Tab') return;
const host = topHost();
if (!host) return;
const items = focusables(host);
if (items.length === 0) return;
const first = items[0];
const last = items[items.length - 1];
if (!first || !last) return;
const active = document.activeElement as HTMLElement | null;
if (e.shiftKey && (active === first || !host.contains(active))) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
}
watch(
() => modals.stack.length,
(n, prev) => {
if (n > 0 && (prev ?? 0) === 0) {
focusBeforeOpen.value = document.activeElement as HTMLElement | null;
}
if (n > (prev ?? 0)) {
// laisse le modal se rendre avant de chercher sa première cible focusable
void nextTick(() => {
const host = topHost();
const target = host ? focusables(host)[0] : null;
target?.focus();
});
} else if (n === 0) {
focusBeforeOpen.value?.focus();
focusBeforeOpen.value = null;
}
},
);
onMounted(() => window.addEventListener('keydown', onKey));
onBeforeUnmount(() => window.removeEventListener('keydown', onKey));
</script>
@@ -1,20 +1,34 @@
<template>
<!-- Cible élargie sans épaissir le trait : la poignée fait 1px de visuel mais capte les pointeurs
sur ~7px grâce à un pseudo-élément (`splitter-hit`), sinon elle est presque impossible à saisir. -->
<div
class="shrink-0 bg-transparent transition-colors hover:bg-accent/40"
class="splitter-hit relative shrink-0 bg-transparent transition-colors hover:bg-accent/40 focus-visible:bg-accent/60 focus-visible:outline-none"
:class="axis === 'x' ? 'w-1 cursor-col-resize' : 'h-1 cursor-row-resize'"
role="separator"
tabindex="0"
:aria-orientation="axis === 'x' ? 'vertical' : 'horizontal'"
:aria-label="label"
:aria-valuenow="size"
:aria-valuemin="min"
:aria-valuemax="max"
@pointerdown="onPointerDown"
@keydown="onKeyDown"
/>
</template>
<script setup lang="ts">
// Poignée de redimensionnement réutilisable pour les panneaux de l'IDE.
// La taille est un v-model (px) que le parent persiste via le store IDE.
// Accessible : focusable, valeurs ARIA renseignées, et pilotable au clavier (flèches, PageUp/Down,
// Home/End) · elle n'était utilisable qu'à la souris.
import { useI18n } from 'vue-i18n';
import { useSplitter } from '../../composables/useSplitter';
const size = defineModel<number>({ required: true });
const props = defineProps<{ axis: 'x' | 'y'; min: number; max: number; invert?: boolean }>();
const props = defineProps<{ axis: 'x' | 'y'; min: number; max: number; invert?: boolean; label?: string }>();
const { t } = useI18n();
const label = props.label ?? t('ide.resizePanel');
const { onPointerDown } = useSplitter({
axis: props.axis,
@@ -26,4 +40,41 @@ const { onPointerDown } = useSplitter({
size.value = v;
},
});
const STEP = 16;
const PAGE = 64;
function apply(delta: number): void {
size.value = Math.min(props.max, Math.max(props.min, size.value + delta));
}
function onKeyDown(e: KeyboardEvent): void {
// L'axe détermine les touches utiles ; `invert` (dock du bas) inverse le sens naturel.
const dir = props.invert ? -1 : 1;
const grow = props.axis === 'x' ? 'ArrowRight' : 'ArrowDown';
const shrink = props.axis === 'x' ? 'ArrowLeft' : 'ArrowUp';
switch (e.key) {
case grow:
apply(STEP * dir);
break;
case shrink:
apply(-STEP * dir);
break;
case 'PageUp':
apply(PAGE * dir);
break;
case 'PageDown':
apply(-PAGE * dir);
break;
case 'Home':
size.value = props.min;
break;
case 'End':
size.value = props.max;
break;
default:
return;
}
e.preventDefault();
}
</script>
@@ -3,6 +3,10 @@
class="flex min-h-0 shrink-0 flex-col border-r border-border bg-surface-1"
:style="{ width: `${ide.leftWidth}px` }"
>
<!-- « À traiter » en tête de sidebar, quel que soit l'onglet actif : une session bloquée sur un
dialogue Claude attend une réponse, et l'information n'était visible que dans le panneau
Sessions (le badge chiffré de l'ActivityBar était le seul signal ailleurs). -->
<AttentionList />
<ProjectTree v-if="ide.activeActivity === 'explorer'" />
<GitPanel v-else-if="ide.activeActivity === 'git'" />
<SessionsPanel v-else-if="ide.activeActivity === 'sessions'" />
@@ -12,6 +16,7 @@
<script setup lang="ts">
import { useIdeStore } from '../../stores/ide';
import AttentionList from './AttentionList.vue';
import ProjectTree from './ProjectTree.vue';
import GitPanel from './GitPanel.vue';
import SessionsPanel from './SessionsPanel.vue';
@@ -4,12 +4,13 @@
{{ t('ide.projects') }}
<button
type="button"
class="ml-auto rounded p-0.5 hover:bg-surface-2 hover:text-fg"
class="ml-auto rounded p-0.5 hover:bg-surface-2 hover:text-fg disabled:opacity-40"
:title="t('repos.scan')"
:disabled="scanning"
@click="onScan"
>
<ScanSearch :size="14" />
<!-- retour visuel explicite : un scan peut durer plusieurs secondes -->
<ScanSearch :size="14" :class="scanning ? 'animate-spin' : ''" />
</button>
<button type="button" class="rounded p-0.5 hover:bg-surface-2 hover:text-fg" :title="t('ide.addProject')" @click="openAddMenu">
<Plus :size="14" />
@@ -17,11 +18,29 @@
</div>
<div class="min-h-0 flex-1 overflow-auto pb-2">
<p v-if="repos.length === 0" class="px-3 py-2 text-xs text-fg-subtle">{{ t('ide.noProjects') }}</p>
<!-- Distinguer les trois états : chargement, échec, vide. L'UI affichait « Aucun projet » dans
les trois cas, y compris quand le premier fetch avait échoué. -->
<SkeletonRow v-if="worktrees.loading && repos.length === 0" :count="4" :height="22" class="px-2 py-1" />
<div v-else-if="worktrees.loadError" class="px-3 py-2 text-xs">
<p class="text-danger">{{ worktrees.loadError }}</p>
<button type="button" class="mt-1 rounded px-1 text-accent hover:bg-surface-2" @click="worktrees.fetchAll()">
{{ t('common.retry') }}
</button>
</div>
<p v-else-if="repos.length === 0" class="px-3 py-2 text-xs text-fg-subtle">{{ t('ide.noProjects') }}</p>
<ProjectTreeNode v-for="repo in repos" :key="repo.id" :repo="repo" />
</div>
<DirectoryPicker v-if="showPicker" mode="repo" :initial-path="''" @select="onPick" @close="showPicker = false" />
<!-- Le sélecteur de dossier a besoin de largeur (chemin + boutons sur une ligne) : dans une sidebar
de 200 px minimum il était illisible. On le présente donc en surcouche centrée, sans changer le
composant (il reste utilisé en ligne dans les Réglages, où la place ne manque pas). -->
<Teleport to="body">
<div v-if="showPicker" class="fixed inset-0 z-50 flex items-start justify-center bg-black/60 p-4 sm:p-8" @click.self="showPicker = false">
<div class="w-full max-w-xl rounded-[14px] border border-border bg-surface-1 p-3 shadow-pop">
<DirectoryPicker mode="repo" :initial-path="''" @select="onPick" @close="showPicker = false" />
</div>
</div>
</Teleport>
</div>
</template>
@@ -36,6 +55,7 @@ import { useContextMenu } from '../../composables/useContextMenu';
import ProjectTreeNode from './ProjectTreeNode.vue';
import DirectoryPicker from '../DirectoryPicker.vue';
import CloneRepoModal from '../CloneRepoModal.vue';
import SkeletonRow from '../ui/SkeletonRow.vue';
const { t } = useI18n();
const worktrees = useWorktreesStore();
@@ -54,9 +74,7 @@ function openAddMenu(e: MouseEvent): void {
]);
}
const repos = computed(() =>
[...worktrees.repos].filter((r) => !r.hidden).sort((a, b) => a.label.localeCompare(b.label)),
);
const repos = computed(() => worktrees.visibleRepos);
async function onScan(): Promise<void> {
scanning.value = true;
@@ -5,10 +5,12 @@
class="group flex items-center rounded text-xs text-fg hover:bg-surface-2/60"
@contextmenu.prevent="openRepoMenu($event)"
>
<button type="button" class="flex min-w-0 flex-1 items-center gap-1 px-2 py-1 text-left" @click="ide.toggleRepo(repo.id)">
<button type="button" class="flex min-w-0 flex-1 items-center gap-1 px-2 py-1 text-left" :title="repoTitle" @click="ide.toggleRepo(repo.id)">
<component :is="repoExpanded ? ChevronDown : ChevronRight" :size="14" class="shrink-0 text-fg-subtle" />
<FolderGit2 :size="13" class="shrink-0 text-fg-subtle" />
<span class="truncate font-medium">{{ repo.label }}</span>
<FolderGit2 :size="13" class="shrink-0" :class="repo.valid ? 'text-fg-subtle' : 'text-danger'" :style="groupTint" />
<span class="truncate font-medium" :class="repo.valid ? '' : 'text-danger'">{{ repo.label }}</span>
<!-- dépôt disparu du disque : l'information existait côté serveur (`valid`) sans jamais être affichée -->
<TriangleAlert v-if="!repo.valid" :size="12" class="shrink-0 text-danger" />
<span v-if="worktreeList.length" class="ml-auto shrink-0 pl-1 text-[10px] text-fg-subtle">{{ worktreeList.length }}</span>
</button>
<button
@@ -34,8 +36,12 @@
<button type="button" class="flex min-w-0 flex-1 items-center gap-1 px-2 py-1 text-left" @click="onWtClick(wt)">
<component :is="isWtExpanded(wt) ? ChevronDown : ChevronRight" :size="14" class="shrink-0 text-fg-subtle" />
<component :is="wt.isMain ? Home : GitBranch" :size="12" class="shrink-0 text-fg-subtle" />
<span class="truncate font-mono">{{ wt.branch ?? wt.head.slice(0, 7) }}</span>
<span v-if="isDirty(wt)" class="ml-auto shrink-0 pl-1 text-warn" :title="t('worktrees.dirty', { n: wt.git.dirtyCount })">●</span>
<span class="min-w-0 truncate font-mono" :title="wt.branch ?? wt.head">{{ wt.branch ?? wt.head.slice(0, 7) }}</span>
<!-- états rares mais décisifs, jusqu'ici invisibles partout dans l'UI -->
<Lock v-if="wt.locked" :size="11" class="shrink-0 text-fg-subtle" :title="t('git.locked')" />
<Unlink v-if="wt.prunable" :size="11" class="shrink-0 text-warn" :title="t('git.prunable')" />
<!-- compteurs git complets (ahead/behind, indexé/non indexé, conflits) + détail en infobulle -->
<GitStatusBadge :git="wt.git" :branch="wt.branch" dense class="ml-auto shrink-0 pl-1" />
</button>
<button
type="button"
@@ -47,17 +53,20 @@
</button>
</div>
<!-- sessions live corrélées au worktree (par cwd) -->
<!-- sessions live rattachées au worktree (cwd, sous-répertoire, ou --add-dir de groupe) -->
<button
v-for="s in sessionsFor(wt)"
:key="s.id"
type="button"
class="flex w-full items-center gap-1.5 rounded py-0.5 pr-2 pl-9 text-left text-[11px] hover:bg-surface-2/60"
:class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted'"
:title="sessionTitle(s)"
@click="ide.openTerminal(s.id)"
>
<SessionStateBadge :session="s" />
<span class="truncate font-mono">{{ s.command }}</span>
<span class="min-w-0 truncate font-mono">{{ s.title ?? s.command }}</span>
<!-- session de groupe : elle couvre d'autres dépôts, ce n'est pas un terminal local -->
<Boxes v-if="s.groupId" :size="11" class="shrink-0 text-fg-subtle" />
</button>
<!-- fichiers du worktree (arbre embarqué, chargé paresseusement au dépliage) -->
@@ -67,6 +76,7 @@
:active="activeFileFor(wt)"
embedded
:depth="0"
:version="worktrees.changeVersion(wt.repoId, wt.path)"
@open="(rel) => ide.openFile(wt.repoId, wt.path, rel)"
/>
</div>
@@ -79,31 +89,37 @@
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ArrowUp,
Boxes,
ChevronDown,
ChevronRight,
FolderGit2,
GitBranch,
Home,
MoreVertical,
SquareTerminal,
GitCompare,
Upload,
ArrowUp,
Trash2,
Scissors,
Eye,
EyeOff,
FolderGit2,
GitBranch,
GitCompare,
Home,
Lock,
MoreVertical,
Rocket,
Scissors,
SquareTerminal,
Trash2,
TriangleAlert,
Unlink,
Upload,
} from '@lucide/vue';
import type { RepoSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
import { sessionBelongsToWorktree, type RepoSummary, type SessionSummary, type WorktreeSummary } from '@arboretum/shared';
import { ApiError } from '../../lib/api';
import { useIdeStore } from '../../stores/ide';
import { useWorktreesStore } from '../../stores/worktrees';
import { useSessionsStore } from '../../stores/sessions';
import { useGroupsStore } from '../../stores/groups';
import { useToastsStore } from '../../stores/toasts';
import { useModalsStore } from '../../stores/modals';
import { useContextMenu, type ContextMenuItem } from '../../composables/useContextMenu';
import FileTree from '../workspace/FileTree.vue';
import GitStatusBadge from '../workspace/GitStatusBadge.vue';
import SessionStateBadge from '../SessionStateBadge.vue';
import ConfirmModal from './modals/ConfirmModal.vue';
import WorktreeCreateModal from './modals/WorktreeCreateModal.vue';
@@ -115,6 +131,7 @@ const { t } = useI18n();
const ide = useIdeStore();
const worktrees = useWorktreesStore();
const sessions = useSessionsStore();
const groups = useGroupsStore();
const toasts = useToastsStore();
const modals = useModalsStore();
const ctx = useContextMenu();
@@ -125,11 +142,35 @@ const worktreeList = computed(() => worktrees.worktreesForRepo(props.repo.id));
const isWtExpanded = (wt: WorktreeSummary): boolean => ide.expandedWtPaths.includes(wt.path);
const isActiveWt = (wt: WorktreeSummary): boolean =>
ide.activeContext?.repoId === wt.repoId && ide.activeContext?.wtPath === wt.path;
const isDirty = (wt: WorktreeSummary): boolean => wt.git.dirtyCount > 0;
// sessions vivantes dont le cwd correspond au worktree (corrélation par répertoire).
// Infobulle du dépôt : chemin, branche par défaut, et l'alerte si le dossier n'existe plus.
const repoTitle = computed(() => {
const lines = [props.repo.path];
if (props.repo.defaultBranch) lines.push(`${t('git.defaultBranch')} : ${props.repo.defaultBranch}`);
if (!props.repo.valid) lines.push(t('git.repoInvalid'));
return lines.join('\n');
});
// Teinte du ou des groupes auxquels ce dépôt appartient : relie visuellement l'explorateur et le
// panneau Groupes (le champ `color` n'était exploité que dans ce dernier).
const groupTint = computed(() => {
const color = groups.colorForRepo(props.repo.id);
return color ? { color } : undefined;
});
/** Détail d'une session : commande réelle, cwd, et les dépôts reliés d'une session de groupe. */
function sessionTitle(s: SessionSummary): string {
const lines = [s.title ? `${s.title} (${s.command})` : s.command, s.cwd];
if (s.addedDirs?.length) lines.push(`--add-dir : ${s.addedDirs.join(', ')}`);
return lines.join('\n');
}
// Sessions vivantes rattachées au worktree. Même règle que le serveur (`@arboretum/shared`) : un
// terminal lancé dans un SOUS-répertoire (« Démarrer le projet ») ou une session de groupe reliant ce
// worktree en `--add-dir` compte aussi · l'égalité stricte les faisait disparaître de l'arbre.
function sessionsFor(wt: WorktreeSummary): SessionSummary[] {
return sessions.sessions.filter((s) => s.live && s.cwd === wt.path);
const siblings = worktreeList.value.map((w) => w.path);
return sessions.sessions.filter((s) => s.live && sessionBelongsToWorktree(s, wt.path, siblings));
}
// fichier actif si l'onglet éditeur courant appartient à ce worktree.
@@ -11,9 +11,16 @@
</div>
<div class="min-h-0 flex-1 overflow-auto">
<AttentionList />
<div class="px-1 pt-1 pb-2">
<p v-if="rows.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('sessions.empty') }}</p>
<!-- chargement / échec / vide distingués (cf. ProjectTree) -->
<SkeletonRow v-if="store.loading && rows.length === 0" :count="3" :height="22" class="px-2 py-1" />
<div v-else-if="store.loadError" class="px-2 py-1 text-xs">
<p class="text-danger">{{ store.loadError }}</p>
<button type="button" class="mt-1 rounded px-1 text-accent hover:bg-surface-2" @click="store.fetchSessions()">
{{ t('common.retry') }}
</button>
</div>
<p v-else-if="rows.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('sessions.empty') }}</p>
<div
v-for="s in rows"
:key="s.id"
@@ -75,7 +82,7 @@ import { useSessionActions } from '../../composables/useSessionActions';
import { sessionLabel } from '../../lib/session-label';
import SessionStateBadge from '../SessionStateBadge.vue';
import BaseBadge from '../ui/BaseBadge.vue';
import AttentionList from './AttentionList.vue';
import SkeletonRow from '../ui/SkeletonRow.vue';
import ConfirmModal from './modals/ConfirmModal.vue';
import NewSessionModal from './modals/NewSessionModal.vue';
import NewProjectModal from '../NewProjectModal.vue';
@@ -1,5 +1,5 @@
<template>
<div class="flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
<div class="no-scrollbar flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
<div class="flex shrink-0 items-center gap-1.5 px-2 label-mono">
<span class="flex items-center gap-1" aria-hidden="true">
<span class="h-2 w-2 rounded-full bg-danger" />
@@ -48,6 +48,7 @@ import type { SessionSummary } from '@arboretum/shared';
import { useIdeStore } from '../../stores/ide';
import { useSessionsStore } from '../../stores/sessions';
import { useWorktreesStore } from '../../stores/worktrees';
import { sessionLabel } from '../../lib/session-label';
import SessionStateBadge from '../SessionStateBadge.vue';
const { t } = useI18n();
@@ -57,16 +58,10 @@ const worktrees = useWorktreesStore();
const sessionOf = (sid: string): SessionSummary | null => sessions.sessions.find((s) => s.id === sid) ?? null;
// libellé compact : « repo · branche » si le worktree est connu, sinon le dernier segment du cwd.
// Libellé compact, mutualisé avec les panneaux (lib/session-label) : le calcul était dupliqué ici, avec
// une corrélation par égalité stricte qui perdait les terminaux lancés dans un sous-répertoire.
function titleFor(sid: string): string {
const s = sessionOf(sid);
if (!s) return sid.slice(0, 8);
const wt = worktrees.worktrees.find((w) => w.path === s.cwd);
if (wt) {
const repo = worktrees.repos.find((r) => r.id === wt.repoId);
const branch = wt.branch ?? wt.head.slice(0, 7);
return repo ? `${repo.label} · ${branch}` : branch;
}
return s.cwd.split('/').filter(Boolean).pop() ?? s.cwd;
return s ? sessionLabel(s, worktrees) : sid.slice(0, 8);
}
</script>
@@ -19,10 +19,10 @@
<div class="flex flex-col gap-1 text-xs text-fg-muted">
{{ t('groups.reposLabel') }}
<p v-if="worktrees.repos.length === 0" class="text-fg-subtle">{{ t('groups.noReposRegistered') }}</p>
<p v-if="worktrees.visibleRepos.length === 0" class="text-fg-subtle">{{ t('groups.noReposRegistered') }}</p>
<div v-else class="flex flex-wrap gap-2">
<label
v-for="repo in worktrees.repos"
v-for="repo in worktrees.visibleRepos"
:key="repo.id"
class="flex items-center gap-1.5 rounded-lg border border-border bg-surface-2/40 px-2 py-1"
>
@@ -13,10 +13,10 @@
<div class="flex flex-col gap-1 text-xs text-fg-muted">
{{ t('groups.reposLabel') }}
<p v-if="worktrees.repos.length === 0" class="text-fg-subtle">{{ t('groups.noReposRegistered') }}</p>
<p v-if="worktrees.visibleRepos.length === 0" class="text-fg-subtle">{{ t('groups.noReposRegistered') }}</p>
<div v-else class="flex flex-wrap gap-2">
<label
v-for="repo in worktrees.repos"
v-for="repo in worktrees.visibleRepos"
:key="repo.id"
class="flex items-center gap-1.5 rounded-lg border border-border bg-surface-2/40 px-2 py-1"
>
@@ -12,7 +12,9 @@
<!-- lignes de commandes éditables -->
<div class="flex flex-col gap-2">
<div v-for="(c, i) in rows" :key="c.id" class="flex items-center gap-2">
<!-- `flex-wrap` : sur mobile (~390px) la ligne ne tenait pas et écrasait le champ le plus
important, la commande. La commande garde donc sa propre ligne complète en étroit. -->
<div v-for="(c, i) in rows" :key="c.id" class="flex flex-wrap items-center gap-2">
<input
v-model="c.enabled"
type="checkbox"
@@ -20,8 +22,8 @@
:title="t('launch.enabledTitle')"
/>
<input v-model="c.label" class="input w-28 shrink-0 text-xs" :placeholder="t('launch.labelPlaceholder')" />
<input v-model="c.run" class="input min-w-0 flex-1 font-mono text-xs" :placeholder="t('launch.runPlaceholder')" />
<input v-model="c.cwd" class="input w-24 shrink-0 font-mono text-xs" :placeholder="t('launch.cwdPlaceholder')" />
<input v-model="c.run" class="input min-w-[12rem] flex-1 basis-full font-mono text-xs sm:basis-0" :placeholder="t('launch.runPlaceholder')" />
<button type="button" class="btn shrink-0 px-1.5" :title="t('launch.remove')" @click="removeRow(i)">
<Trash2 :size="13" />
</button>
@@ -72,10 +72,11 @@
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plug, Plus, Trash2 } from '@lucide/vue';
import type { GitAuthType, GitService } from '@arboretum/shared';
import { wsClient } from '../../lib/ws-client';
import { useGitConnectionsStore } from '../../stores/git-connections';
import { useToastsStore } from '../../stores/toasts';
import BaseButton from '../ui/BaseButton.vue';
@@ -98,6 +99,16 @@ const canCreate = computed(
onMounted(() => void store.fetchAll());
// Ces connexions n'ont pas de topic WS (aucun événement à diffuser) : elles sont donc les seules
// données de l'app à pouvoir dater d'avant une coupure. On les recharge au retour de la connexion,
// tant que la section est ouverte.
watch(
() => wsClient.status.value,
(now, before) => {
if (now === 'open' && before && before !== 'open') void store.fetchAll();
},
);
function openForm(): void {
Object.assign(form, { service: 'gitea', authType: 'pat', label: '', baseUrl: '', username: '', secret: '' });
error.value = null;
@@ -0,0 +1,96 @@
<template>
<section class="card flex flex-col gap-3">
<h2 class="flex items-center gap-2 text-sm font-semibold text-fg">
<Globe :size="16" /> {{ t('remote.title') }}
</h2>
<p class="text-xs text-fg-subtle">{{ t('remote.hint') }}</p>
<!-- Comment ce client parle au daemon : origine, transport, état de la connexion temps réel -->
<div class="card-inset flex flex-col gap-2 text-xs">
<div class="flex flex-wrap items-center gap-2">
<span class="text-fg-muted">{{ t('remote.currentOrigin') }}</span>
<code class="min-w-0 flex-1 truncate rounded bg-surface-0 px-2 py-0.5 font-mono text-fg" :title="currentOrigin">{{ currentOrigin }}</code>
<BaseButton size="sm" variant="ghost" :icon="copied ? Check : Copy" @click="copyOrigin">
{{ copied ? t('settings.copied') : t('settings.copy') }}
</BaseButton>
</div>
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
<span :class="isSecure ? 'text-accent' : 'text-warn'">
{{ isSecure ? t('remote.https') : t('remote.http') }}
</span>
<span class="text-fg-subtle">{{ t('remote.bind', { bind: server?.bind ?? '?', port: server?.port ?? '?' }) }}</span>
<span :class="loopbackOnly ? 'text-fg-subtle' : 'text-warn'">
{{ loopbackOnly ? t('remote.loopback') : t('remote.exposed') }}
</span>
</div>
</div>
<!-- Origines autorisées : la cause n°1 des 403 en accès distant -->
<div class="flex flex-col gap-1">
<span class="text-xs text-fg-muted">{{ t('remote.allowedOrigins') }}</span>
<p v-if="(server?.allowedOrigins.length ?? 0) === 0" class="text-xs text-fg-subtle">{{ t('remote.noExtraOrigins') }}</p>
<ul v-else class="flex flex-col gap-1">
<li v-for="o in server?.allowedOrigins ?? []" :key="o" class="card-inset py-1">
<code class="block truncate font-mono text-xs text-fg" :title="o">{{ o }}</code>
</li>
</ul>
<!-- Si la page fonctionne, l'origine courante est forcément acceptée ; ce bloc sert donc à
préparer un AUTRE point d'accès (nom Tailscale, IP LAN, domaine du reverse proxy). -->
<p class="flex flex-wrap items-start gap-1 text-xs text-fg-subtle">
<Info :size="13" class="mt-0.5 shrink-0" />
<span>{{ t('remote.originHint') }}</span>
</p>
<code class="rounded bg-surface-0 px-2 py-1 font-mono text-[11px] text-fg-muted">{{ allowOriginCommand }}</code>
</div>
<!-- Notifications : la supervision mobile en dépend, et elles exigent HTTPS -->
<div class="flex flex-wrap items-center gap-2 border-t border-border/80 pt-3 text-xs">
<span class="text-fg-muted">{{ t('remote.push') }}</span>
<span :class="pushReady ? 'text-accent' : 'text-fg-subtle'">{{ pushStatus }}</span>
</div>
<p class="text-xs text-fg-subtle">{{ t('remote.pwaHint') }}</p>
</section>
</template>
<script setup lang="ts">
// « Accès distant » : rend lisible d'un coup d'œil comment le daemon est joignable et ce qui manque
// pour l'atteindre depuis un autre appareil. Purement informatif (aucune mutation) : les réglages
// d'exposition sont des FLAGS de démarrage, jamais modifiables à chaud (modèle de sécurité).
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Check, Copy, Globe, Info } from '@lucide/vue';
import { useSettingsStore } from '../../stores/settings';
import { usePushStore } from '../../stores/push';
import BaseButton from '../ui/BaseButton.vue';
const { t } = useI18n();
const settings = useSettingsStore();
const push = usePushStore();
const server = computed(() => settings.server);
const currentOrigin = computed(() => window.location.origin);
const isSecure = computed(() => window.location.protocol === 'https:');
const loopbackOnly = computed(() => {
const bind = server.value?.bind ?? '127.0.0.1';
return bind === '127.0.0.1' || bind === 'localhost' || bind === '::1';
});
const allowOriginCommand = computed(() => `arboretum --allow-origin ${currentOrigin.value}`);
const pushReady = computed(() => push.supported && push.enabled);
const pushStatus = computed(() => {
if (!push.supported) return t('remote.pushUnsupported');
return push.enabled ? t('remote.pushOn') : t('remote.pushOff');
});
const copied = ref(false);
async function copyOrigin(): Promise<void> {
try {
await navigator.clipboard.writeText(currentOrigin.value);
copied.value = true;
setTimeout(() => (copied.value = false), 1500);
} catch {
/* presse-papiers indisponible (http non sécurisé) : silencieux, l'URL reste sélectionnable */
}
}
</script>
@@ -1,31 +0,0 @@
<template>
<!-- Lucide n'a pas d'icône Gitea : motif « tasse de thé fumante » (git + tea), trait cohérent
avec les icônes Lucide (currentColor, coins arrondis). stroke-width hérité via fallthrough. -->
<svg
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<!-- vapeur = mini-branche git -->
<path d="M9 5.5V4" />
<path d="M13 5.5V3" />
<circle cx="9" cy="3" r="0.6" fill="currentColor" stroke="none" />
<circle cx="13" cy="2.5" r="0.6" fill="currentColor" stroke="none" />
<!-- tasse -->
<path d="M4 8h12v4a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5z" />
<!-- anse -->
<path d="M16 9h1.5a2.5 2.5 0 0 1 0 5H16" />
<!-- soucoupe -->
<path d="M5 20h10" />
</svg>
</template>
<script setup lang="ts">
withDefaults(defineProps<{ size?: number }>(), { size: 18 });
</script>
@@ -0,0 +1,143 @@
<template>
<div class="flex min-h-0 flex-col border-t border-border">
<!-- deux boutons frères (jamais imbriqués : un bouton dans un bouton est du HTML invalide) -->
<div class="flex shrink-0 items-center gap-1 px-2 py-1 label-mono">
<button type="button" class="flex min-w-0 flex-1 items-center gap-1 text-left hover:text-fg" :aria-expanded="open" @click="open = !open">
<component :is="open ? ChevronDown : ChevronRight" :size="13" class="shrink-0" />
<History :size="13" class="shrink-0" />
<span class="truncate">{{ t('history.title') }}</span>
<span v-if="unpushedTotal > 0" class="shrink-0 rounded bg-warn/15 px-1 text-[10px] text-warn" :title="t('history.unpushedHint')">
{{ t('history.unpushed', { n: unpushedTotal }) }}
</span>
</button>
<button
v-if="open"
type="button"
class="shrink-0 rounded p-0.5 hover:bg-surface-2 hover:text-fg"
:title="t('common.refresh')"
@click="load"
>
<RefreshCw :size="12" />
</button>
</div>
<div v-if="open" class="min-h-0 flex-1 overflow-auto">
<p v-if="loading && commits.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('fs.loading') }}</p>
<p v-else-if="error" class="px-2 py-1 text-xs text-danger">{{ error }}</p>
<p v-else-if="commits.length === 0" class="px-2 py-1 text-xs text-fg-subtle">{{ t('history.empty') }}</p>
<template v-for="(c, i) in commits" :key="c.hash">
<button
type="button"
class="flex w-full items-baseline gap-2 px-2 py-1 text-left text-xs hover:bg-surface-2/60"
:class="selected === c.hash ? 'bg-surface-2' : ''"
:title="`${c.subject}\n${c.author} · ${absoluteDate(c.date)}\n${c.hash}`"
@click="toggle(c.hash)"
>
<span class="shrink-0 font-mono text-[11px]" :class="isUnpushed(i) ? 'text-warn' : 'text-fg-subtle'">
{{ c.shortHash }}
</span>
<span class="min-w-0 flex-1 truncate">{{ c.subject }}</span>
<span class="shrink-0 text-[10px] text-fg-subtle">{{ relativeDate(c.date) }}</span>
</button>
<DiffViewer
v-if="selected === c.hash"
:repo-id="repoId"
:wt="wt"
:commit="c.hash"
class="max-h-80 border-y border-border bg-surface-1/40"
/>
</template>
<button
v-if="canLoadMore"
type="button"
class="w-full px-2 py-1 text-left text-[11px] text-fg-subtle hover:text-fg"
:disabled="loading"
@click="loadMore"
>
{{ t('history.loadMore') }}
</button>
</div>
</div>
</template>
<script setup lang="ts">
// Historique de la branche du worktree : ce qui a déjà été acté, et ce qui n'est pas encore poussé.
// Complète le panneau de changements (« ce qui n'est pas commité ») pour donner l'état complet du
// travail en cours sans ouvrir un terminal. Le diff d'un commit se déplie sur place, dans la même vue
// que les diffs de fichiers (DiffViewer accepte les deux formes).
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight, History, RefreshCw } from '@lucide/vue';
import type { CommitEntry } from '@arboretum/shared';
import { gitApi } from '../../lib/git-api';
import { formatDateTime, formatRelative } from '../../lib/format';
import { persistedRef } from '../../lib/persisted-ref';
import DiffViewer from './DiffViewer.vue';
const props = defineProps<{ repoId: string; wt: string; version: number }>();
const { t, locale } = useI18n();
const PAGE = 30;
const open = persistedRef<boolean>('arb.history.open', false);
const commits = ref<CommitEntry[]>([]);
const unpushedCount = ref(0);
const hasUpstream = ref(false);
const loading = ref(false);
const error = ref<string | null>(null);
const selected = ref<string | null>(null);
const reachedEnd = ref(false);
/** Sans upstream, AUCUN commit n'est publié : on marque toute la liste plutôt qu'un préfixe. */
const isUnpushed = (index: number): boolean => (hasUpstream.value ? index < unpushedCount.value : true);
const unpushedTotal = computed(() => (hasUpstream.value ? unpushedCount.value : commits.value.length));
const canLoadMore = computed(() => !reachedEnd.value && commits.value.length > 0);
const absoluteDate = (iso: string): string => formatDateTime(iso, locale.value);
const relativeDate = (iso: string): string => formatRelative(iso, locale.value);
async function load(): Promise<void> {
loading.value = true;
error.value = null;
try {
const res = await gitApi.log(props.repoId, props.wt, { limit: PAGE });
commits.value = res.commits;
unpushedCount.value = res.unpushedCount;
hasUpstream.value = res.hasUpstream;
reachedEnd.value = res.commits.length < PAGE;
if (selected.value && !res.commits.some((c) => c.hash === selected.value)) selected.value = null;
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
}
}
async function loadMore(): Promise<void> {
loading.value = true;
try {
const res = await gitApi.log(props.repoId, props.wt, { limit: PAGE, skip: commits.value.length });
commits.value = [...commits.value, ...res.commits];
reachedEnd.value = res.commits.length < PAGE;
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
loading.value = false;
}
}
function toggle(hash: string): void {
selected.value = selected.value === hash ? null : hash;
}
// Rechargement au changement de worktree et à chaque modification disque (un commit fait bouger
// .git/HEAD, donc le jeton change) ; rien n'est chargé tant que la section est repliée.
watch(
() => [props.repoId, props.wt, props.version, open.value] as const,
() => {
if (open.value) void load();
},
{ immediate: true },
);
</script>
@@ -1,5 +1,7 @@
<template>
<div class="flex h-full flex-col border-t border-border">
<!-- pas de bordure haute : ce panneau est le premier enfant du panneau Git (le trait était un
vestige de l'ancien layout, où il vivait sous le contenu). -->
<div class="flex h-full flex-col">
<!-- en-tête + actions distantes -->
<div class="flex items-center gap-1 px-2 py-1 label-mono">
<GitCompare :size="13" /> {{ t('workspace.changes') }}
@@ -15,13 +15,13 @@
<tbody>
<template v-for="(h, hi) in parsed.hunks" :key="hi">
<tr class="bg-surface-1/60 text-info/80">
<td class="select-none px-2 text-right text-fg-subtle" />
<td class="select-none px-2 text-right text-fg-subtle" />
<td class="diff-gutter left-0" />
<td class="diff-gutter left-10" />
<td class="whitespace-pre px-2">{{ h.header }}</td>
</tr>
<tr v-for="(l, li) in h.lines" :key="`${hi}-${li}`" :class="rowClass(l.type)">
<td class="w-10 select-none px-2 text-right text-fg-subtle">{{ l.oldLine ?? '' }}</td>
<td class="w-10 select-none px-2 text-right text-fg-subtle">{{ l.newLine ?? '' }}</td>
<td class="diff-gutter left-0">{{ l.oldLine ?? '' }}</td>
<td class="diff-gutter left-10">{{ l.newLine ?? '' }}</td>
<td class="whitespace-pre px-2">{{ marker(l.type) }}{{ l.content }}</td>
</tr>
</template>
@@ -37,7 +37,12 @@ import { useI18n } from 'vue-i18n';
import { gitApi } from '../../lib/git-api';
import { parseUnifiedDiff, type DiffLineType, type ParsedDiff } from '../../lib/diff-parse';
const props = defineProps<{ repoId: string; wt: string; file: string; staged: boolean; version: number }>();
// Deux formes, un seul rendu : diff d'un FICHIER (`file`, éventuellement indexé) ou diff complet d'un
// COMMIT (`commit`). Les deux sont des diffs unifiés, donc le même parseur et la même table.
const props = withDefaults(
defineProps<{ repoId: string; wt: string; file?: string; commit?: string; staged?: boolean; version?: number }>(),
{ file: '', commit: '', staged: false, version: 0 },
);
const { t } = useI18n();
const loading = ref(false);
@@ -47,12 +52,15 @@ const tooLarge = ref(false);
const parsed = ref<ParsedDiff>({ hunks: [], additions: 0, deletions: 0 });
async function load(): Promise<void> {
if (!props.file && !props.commit) return;
loading.value = true;
error.value = null;
binary.value = false;
tooLarge.value = false;
try {
const res = await gitApi.diff(props.repoId, props.wt, props.file, props.staged);
const res = props.commit
? await gitApi.commitDiff(props.repoId, props.wt, props.commit)
: await gitApi.diff(props.repoId, props.wt, props.file, props.staged);
binary.value = res.binary;
tooLarge.value = res.tooLarge;
parsed.value = res.binary || res.tooLarge ? { hunks: [], additions: 0, deletions: 0 } : parseUnifiedDiff(res.diff);
@@ -63,7 +71,13 @@ async function load(): Promise<void> {
}
}
watch(() => [props.repoId, props.wt, props.file, props.staged, props.version], load, { immediate: true });
// Un commit est immuable : sa version n'entre pas dans les dépendances (inutile de recharger un diff
// figé à chaque écriture disque).
watch(
() => [props.repoId, props.wt, props.file, props.commit, props.staged, props.commit ? 0 : props.version],
load,
{ immediate: true },
);
function rowClass(type: DiffLineType): string {
if (type === 'add') return 'diff-add';
@@ -17,6 +17,7 @@
:wt="wt"
:depth="depth"
:active="active"
:version="version"
@open="(p) => emit('open', p)"
/>
</div>
@@ -31,9 +32,13 @@ import type { FsEntry, FsListResponse } from '@arboretum/shared';
import { api } from '../../lib/api';
import FileTreeNode from './FileTreeNode.vue';
const props = withDefaults(defineProps<{ wt: string; active: string | null; embedded?: boolean; depth?: number }>(), {
// `version` = jeton d'invalidation du worktree (stores/worktrees.changeVersion) : il change à chaque
// `worktree_changes` reçu, ce qui recharge l'arbre sans polling. Sans lui, un fichier créé ou supprimé
// par une session n'apparaissait jamais tant qu'on ne repliait pas le nœud.
const props = withDefaults(defineProps<{ wt: string; active: string | null; embedded?: boolean; depth?: number; version?: number }>(), {
embedded: false,
depth: 0,
version: 0,
});
const emit = defineEmits<{ open: [relPath: string] }>();
const { t } = useI18n();
@@ -56,5 +61,5 @@ async function load(): Promise<void> {
}
onMounted(load);
watch(() => props.wt, load);
watch([() => props.wt, () => props.version], load);
</script>
@@ -26,6 +26,7 @@
:wt="wt"
:depth="depth + 1"
:active="active"
:version="version"
@open="(p) => emit('open', p)"
/>
</template>
@@ -33,12 +34,12 @@
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, ref, watch } from 'vue';
import { ChevronDown, ChevronRight, File } from '@lucide/vue';
import type { FsEntry, FsListResponse } from '@arboretum/shared';
import { api } from '../../lib/api';
const props = defineProps<{ entry: FsEntry; wt: string; depth: number; active: string | null }>();
const props = defineProps<{ entry: FsEntry; wt: string; depth: number; active: string | null; version: number }>();
const emit = defineEmits<{ open: [relPath: string] }>();
const expanded = ref(false);
@@ -66,6 +67,17 @@ async function loadChildren(): Promise<void> {
}
}
// Le contenu du worktree a changé sur le disque : on invalide le cache d'enfants. Rechargement
// immédiat si le dossier est déplié (donc visible), sinon paresseux au prochain dépliage · seuls les
// nœuds réellement affichés paient une requête.
watch(
() => props.version,
() => {
loaded = false;
if (expanded.value && !props.entry.isFile) void loadChildren();
},
);
function onClick(): void {
if (props.entry.isFile) {
emit('open', relPath.value);
@@ -1,14 +1,17 @@
<template>
<span class="flex items-center gap-2 text-xs">
<span class="flex items-center gap-1 font-mono text-fg-muted">
<!-- `dense` : variante sans branche ni « propre », pour tenir sur la ligne d'un worktree dans
l'arbre de projets. Les compteurs existaient déjà dans le protocole mais n'étaient visibles
QUE dans la barre de statut, pour le seul worktree actif. -->
<span class="flex items-center text-xs" :class="dense ? 'gap-1' : 'gap-2'" :title="dense ? summary : undefined">
<span v-if="!dense" class="flex items-center gap-1 font-mono text-fg-muted">
<GitBranch :size="13" />{{ branch ?? t('worktrees.detached') }}
</span>
<span v-if="git.ahead" class="text-accent" :title="t('git.ahead')">↑{{ git.ahead }}</span>
<span v-if="git.behind" class="text-warn" :title="t('git.behind')">↓{{ git.behind }}</span>
<span v-if="git.stagedCount" class="text-accent" :title="t('git.staged')">●{{ git.stagedCount }}</span>
<span v-if="git.unstagedCount" class="text-warn" :title="t('git.unstaged')">○{{ git.unstagedCount }}</span>
<span v-if="git.conflictCount" class="text-danger" :title="t('git.conflicts')">⚠{{ git.conflictCount }}</span>
<span v-if="isClean" class="text-fg-subtle">{{ t('worktrees.clean') }}</span>
<span v-if="git.ahead" class="text-accent" :title="dense ? undefined : t('git.ahead')">↑{{ git.ahead }}</span>
<span v-if="git.behind" class="text-warn" :title="dense ? undefined : t('git.behind')">↓{{ git.behind }}</span>
<span v-if="git.stagedCount" class="text-accent" :title="dense ? undefined : t('git.staged')">●{{ git.stagedCount }}</span>
<span v-if="git.unstagedCount" class="text-warn" :title="dense ? undefined : t('git.unstaged')">○{{ git.unstagedCount }}</span>
<span v-if="git.conflictCount" class="text-danger" :title="dense ? undefined : t('git.conflicts')">⚠{{ git.conflictCount }}</span>
<span v-if="!dense && isClean" class="text-fg-subtle">{{ t('worktrees.clean') }}</span>
</span>
</template>
@@ -18,10 +21,32 @@ import { useI18n } from 'vue-i18n';
import { GitBranch } from '@lucide/vue';
import type { WorktreeGitStatus } from '@arboretum/shared';
const props = defineProps<{ git: WorktreeGitStatus; branch: string | null }>();
const props = withDefaults(defineProps<{ git: WorktreeGitStatus; branch: string | null; dense?: boolean }>(), {
dense: false,
});
const { t } = useI18n();
const isClean = computed(
() => !props.git.dirtyCount && !props.git.ahead && !props.git.behind && !props.git.stagedCount && !props.git.unstagedCount,
);
/**
* En mode dense, les symboles seuls sont trop laconiques : on regroupe tout dans une infobulle unique
* (compteurs nommés, upstream, dernier commit). C'est là que `upstream`, `lastCommitHash` et
* `lastCommitSubject` deviennent enfin visibles quelque part.
*/
const summary = computed(() => {
const g = props.git;
const lines: string[] = [props.branch ?? t('worktrees.detached')];
const counts: string[] = [];
if (g.ahead) counts.push(`↑${g.ahead} ${t('git.ahead')}`);
if (g.behind) counts.push(`↓${g.behind} ${t('git.behind')}`);
if (g.stagedCount) counts.push(`${g.stagedCount} ${t('git.staged')}`);
if (g.unstagedCount) counts.push(`${g.unstagedCount} ${t('git.unstaged')}`);
if (g.conflictCount) counts.push(`${g.conflictCount} ${t('git.conflicts')}`);
lines.push(counts.length > 0 ? counts.join(' · ') : t('worktrees.clean'));
lines.push(g.upstream ? `${t('git.upstream')} ${g.upstream}` : t('git.noUpstream'));
if (g.lastCommitHash) lines.push(`${t('git.lastCommit')} ${g.lastCommitHash} ${g.lastCommitSubject ?? ''}`.trim());
return lines.join('\n');
});
</script>
@@ -1,22 +0,0 @@
import { ref, watch, onUnmounted, getCurrentInstance, type Ref } from 'vue';
/**
* Renvoie un miroir débouncé d'un ref source. Le ref source reste instantané (idéal pour un
* v-model d'input) ; le miroir ne se met à jour qu'après `delay` ms de stabilité : c'est lui
* que le pipeline de tri/filtre consomme, pour ne pas recalculer à chaque frappe.
*/
export function useDebouncedRef<T>(source: Ref<T>, delay = 150): Ref<T> {
const debounced = ref(source.value) as Ref<T>;
let timer: ReturnType<typeof setTimeout> | undefined;
watch(source, (v) => {
clearTimeout(timer);
timer = setTimeout(() => {
debounced.value = v;
}, delay);
});
if (getCurrentInstance()) onUnmounted(() => clearTimeout(timer));
return debounced;
}
@@ -4,6 +4,7 @@ import { useSessionsStore } from '../stores/sessions';
import { useWorktreesStore } from '../stores/worktrees';
import { useGroupsStore } from '../stores/groups';
import { useSettingsStore } from '../stores/settings';
import { wsClient } from '../lib/ws-client';
/**
* Propriétaire unique du chargement initial et des abonnements temps réel (sessions, worktrees,
@@ -20,13 +21,18 @@ export function useRealtimeBootstrap(): void {
let started = false;
function start(): void {
if (started) return;
started = true;
/** Recharge l'état complet depuis REST (boot, et après chaque reconnexion WS). */
function refetchAll(): void {
void worktrees.fetchAll();
void sessions.fetchSessions();
void groups.fetchGroups();
void settings.fetch(); // alimente l'icône de nav Gitea et la vue Réglages
}
function start(): void {
if (started) return;
started = true;
refetchAll();
worktrees.startRealtime();
sessions.startRealtime();
groups.startRealtime();
@@ -50,4 +56,19 @@ export function useRealtimeBootstrap(): void {
},
{ immediate: true },
);
// Une coupure WS fait perdre DÉFINITIVEMENT les événements émis pendant l'interruption (le
// protocole ne rejoue rien) : sans ce rechargement, l'UI restait sur des listes périmées jusqu'au
// prochain rafraîchissement manuel. La réinscription aux topics et le ré-armement des `watch` sont
// déjà faits par le client WS lui-même ; ici on resynchronise seulement les données.
let hadOpenConnection = false;
watch(
() => wsClient.status.value,
(now) => {
if (now !== 'open') return;
// La toute première ouverture suit immédiatement le fetch de `start()` : ne pas le refaire.
if (hadOpenConnection && started) refetchAll();
hadOpenConnection = true;
},
);
}

Some files were not shown because too many files have changed in this diff Show More