Compare commits

..
69 Commits
Author SHA1 Message Date
johanleroy 0c191b1296 release: git-arboretum 3.7.1 (transcripts préservés), desktop 0.2.5 (mise à jour automatique)
CI / No em/en dashes (push) Successful in 3s
CI / Build & test (Node 24) (push) Successful in 11m5s
Release / Publish to Gitea npm registry (push) Successful in 11m10s
CI / Build & test (Node 22) (push) Successful in 11m24s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m57s
Desktop Release / Publish floating desktop-latest release (push) Successful in 10s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m54s
2026-08-05 11:35:59 +02:00
johanleroy 17e95754b1 fix(server, desktop): plus de transcript perdu, et la mise à jour s'applique toute seule
Deux défauts vécus sur le poste, tous deux « invisibles » jusqu'à ce qu'on regarde.

1. Une console Claude ouverte depuis l'app affichait « Transcript saving is off,
   inherited CLAUDE_CODE_CHILD_SESSION marker ». Le daemon avait été lancé depuis
   une session Claude Code, il héritait donc de ses marqueurs d'exécution et les
   repassait à CHAQUE session qu'il lance. Le CLI se croyait sous-session et
   coupait la sauvegarde de son transcript : plus d'historique, plus de --resume,
   claudeSessionId restant null (et avec lui l'état fin busy/waiting/idle, ce qui
   explique les sessions sans activité détectée). L'environnement des PTY est
   desormais assaini de ces marqueurs, pour `claude` comme pour les shells (un
   `claude` tapé à la main en héritait aussi). La configuration légitime de
   l'utilisateur (CLAUDE_CONFIG_DIR, ANTHROPIC_*, proxies) passe intacte.
   Vérifié par acceptance-p17 : le daemon de test est lancé avec un environnement
   volontairement pollué, et le PTY n'en voit plus rien.

2. Une mise à jour installée à chaud demandait encore une manipulation. La 0.2.4
   détectait le remplacement du binaire et proposait un dialogue « Restart now » :
   le travail restait à la charge de l'utilisateur. L'app redémarre maintenant
   d'elle-même quand cela ne coûte rien, c'est-à-dire le cas courant, et ne
   demande que s'il y a quelque chose à perdre : des sessions vivantes à
   interrompre (le dialogue dit combien) ou un daemon injoignable. Un « Later »
   reste définitif pour cette version : rien ne redémarre dans le dos de
   personne. La détection ne dépend plus d'un retour par le tray ou le Dock : un
   `stat` toutes les 30 s la couvre même fenêtre ouverte, par poll et non par
   `fs.watch`, qui ne voit souvent rien quand un paquet remplace un binaire ou
   tout un répertoire.
2026-08-05 11:35:51 +02:00
johanleroy dc8c7c9534 release: git-arboretum 3.7.0 (fin de l'écran noir, colonnes de terminaux, git scopé), desktop 0.2.4
CI / No em/en dashes (push) Successful in 4s
CI / Build & test (Node 24) (push) Successful in 10m50s
CI / Build & test (Node 22) (push) Successful in 11m5s
Release / Publish to Gitea npm registry (push) Successful in 10m57s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m27s
Desktop Release / Publish floating desktop-latest release (push) Successful in 10s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m55s
Le desktop 0.2.4 embarque le daemon 3.7.0 et livre aussi les garde-fous de
démarrage déjà sur main (dialogue d'échec, reprise d'un daemon orphelin,
redémarrage après mise à jour installée à chaud).
2026-08-05 10:57:05 +02:00
johanleroy bdec8d6ad0 ci(desktop): retire le job Windows du packaging, aucun runner n'est enregistré
Le job était conditionné par la variable de dépôt ENABLE_WINDOWS_BUILD, ce qui ne
suffit pas : sans runner labellisé `windows-latest`, la release desktop tombait en
erreur au lieu de sauter le job. Il est retiré, ainsi que le téléchargement de son
artefact et ses assets dans le canal flottant desktop-latest.

Le job complet reste dans l'historique (tag desktop-v0.2.3) et docs/CI_RUNNERS.md
décrit ce qu'il faut restaurer une fois un runner Windows enregistré. Le repli
reste un `npm run dist:win` manuel attaché à la release.
2026-08-05 10:56:54 +02:00
johanleroy 8aea0ae32d fix(server, web, vscode): les terminaux ne restent plus noirs, panes côte à côte, git scopé au terminal
Un terminal pouvait rester tout noir alors que sa session tournait. Le PTY était
vivant et avait bien écrit sa sortie : la panne était dans le transport. Le replay
d'attache est une frame BINAIRE, mais un client n'apprend son numéro de canal
qu'avec le message `attached` ; le serveur envoyait le replay AVANT, donc tout
client le jetait sur un canal inconnu. Rien n'était peint, et un TUI au repos
(Claude à son prompt) ne réémet jamais rien de lui-même. `attach()` renvoie
désormais le replay et la gateway l'émet APRÈS `attached` : un seul correctif
serveur répare le web, l'app de bureau et l'extension VS Code, qui portaient le
même défaut client. Le resize de l'attache masquait le bug en provoquant un
SIGWINCH, d'où son apparence intermittente.

Seconde moitié du symptôme (« je tape et rien ne se passe ») : le dock montait
avant la liste des sessions, en déduisait « non attachable » et s'attachait en
observateur, à vie et en silence. Un pane n'attache plus avant de connaître sa
session (`sessions.loaded`).

Attaches sans écran : le message `attach` accepte un `screen` optionnel (défaut
true). Un client qui n'affiche rien et veut seulement répondre à un dialogue ne
prend plus le contrôle de la session, ne lui impose plus ses dimensions (ce qui
figeait la géométrie du vrai terminal) et ne reçoit plus le flux pour le jeter.

Rendre les pannes visibles : la raison d'un exit est écrite dans le terminal
(`[arboretum] bash exited with code 3`) avant le détachement ; un repaint est
forcé si rien n'arrive 1,2 s après l'attache, puis annoncé avec « Refresh
screen » ; les refus de canal remontent à l'écran au lieu d'un console.warn ; le
chemin du CLI claude est revalidé (périmé après une bascule nvm/asdf, le PTY
mourait sans un octet).

Colonnes de terminaux : le dock devient une rangée de colonnes redimensionnables
(3 max), chacune avec ses onglets. Algèbre pure dans lib/dock-model.ts, cinq
invariants documentés, ratios plutôt que pixels. `dockSessionIds` et
`activeDockSessionId` deviennent des computed dérivés : aucun consommateur ni
test existant ne change. Alt+clic ouvre à côté depuis les quatre panneaux. Le
plafond de hauteur du dock suit le viewport au lieu d'un 640 px figé. Correctif
préexistant au passage : PanelSplitter passait ses bornes par valeur, figées au
premier rendu, alors que le clavier les relisait.

Portée git : la vue Changements suit le worktree du terminal focalisé, ou tous
les dépôts de son groupe pour une session de groupe, avec « tout voir » à un
clic. L'index Git de la sidebar reste global (c'est la sortie d'une portée
étroite) et le badge d'activité aussi (il sert à signaler le travail qu'on ne
regarde pas). Seul le TERMINAL impose le contexte : le repli sur l'onglet
éditeur, essayé d'abord, rétrécissait la vue multi-projet dès qu'on ouvrait un
fichier.

Vérifications : acceptance-p17.mjs prouve l'ordre des trames sur un vrai
WebSocket (avec l'ancien ordre : 0 octet rejoué, échec), verify-terminals.mjs
prouve par interaction réelle que le terminal peint, que deux colonnes
coexistent, que la frappe atteint le bon PTY (fichier témoin par cwd) et que la
vue suit le terminal.
2026-08-05 10:56:42 +02:00
johanleroy 9390b62249 fix(desktop): l'app démarre après une mise à jour, et parle quand elle ne peut pas
Installer une nouvelle version remplace les fichiers sur disque mais ne touche
pas le process en cours : l'ancienne instance gardait le port 7317, la version
fraîchement installée mourait sur EADDRINUSE avant son handshake, et le shell se
contentait d'un console.error suivi d'un app.quit(). Depuis le lanceur, cliquer
l'icône ne produisait donc rien du tout.

- Tout échec de démarrage ouvre un dialogue Retry / Show log / Quit
  (start-failure.ts, texte pur et testé) et la sortie du daemon est conservée
  dans <userData>/logs/daemon.log. Une mort du daemon APRÈS le handshake propose
  de le relancer, au lieu de laisser une fenêtre morte à l'écran.
- Le port est diagnostiqué avant le spawn (port-guard.ts, empreinte
  {pid, ownerPid, port}) : un daemon orphelin, dont l'Electron est mort, est
  repris (SIGTERM puis SIGKILL, en attendant un bind réellement possible) ;
  une instance vivante ou un tiers (service, npx) est annoncé avec l'action qui
  débloque, et jamais tué. La reprise exige deux preuves, l'empreinte orpheline
  ET l'identité du process (ps -ww), car un pidfile périmé peut désigner un pid
  recyclé entre-temps par un programme quelconque.
- Une mise à jour installée à chaud est signalée avec « Restart now »
  (upgrade-watch.ts), qui arrête le daemon avant app.relaunch() ; sans quoi le
  lock d'instance unique renvoyait silencieusement sur la fenêtre de l'ancienne
  version, et on croyait avoir migré.
- ARBORETUM_DESKTOP_PORT pour cohabiter avec un Arboretum qui occupe 7317 en
  permanence (service installé, ou daemon lancé en terminal).

24 tests dans packages/desktop/test, et quatre scénarios rejoués en dev sous
xvfb-run avec profil isolé : port tenu par un tiers, orphelin repris puis SPA
servie, instance vivante laissée intacte, pid recyclé épargné.
2026-08-05 09:10:43 +02:00
johanleroy c6deded0c6 release: git-arboretum 3.6.0 (ouverture des fichiers réparée, vue Changements par projet), desktop 0.2.3
CI / No em/en dashes (push) Successful in 3s
CI / Build & test (Node 24) (push) Successful in 11m1s
Release / Publish to Gitea npm registry (push) Successful in 11m6s
CI / Build & test (Node 22) (push) Successful in 11m17s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 14m18s
Desktop Release / Publish floating desktop-latest release (push) Successful in 12s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m57s
Desktop Release / Build Windows (NSIS + portable) (push) Canceled after 0s
Le daemon 3.6.0 corrige la zone d'édition qui pouvait rester vide et ajoute la
bascule Fichiers / Changements au centre de l'IDE. Le shell Electron est inchangé,
seule la version du daemon embarqué change.
2026-08-04 23:19:16 +02:00
johanleroy ce224fd470 fix(web): les fichiers s'ouvrent enfin, et le travail git par projet au centre
Deux défauts d'usage de la zone centrale de l'IDE.

1. Ouvrir un fichier affichait une page vide. Le conteneur de l'unique instance
   Monaco vivait sous le `v-if="activeTab"` : monté sans onglet actif (premier
   usage, ou après avoir tout fermé), `onMounted` sortait en silence sur
   `!host.value`, `ready` restait faux pour toujours, et les deux watchers
   d'affichage étaient gardés par lui. Le conteneur est désormais toujours monté
   (v-show, jamais v-if : sous un v-if, fermer le dernier onglet détruisait le
   DOM et l'éditeur gardait une référence sur un noeud détaché) et l'éditeur est
   créé paresseusement depuis `showTab`, devenu l'unique entonnoir d'affichage.
   `useMonaco` ne mémoïse plus un échec, l'attente et l'erreur sont visibles, et
   la relecture disque ne se tait plus. Sur mobile, ouvrir un fichier amène enfin
   la zone centrale au premier plan et la valeur morte `mobilePanel = 'sidebar'`
   disparaît (migrée).

   Trouvé par l'E2E : seul l'`editor.worker` était fourni, donc ouvrir un `.ts`
   lançait le service TypeScript contre un worker qui n'en connaissait pas les
   méthodes, et jetait un rejet non géré à chaque ouverture. Les workers de
   langage sont fournis (chunks à la demande), diagnostics sémantiques coupés
   (sans tsconfig ni node_modules, ils inventeraient des erreurs).

2. Le statut git était à l'étroit et mono-projet. La zone centrale porte un mode
   « Fichiers / Changements » (bascule à icônes dans la barre d'onglets, donc
   accessible même sans onglet ouvert). La vue Changements montre un bloc par
   worktree pour TOUS les projets ouverts : fichiers indexés et non indexés, diff
   déplié sur place, commit, push, fetch, pull et historique par bloc. Le panneau
   Git de la barre latérale devient l'index (compteurs déjà diffusés par WS, donc
   zéro requête) et le badge de la barre d'activité, codé à 0, compte enfin les
   worktrees à traiter.

   Au passage : `canPush` était faux dans les deux sens (actif sans rien à
   pousser, bloqué en étant seulement en retard), l'amend d'un message seul est
   accepté comme le serveur le permettait déjà, le rebase est proposé dès qu'on
   est en retard, une confirmation d'abandon ne survit plus au rechargement de la
   liste, et `commit`/`fetch`/`push` émettent enfin `worktree_changes` (le
   compteur « n non poussés » restait périmé juste après un push).

Vérifié : 528 tests, acceptations P7/P9/P14/P15, `verify-ui` (4 captures
nouvelles) et un `verify-editor` qui prouve par clics réels l'ouverture d'un
fichier sans onglet persisté, la fermeture/réouverture, la bascule mobile et le
chunk éditeur absent. Ce dernier échoue bien si l'on remet le conteneur sous un
v-if.
2026-08-04 23:18:40 +02:00
johanleroy 114fbc8ba0 fix(desktop, web): pont presse-papier Electron, sans quoi copier ne faisait rien dans l'app
CI / No em/en dashes (push) Successful in 3s
CI / Build & test (Node 24) (push) Successful in 10m48s
Release / Publish to Gitea npm registry (push) Successful in 10m52s
CI / Build & test (Node 22) (push) Successful in 11m6s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m38s
Desktop Release / Publish floating desktop-latest release (push) Successful in 11s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m56s
Desktop Release / Build Windows (NSIS + portable) (push) Canceled after 0s
git-arboretum 3.5.1, desktop 0.2.2.

Le copier/coller livre en 3.5.0 ne fonctionnait que dans un navigateur : verifie dans l'app packagee,
`navigator.clipboard` y rejette en NotAllowedError A LA LECTURE COMME A L'ECRITURE. La copie echouait
donc silencieusement dans le contexte meme ou le probleme avait ete signale.

- feat(desktop): `arboretumDesktop.clipboard` expose par le preload, relaye en IPC vers le module
  `clipboard` d'Electron (lecture + ecriture, ecriture bornee a 1 M de caracteres). Le module
  `clipboard` n'etant pas accessible a un preload sandboxe, le passage par le main est obligatoire.
  Constantes de canaux isolees dans src/shared/ipc.ts pour que le bundle du preload ne tire pas
  `ipcMain` avec lui.
- fix(web): acces au presse-papier en cascade, du plus fiable au plus degrade : pont de l'app de
  bureau, puis `navigator.clipboard`, puis `document.execCommand('copy')` pour l'ecriture. Ce dernier
  recours couvre aussi l'acces LAN en clair (http://<ip>:7317), ou l'API Clipboard est indisponible.
- test: quatre cas de plus sur l'ordre de la cascade et le retour a null quand tout est refuse
  (501 tests). Pont IPC verifie dans un vrai Electron : writeText/readText repondent OK, alors que
  `navigator.clipboard` y refuse. Le chemin complet frappe -> copie -> collage -> SIGINT reste
  couvert par verify-clipboard.mjs (Chromium CDP, ALL GREEN).
2026-08-04 21:11:46 +02:00
johanleroy bde5358ea8 release: git-arboretum 3.5.0 (cache SPA, copier/coller terminal, fichiers des groupes), desktop 0.2.1
CI / No em/en dashes (push) Successful in 3s
CI / Build & test (Node 24) (push) Successful in 10m50s
CI / Build & test (Node 22) (push) Successful in 11m2s
Release / Publish to Gitea npm registry (push) Successful in 10m56s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m21s
Desktop Release / Publish floating desktop-latest release (push) Successful in 11s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m53s
Desktop Release / Build Windows (NSIS + portable) (push) Canceled after 0s
Cause racine de l'ecran noir apres mise a jour : l'etag faible de @fastify/static derive de
taille+mtime, et npm pack fige le mtime de tout le tarball a une date constante (1985-10-26). Deux
index.html de versions differentes mais de meme taille partageaient donc le meme etag : le client
recevait un 304, gardait son index perime, et demandait des /assets/<hash> disparus ; le fallback SPA
repondait index.html en text/html pour ces modules, le navigateur refusait le script, rien ne peignait.

- fix(server): index.html et tous les fichiers non haches servis en no-store, validation
  conditionnelle desactivee (etag/lastModified) pour qu'un client bloque sur un index perime se
  repare seul ; /assets/ (noms haches) passent en immutable un an
- feat(web): copier/coller dans le terminal xterm, dont la selection n'est pas une selection DOM :
  Ctrl+Maj+C / Ctrl+Maj+V, Cmd+C / Cmd+V sur macOS, Ctrl+Inser / Maj+Inser, plus interception de
  l'evenement DOM copy pour que le Copier natif fonctionne. Ctrl+C reste SIGINT
- fix(web): script anti-FOUC sorti dans /theme-boot.js, la CSP script-src 'self' du daemon refusait
  de l'executer inline (le theme n'etait donc pose qu'au montage de la SPA)
- feat(web): les worktrees d'un groupe se deplient sur leur arborescence de fichiers dans le panneau
  Groupes (meme composant et meme etat d'expansion que l'Explorateur), et un worktree ainsi deplie
  est desormais surveille en temps reel
- fix: octet nul litteral remplace par \0 dans trois sources (stores/ide.ts, GitPanel.vue,
  vscode/repos-tree.ts) : git et grep les traitaient comme binaires, leurs diffs etaient
  illisibles en revue et la garde CI lint-dashes (git grep -I) les sautait en silence
- test: cacheControlFor et clipboardIntent en tests purs, verify-clipboard.mjs (E2E Chromium CDP :
  copie, collage et SIGINT prouves par le presse-papier reel et par le systeme de fichiers),
  capture groups-dark-desktop ajoutee a verify-ui.mjs
2026-08-04 16:23:33 +02:00
johanleroy 9624270d9b ci: rendre lisible l'échec d'attache de release (401 / 403 distingués)
CI / No em/en dashes (push) Successful in 3s
Deploy site (production) / build-and-deploy (push) Successful in 47s
CI / Build & test (Node 24) (push) Successful in 10m12s
CI / Build & test (Node 22) (push) Successful in 10m23s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m55s
Le parsing JSON du script n'était pas tolérant à une réponse vide : sur un 401, deux
« SyntaxError: Unexpected end of JSON input » de Node s'affichaient AVANT le message d'erreur utile et
noyaient le diagnostic. La lecture de champ est désormais tolérante, et le script nomme la cause selon
le code HTTP : 401 = token invalide ou expiré, 403 = portées insuffisantes.

Testé contre un faux serveur pour les trois cas (401, 403, succès) : messages attendus et codes de
sortie corrects (1 en échec, 0 en succès).
2026-08-04 15:44:12 +02:00
johanleroy c8bf6534e0 fix(site): barre de navigation lisible à toutes les largeurs, et bouton de remontée
Les huit liens de la barre ne tiennent qu'au-delà de ~1180px. En dessous, la barre flex les compressait
au lieu de les masquer : « Start project », « Git services » et « How it works » se cassaient sur deux
ou trois lignes, les libellés recouvraient le logo et le bouton Gitea sortait du cadre. Sous 900px, il
n'y avait par ailleurs AUCUNE navigation : les sections n'étaient atteignables qu'en scrollant.

- Aucun libellé ne peut plus se casser (`whitespace-nowrap` + `shrink-0`), et le logo ne se rogne plus.
- Les liens apparaissent par palier de largeur : 4 dès 900px, 6 à partir de 1024, les 8 à partir de
  1180. Pur CSS, aucun JS, aucune mesure au runtime.
- Sous 900px, un bouton menu ouvre un panneau listant TOUS les liens (plus Gitea), refermé au choix
  d'un lien ou par Échap. Le bouton Gitea quitte la barre à ces largeurs, sinon le bouton menu se
  retrouvait tronqué au bord de l'écran sur un mobile de 390px.
- Le libellé « Gitea » n'apparaît qu'au-delà de 1180px ; en dessous l'icône suffit et l'aria-label reste.

Ajout d'un bouton « remonter en haut » en bas à droite : mêmes tokens que le reste du site, visible
seulement après 600px de défilement, cible de 44px, respecte prefers-reduced-motion.

Vérifié au rendu à 390, 760, 900, 1024, 1180 et 1440px, dans les deux thèmes, menu ouvert compris.
2026-08-04 15:43:59 +02:00
johanleroy c8d30c7b0d fix(desktop): nom d'artefact distinct pour le build Windows portable
CI / No em/en dashes (push) Successful in 3s
CI / Build & test (Node 24) (push) Successful in 10m27s
CI / Build & test (Node 22) (push) Successful in 10m58s
VSCode Release / Package VSIX (push) Successful in 9m57s
Release / Publish to Gitea npm registry (push) Successful in 10m16s
CI / Pack & boot smoke (Node 22) (push) Successful in 10m16s
Desktop Release / Build Linux (AppImage + deb) (push) Failing after 8m31s
Desktop Release / Build Windows (NSIS + portable) (push) Canceled after 0s
Desktop Release / Publish floating desktop-latest release (push) Skipped
`win.artifactName` s'applique aux deux cibles : l'installeur NSIS et le build portable produisaient
tous deux `Arboretum-<version>-x64.exe`, donc une collision où l'un écrase l'autre. Le portable prend
un suffixe explicite. Les liens de la vitrine visent l'installeur NSIS, dont le nom ne change pas.
2026-08-04 15:07:27 +02:00
johanleroy f96b36c548 ci: un token de release refusé doit faire échouer le job, pas passer inaperçu
CI / No em/en dashes (push) Successful in 3s
CI / Build & test (Node 24) (push) Successful in 10m11s
CI / Build & test (Node 22) (push) Successful in 10m26s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m52s
Avec un NPM_TOKEN expiré, les trois workflows de release sont ressortis « réussis » alors qu'aucune
release n'avait été créée et qu'aucun asset n'était attaché : l'attache était en continue-on-error et
le script sortait en 0 quand l'API refusait le token. Diagnostiquer a demandé de comparer les assets
de releases pour comprendre ce que les logs auraient dit tout de suite.

Désormais : token ABSENT (fork, run sans secret) reste un cas légitime qui sort proprement, mais un
token PRÉSENT et refusé, ou un upload d'asset en échec, fait échouer le job avec un message qui nomme
les portées attendues. Les artefacts du run sont uploadés AVANT cette étape, donc un job rouge ne
perd aucun binaire.

L'attache du VSIX passe au même script partagé : elle dupliquait la logique, avec le même angle mort.
2026-08-04 14:29:27 +02:00
johanleroy e4dd64b535 ci: corrige le contrôle d'autonomie du tarball et allège le typecheck desktop
CI / Build & test (Node 22) (push) Successful in 10m7s
CI / Build & test (Node 24) (push) Successful in 9m57s
CI / No em/en dashes (push) Successful in 3s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m50s
Release / Publish to Gitea npm registry (push) Failing after 6m5s
VSCode Release / Package VSIX (push) Successful in 10m27s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m55s
Desktop Release / Publish floating desktop-latest release (push) Successful in 18s
Desktop Release / Build Windows (NSIS + portable) (push) Canceled after 0s
Le contrôle « paquet autonome » cherchait la chaîne `@arboretum/shared` n'importe où dans le JS
publié. Un commentaire de code qui mentionne le paquet (pour dire où vit la règle partagée, cf.
core/session-match.ts) suffisait donc à faire échouer le job, alors que l'inlining était correct.
Le grep vise désormais les vraies formes d'import (from / require( / import(), ce qui est ce que la
garde veut réellement interdire.

L'étape de typecheck desktop téléchargeait ~100 Mo de binaire Electron, sur les deux versions de la
matrice : le job passait de 3 à 12 minutes. ELECTRON_SKIP_BINARY_DOWNLOAD=1 et une seule version de
Node suffisent pour un `tsc --noEmit`.
2026-08-04 13:27:32 +02:00
johanleroy 63f2697745 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).
2026-08-04 13:02:11 +02:00
johanleroy a7e04278fd release: git-arboretum 3.3.0 (« Démarrer le projet » : lancement multi-terminaux), vscode 0.4.0, desktop 0.1.3
CI / Build & test (Node 22) (push) Successful in 10m17s
CI / Build & test (Node 24) (push) Successful in 10m13s
CI / No em/en dashes (push) Successful in 4s
Deploy site (production) / build-and-deploy (push) Successful in 24s
Release / Publish to Gitea npm registry (push) Successful in 10m17s
VSCode Release / Package VSIX (push) Successful in 9m39s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 15m41s
CI / Pack & boot smoke (Node 22) (push) Successful in 10m3s
« Démarrer le projet » : un repo définit une fois ses commandes de démarrage
(serveur de dev, API, base de données), un clic ouvre un terminal PTY par
commande dans le dock IDE.

Serveur (additif, PROTOCOL_VERSION inchangé) :
- LaunchCommand[] persistées sur repos.launch_commands (migration 13) ; champ additif SessionSummary.launchRunId.
- POST /repos/:id/launch : résolution du worktree côté serveur, cwd de commande borné (anti-traversal), commandIds outrepasse enabled.
- GET /repos/:id/launch/detect : détection package.json / Procfile / docker-compose.
- Shell de login interactif ($SHELL -l -i, charge le PATH nvm/asdf) + auto-type de la commande ; le shell survit à la commande (échec visible).

Web : LaunchProjectModal + actions (ProjectTreeNode, SessionsPanel, CommandPalette), stores sessions/worktrees, i18n EN/FR.

Alignement du reste du projet :
- Extension VS Code 0.4.0 : commande Start Project (repo/worktree), Stop Launch, badge « launch » dans l'arbre, méthode REST startLaunch.
- Site vitrine : 16e feature card (Rocket) + section showcase « Start the project » (mockup fidèle au modal), i18n EN/FR.
- Documentation : README (EN + FR), help-content (EN + FR), CHANGELOGs server + vscode.

Vérifié : 430 tests, typecheck, build (web + site + vscode), acceptance-p13 ALL GREEN, VSIX packagé, garde anti-tirets, vérif visuelle du site (thèmes clair et sombre).
2026-07-21 13:54:16 +02:00
johanleroy 7327407193 release: desktop 0.1.2 (embarque le daemon 3.2.0, UI Emerald)
CI / Build & test (Node 22) (push) Successful in 10m19s
CI / Build & test (Node 24) (push) Successful in 10m6s
CI / No em/en dashes (push) Successful in 3s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 14m47s
CI / Pack & boot smoke (Node 22) (push) Successful in 10m1s
2026-07-21 08:58:55 +02:00
johanleroy 7a802e8920 release: git-arboretum 3.2.0 (refonte visuelle Emerald, thème clair/sombre, site & doc alignés)
CI / Build & test (Node 22) (push) Successful in 10m19s
CI / Build & test (Node 24) (push) Successful in 10m19s
CI / No em/en dashes (push) Successful in 6s
Deploy site (production) / build-and-deploy (push) Successful in 42s
Release / Publish to Gitea npm registry (push) Successful in 10m8s
CI / Pack & boot smoke (Node 22) (push) Successful in 10m0s
2026-07-20 22:49:51 +02:00
johanleroy adc53b413e feat(site,docs): aligne le site vitrine et la doc sur l'app « Emerald »
Site (packages/site) : adopte le design system Emerald (polices Inter +
JetBrains Mono variables, tokens sémantiques, thème clair/sombre + bascule)
et met les mockups à jour sur l'app réelle.

- style.css : tokens Emerald (@theme sombre + override html[data-theme=light]) ;
  lib/theme.ts + ThemeToggle.vue + anti-FOUC index.html ; sweep des couleurs
  brutes vers les tokens dans toutes les sections.
- Mockups fidèles à l'IDE multi-projet : HeroMockup (rail ActivityBar au lieu
  de la sidebar large + v obsolète retirée), ShowcaseSection (supervision au
  lieu du dashboard worktree-first, onglets mobiles réels), WorkspaceShowcase
  (diff-add/del, bouton commit accent-solid) ; framing « worktree-first »
  résiduel levé (i18n).
- og-cover.png rafraîchi (carte Emerald).

Docs : README.md + README.fr.md (retrait « Status: MVP », ajout du langage
Emerald + thème clair/sombre/système, VSIX 0.2.0 -> 0.3.0, section Screenshots),
vscode README (VSIX 0.3.0), brand README (thème clair), CHANGELOG daemon 3.2.0.
Captures IDE sombre + clair (brand/screenshot-ide-*.png).
2026-07-20 22:48:59 +02:00
johanleroy 063f5e928b feat(web): refonte visuelle « Emerald » (thème clair/sombre, polices, tokens)
Adopte le langage visuel du design system Emerald dans l'IDE web :
neutres zinc + accent emerald, polices auto-hébergées Inter + JetBrains
Mono, radii/pills mono, points de statut, motif terminal, halo/grain.
Refonte purement visuelle et additive (layout, routing, stores, protocole
inchangés).

- style.css : défauts sombres dans @theme + override clair sous
  html[data-theme=light] ; accent scindé (bright #34d399 / solid #059669 /
  hover) ; tokens border-soft/info/warn/danger/coffee ; idiomes globaux
  (focus/selection accent, scrollbars fines, jl-pulse/jl-blink, classes
  .chip/.status/.eyebrow/.label-mono/.caret/.halo/.grain, .btn*/.badge pill).
- lib/theme.ts : singleton themeMode/resolvedTheme (dark/light/system,
  persistedRef arb.theme) + application dataset.theme/metas ; script
  anti-FOUC inline dans index.html ; toggle ActivityBar + Réglages.
- Thèmes Monaco + xterm dark/light réactifs (palette ANSI + coloration
  syntaxique) ; fonts.ready + remeasureFonts pour l'alignement des glyphes.
- status-tokens : tons sémantiques tokenisés ; balayage des ~340 couleurs
  Tailwind brutes vers les tokens sur tout components/* et views/*
  (exceptions assumées commentées).
- GroupSummary.color exploité : icône de groupe teintée + ColorSwatchPicker
  (lib/group-colors.ts) dans les modals de groupe.
- Polices via @fontsource-variable/{inter,jetbrains-mono} (offline).
2026-07-20 21:30:57 +02:00
johanleroy 008e976e01 release: git-arboretum 3.1.0 (IDE unique), desktop 0.1.1 (fix logo Debian)
CI / Build & test (Node 22) (push) Successful in 10m13s
CI / Build & test (Node 24) (push) Successful in 10m6s
CI / No em/en dashes (push) Successful in 3s
Release / Publish to Gitea npm registry (push) Successful in 9m55s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 14m9s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m56s
2026-07-20 12:11:50 +02:00
johanleroy 662c537ac4 fix(desktop): logo manquant sous Debian/Wayland
Sous Wayland (défaut Debian/GNOME) l'option icon: de BrowserWindow est
ignorée : l'icône de fenêtre/dock vient du .desktop apparié via l'app_id.
electron-builder pose déjà StartupWMClass=productName, mais l'app_id runtime
ne valait pas "Arboretum" (dérivé du name package.json). On force donc
app.setName('Arboretum') avant app.whenReady(), et on rend StartupWMClass
explicite dans electron-builder.yml. Prend effet après rebuild + réinstall
du .deb.
2026-07-20 12:10:23 +02:00
johanleroy c694f9f2dd feat(web): IDE unique comme seule coquille, ancien dashboard retiré
L'IDE (/ide) devient l'unique interface sur tous les supports (navigateur,
PWA, app Electron chargent la même SPA). Tout le cycle de vie de l'ancien
monde est réintégré dans l'IDE ; AppShell et les vues Dashboard / Sessions /
Groups / GroupView / SessionView sont supprimés.

- Infra: pile de modals Teleport (stores/modals.ts + ModalHost) et menu
  contextuel (useContextMenu + ContextMenu), montés dans IdeShell sans le
  démonter (attaches WS du dock préservées).
- Explorer: créer worktree (branche + baseRef + session), travailler sur main,
  prune, promote (escalade force), supprimer worktree, commit/push, masquer/
  supprimer repo, ajouter dépôt local ou cloner.
- Sessions: create/kill/resume/fork, hide/unhide, archive/unarchive, masquer
  les découvertes, supervision AttentionList + réponse aux dialogues.
- Groupes: create/delete, composition, lancement de session de groupe (ouvre
  le terminal dans le dock).
- Compte: Réglages et Aide en overlays par-dessus l'IDE ; langue, push/PWA,
  tokens, connexions git, RGPD, déconnexion. Command Palette et deep-links
  recâblés pour rester dans l'IDE.
- Routes: les anciens chemins rendent IdeShell via meta (overlay/panel/
  terminal) ; /workspace/:repoId/:wt inchangé (contrat extension VS Code).
  Mobile: nav à 6 panneaux (explorer/editor/terminal/git/sessions/groups).

La grille multi-terminaux de groupe est retirée (supplantée par la session de
groupe unique P6 via --add-dir + le dock multi-onglets).
2026-07-20 12:10:12 +02:00
johanleroy e48798ebff fix(ci): release.yml invalide, ': ' dans un nom d'étape cassait le YAML
CI / Build & test (Node 22) (push) Successful in 10m13s
CI / Build & test (Node 24) (push) Successful in 10m6s
CI / No em/en dashes (push) Successful in 3s
Release / Publish to Gitea npm registry (push) Successful in 9m59s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m58s
Séquelle du nettoyage des tirets : un tiret cadratin dans le nom de l'étape
« Publish » avait été remplacé par ' : ', or un scalaire YAML non quoté ne
peut pas contenir deux-points+espace ("mapping values are not allowed").
Remplacé par une virgule. Gitea refusait de lancer le workflow → la
publication npm du daemon sur un tag v* ne partait pas.
2026-07-17 21:55:53 +02:00
johanleroy 1a74576955 feat(desktop): logo de fenêtre, homepage vitrine, licence MIT ; attache release idempotente
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m34s
CI / Build & test (Node 22) (push) Has been cancelled
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
- Fenêtre principale : icône explicite (resolveIconPath partagé dans paths.ts,
  réutilisé par le tray) pour afficher le logo Arboretum en fenêtre/barre des
  tâches au lieu de l'icône Electron générique.
- package.json desktop : homepage -> https://git-arboretum.com (la vitrine, plus
  le dépôt Gitea) et champ license: MIT. Copyright daté avec le nom dans
  electron-builder.yml. Licence MIT + author aussi au package.json racine.
- desktop-release.yml : attache des assets idempotente (supprime l'asset de même
  nom avant ré-upload) pour que le dernier build gagne sur un re-run.
2026-07-17 21:46:22 +02:00
johanleroy bd76e53570 docs(ci): documenter la portée write:repository requise de NPM_TOKEN
CI / Build & test (Node 22) (push) Successful in 10m15s
CI / Build & test (Node 24) (push) Successful in 10m10s
CI / No em/en dashes (push) Successful in 3s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 14m1s
CI / Pack & boot smoke (Node 22) (push) Successful in 10m5s
L'attache des installeurs/VSIX à la release Gitea réutilise NPM_TOKEN ; ce
token doit porter write:repository EN PLUS de write:package, sinon l'API
release renvoie 403 (l'étape est best-effort, non bloquante : les artefacts
restent disponibles via upload-artifact).
2026-07-17 20:42:21 +02:00
johanleroy b0a75df204 fix(desktop): métadonnées de packaging .deb (homepage, author.email, maintainer)
CI / Build & test (Node 22) (push) Successful in 10m10s
CI / Build & test (Node 24) (push) Successful in 10m6s
CI / No em/en dashes (push) Successful in 5s
Desktop Release / Build Linux (AppImage + deb) (push) Successful in 13m39s
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
electron-builder exige un homepage projet, un author.email et un maintainer
.deb : le build Linux produisait l'AppImage mais échouait sur la cible deb.
Ajoute ces champs au package.json desktop et fixe explicitement le
maintainer dans electron-builder.yml.
2026-07-17 20:04:50 +02:00
johanleroy c7af406cbf release: IDE multi-projet + app native (git-arboretum 3.0.0, vscode 0.3.0, desktop 0.1.0)
CI / Build & test (Node 22) (push) Successful in 10m13s
CI / Build & test (Node 24) (push) Successful in 10m6s
CI / No em/en dashes (push) Successful in 3s
VSCode Release / Package VSIX (push) Successful in 9m38s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m56s
Desktop Release / Build Linux (AppImage + deb) (push) Failing after 6m11s
Daemon 3.0.0 : marque le cap « IDE IA multi-projet + app de bureau native » (refonte additive, PROTOCOL_VERSION inchangé ; le tarball embarque la nouvelle SPA IDE + le handshake token desktop). Extension VS Code 0.3.0 : deep-link « Open Worktree IDE » vers l'IDE multi-projet, encodage wt-key unifié via @arboretum/shared (CHANGELOG + README à jour). Paquet desktop 0.1.0 (première release).

package.json ET package-lock.json bumpés (npm ci strict). 431 tests, 0 tiret, builds daemon/web/vscode/site verts.
2026-07-17 18:31:37 +02:00
johanleroy 8042376f9c fix(site): fidélité des mockups au nouvel IDE (HeroMockup, ShowcaseSection)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Deploy site (production) / build-and-deploy (push) Successful in 16s
HeroMockup : entrée de nav « IDE » active en tête (comme AppSidebar), badge version v2.0.0 (au lieu de v1.6.0 figé). ShowcaseSection : entrée « IDE » ajoutée à la barre d'onglets mobile (comme MobileTabBar). Clé i18n mIde (EN/FR). build:site vert, 0 tiret.
2026-07-17 18:28:04 +02:00
johanleroy ef21b03d9c feat(site): vitrine recadrée IDE multi-projet + section Download desktop (D2)
CI / Build & test (Node 22) (push) Successful in 10m11s
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 24) (push) Has been cancelled
Deploy site (production) / build-and-deploy (push) Has been cancelled
i18n EN/FR (miroir) : hero, section « workspace » et carte feature 11 recadrés vers l'IDE multi-projet (arbre unique, onglets, dock bas), + clés de la section Download. Nouvelle section DownloadSection.vue (app de bureau : Linux/Windows/macOS, runtime embarqué, auto-update ; boutons vers la page des releases et le build depuis les sources) + entrée de nav « Download ».

Mockup WorkspaceShowcase redessiné sur le nouvel IDE : barre d'activité, arbre unifié multi-projet (api/web + worktree + session), éditeur à onglets, diff, dock terminaux à onglets, barre de statut. build:site vert, 0 tiret.
2026-07-17 18:14:39 +02:00
johanleroy 0532331795 docs(D1): README EN/FR + ENTERPRISE recadrés IDE multi-projet + app native
README.md et README.fr.md (miroir strict, 18 sections) : tagline et « What Arboretum does » recadrés vers l'IDE IA multi-projet (arbre unique, onglets, dock terminaux, panneaux git), nouvelle section « Desktop app » / « Application de bureau » (3 OS, runtime embarqué donc pas de Node à installer côté app, auto-update, SmartScreen/Gatekeeper), « The IDE, workspace & git operations » réécrit, « Requirements » précisé. Pas d'URL d'artefact inventée (page des releases + packages/desktop).

docs/ENTERPRISE_DEPLOYMENT.md : app desktop = client autonome additif (daemon local embarqué), déploiement serveur inchangé. 0 tiret (garde CI).
2026-07-17 18:14:25 +02:00
johanleroy 1299b1b349 ci(desktop): workflow de release (C6) sur tag desktop-v*
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
.gitea/workflows/desktop-release.yml : garde-fou tag==version (packages/desktop), npm ci racine + npm ci desktop (hors workspaces), npm run dist:linux (AppImage+deb), artefacts + attachement des installeurs et de latest-linux.yml (auto-update) à la release Gitea via NPM_TOKEN. Windows/macOS : build manuel sur ces OS (README desktop). N'affecte aucun workflow existant (tag desktop-v* distinct de v* et vscode-v*).
2026-07-17 18:05:36 +02:00
johanleroy ccbc1b9e4e feat(desktop): tray + lancement au login + auto-update (C5)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
tray.ts : icône de barre système (Ouvrir, bascule « Launch at login », Quitter). autostart.ts : login items (Windows/macOS) + fichier ~/.config/autostart/*.desktop (Linux). updater.ts : electron-updater (provider generic -> release Gitea), no-op en dev, actif Windows/Linux. main.ts : fermeture de fenêtre = réduction dans le tray, quit explicite via tray/menu, arrêt propre du daemon avant sortie.

icon.png ajouté aux extraResources (tray en packagé). Vérifié : typecheck contre l'API Electron + electron-updater, bundle esbuild.
2026-07-17 18:04:36 +02:00
johanleroy c9811fc0ca feat(desktop): packaging Windows + macOS (C3/C4) : icône, cibles, doc de build
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
resources/icon.png (source unique, electron-builder dérive tous les formats/tailles par OS). electron-builder.yml : cibles Windows (nsis+portable) et macOS (dmg/zip non signé) déjà présentes. daemon.ts gère SIGTERM puis SIGKILL (Windows sans SIGTERM natif).

README desktop : build par OS (dist:linux/win/mac), ConPTY Windows + SmartScreen (éditeur inconnu), Gatekeeper macOS (clic droit Ouvrir / xattr), limites du cross-build, prérequis git/claude sur le PATH. Les builds Windows/macOS se font sur ces OS.
2026-07-17 18:01:48 +02:00
johanleroy 82682b0a37 feat(desktop): packaging (C2) : prepare-server, fetch-node, electron-builder
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
scripts/prepare-server.mjs : rebuild forcé shared+server (évite la non-idempotence du prepack), npm pack du daemon (tarball autonome), extraction, strip des devDependencies (dont @arboretum/shared inliné, non publié), npm install --omit=dev des deps runtime avec le bon prebuild node-pty (cross via npm_config_platform/arch). scripts/fetch-node.mjs : Node standalone épinglé (22.21.1) vérifié SHA256 -> build/node.

electron-builder.yml : dist/ en ASAR ; build/server et build/node en extraResources (hors ASAR pour les .node) ; cibles Linux (AppImage+deb), Windows (nsis+portable), macOS (dmg/zip non signé) ; publish generic -> release Gitea. Scripts dist:linux/win/mac.

Vérifié : fetch-node (Node bundlé + node:sqlite), prepare-server (structure complète), et la chaîne runtime complète (Node bundlé exécute le daemon empaqueté : handshake + session bash via node-pty OK). Le wrapping electron-builder est une étape machine.
2026-07-17 17:59:32 +02:00
johanleroy ae7ede6684 feat(desktop): squelette Electron (C1) : daemon enfant + auth auto
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Nouveau paquet packages/desktop (Electron, autonome, HORS des workspaces racine pour ne pas alourdir la CI du daemon). Process principal : lance le daemon en enfant (Node), lit le handshake token sur le fd 3, pose le cookie de session server-to-server (session.fetch) puis charge la SPA sur 127.0.0.1 (aucun écran de login). Fenêtre sûre (contextIsolation, sandbox, nodeIntegration off, preload minimal), instance unique, liens externes vers le navigateur, permissions limitées aux notifications, état de fenêtre persistant, arrêt propre du daemon (SIGTERM puis SIGKILL).

Vérifié ici : tsc contre l'API Electron réelle + bundle esbuild (main/preload). Le run GUI et le packaging se font sur une machine avec affichage (C2+). Racine workspaces passée en liste explicite (5 paquets) pour exclure desktop du npm ci racine.
2026-07-17 17:51:12 +02:00
johanleroy de066abb54 feat(server): handshake token pour un shell embarquant le daemon (app de bureau)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Dans runDaemon, si ARBORETUM_EMIT_TOKEN_FD est fourni, mint un token 'desktop' et l'écrit en JSON {token,url} sur ce descripteur (pipe stdio privé parent-enfant). Additif et gardé : sans la variable, comportement strictement inchangé. Permettra à l'app Electron d'ouvrir la SPA déjà authentifiée sans écran de login. Vérifié (handshake OK), 431 tests.
2026-07-17 17:44:36 +02:00
johanleroy 4798732856 feat(web): IDE responsive (panneau unique mobile) + défaut adapté à l'écran
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
IdeShell dégrade sous le breakpoint md en un panneau unique (Explorateur/Éditeur/Terminal/Git) commuté par une barre d'onglets basse, avec un bouton retour vers le dashboard. La redirection / envoie le mobile vers /dashboard (supervision + nav) et le desktop vers /ide.

Garde-fou : pas de '<' dans les commentaires de template Vue (rolldown casse le build alors que vue-tsc passe). 431 tests.
2026-07-17 17:40:44 +02:00
johanleroy d287c3c1d1 feat: l'IDE devient la vue par défaut + deep-link worktree unifié
CI / Build & test (Node 22) (push) Successful in 10m13s
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 24) (push) Has been cancelled
Route / redirige vers /ide ; le dashboard passe à /dashboard (nom inchangé). /workspace/:repoId/:wt rend désormais l'IDE (IdeShell) : au montage il décode la clé, active et déplie le worktree ciblé, ouvre ?file= le cas échéant. WorkspaceView et useWorkspaceLayout retirés.

encode/decodeWtKey déplacés dans @arboretum/shared (source unique) avec décodeur TOLÉRANT (base64url OU chemin percent-encodé), corrigeant la divergence historique du deep-link VS Code. config.ts de l'extension aligné sur encodeWtKey. Tests wt-key (shared) + config (vscode) mis à jour. 431 tests.
2026-07-17 17:28:48 +02:00
johanleroy 6741b2d47c feat(web): panneaux IDE Git / Sessions / Groupes
CI / Build & test (Node 22) (push) Successful in 10m15s
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 24) (push) Has been cancelled
components/ide/GitPanel.vue : CommitPanel ciblant le worktree actif (ide.activeContext), chargement des changements + abonnement disque (watchWorktree) ré-abonné au changement de worktree ; sélection d'un fichier ouvre un onglet diff. SessionsPanel : sessions vivantes -> ouverture dans le dock. GroupsPanel : groupes (getters) avec passerelle vers la vue Groupes.

PrimarySidebar aiguille désormais Explorer/Git/Sessions/Groupes vers ces panneaux (fin des placeholders). vue-tsc + build web verts.
2026-07-17 17:17:27 +02:00
johanleroy 5302bf29ae feat(web): dock terminaux en bas (multi-sessions attachées)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
components/ide/TerminalDock.vue + TerminalDockTabs.vue : dock à onglets, une TerminalView par session du dock, toutes montées en v-show pour préserver l'attache WS (seule l'active visible). Fermer un onglet démonte réellement la vue -> detach() propre, pas de fuite. DialogPrompt au-dessus du terminal actif en attente. Repli via la barre de statut ou le chevron.

Branché dans IdeShell (section dock redimensionnable, splitter inversé). 427 tests.
2026-07-17 17:14:40 +02:00
johanleroy f62404234b feat(web): zone éditeur à onglets (Monaco multi-modèles + diff)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
components/ide/EditorArea.vue : UNE instance Monaco partagée avec cache de modèles par onglet (préserve contenu, undo et curseur au changement d'onglet ; view states restaurés), thème arboretum-dark, save + conflit STALE_FILE + reload/overwrite, dispose des modèles à la fermeture d'onglet et au démontage. Onglets diff via DiffViewer.

components/ide/EditorTabs.vue : bandeau d'onglets multi-projets, point de modification, fermeture immédiate si propre et garde à deux clics si modifié. Bascule éditeur/diff par onglet. Branché dans IdeShell (centre). 427 tests.
2026-07-17 17:12:15 +02:00
johanleroy c96d929c7a feat(web): coquille IDE + arbre de projets unifié (route /ide)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
components/ide/ : IdeShell (grille barre d'activité + panneau gauche + zone centrale + dock + barre de statut, splitters persistés, réconciliation des ressources ouvertes contre les données live), ActivityBar (Explorer/Git/Sessions/Groupes + Réglages/Aide), PrimarySidebar, ProjectTree + ProjectTreeNode (arbre unique repos -> worktrees -> sessions, fichiers embarqués via FileTree en mode sans chrome, dépliage paresseux), StatusBar.

Route /ide (layout 'ide'), entrée de nav « IDE », namespace i18n ide (EN/FR). Clics de l'arbre pilotent le store (contexte worktree, ouverture de fichier/terminal). Centre et dock en placeholders (remplis en B4/B5). FileTree gagne un mode embedded. 427 tests.
2026-07-17 17:08:35 +02:00
johanleroy 6acd4a16fd feat(web): store IDE (onglets, dock terminaux, panneaux, réconciliation)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
stores/ide.ts : état de vue de l'IDE (onglets éditeur, dock de sessions, activité, contexte worktree actif, tailles/visibilité des panneaux, expansion de l'arbre), en références uniquement (ids/chemins), persisté par persistedRef via mises à jour immuables. dirty reste volatile.

pruneDeadResources réconcilie au bootstrap (retire onglets/terminaux dont worktree/session n'existent plus). Store pur, sans couplage aux stores de données (résolution côté composants). 11 tests unitaires.
2026-07-17 16:59:44 +02:00
johanleroy cf60fa3a56 feat(web): infra IDE réutilisable (persisted-ref, splitter, bootstrap temps réel)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Extrait persistedRef dans lib/persisted-ref.ts (partagé, testable en node). Ajoute useSplitter + components/ide/PanelSplitter.vue (poignée de resize générique par pointer events, largeur/hauteur persistable), généralisant le resize souris de WorkspaceView.

Hisse le chargement initial et les abonnements temps réel dans useRealtimeBootstrap (monté par App.vue) : un seul propriétaire actif sur TOUS les layouts, y compris la vue IDE plein écran. AppShell et WorkspaceView n'en portent plus la responsabilité. Tests unitaires persisted-ref et useSplitter (10).
2026-07-17 16:55:14 +02:00
johanleroy 9a496abd00 feat(web): couche de tokens de design centralisée (surfaces, statuts, terminal)
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Introduit une couche sémantique dans style.css (@theme) : surfaces (surface-0..3), bordures, texte (fg/muted/subtle) et accent, aliasant la palette Tailwind (rendu identique, vérifié dans le CSS produit). Ajoute les métriques du chrome IDE (--ide-*) pour la refonte à venir.

Centralise deux sources uniques : lib/terminal-theme.ts (thème + police xterm) et lib/status-tokens.ts (tons de statut, dédupliqués entre BaseBadge et SessionStateBadge). Définit le thème Monaco « arboretum-dark ». Remplace les #09090b épars des composants par bg-surface-0 (ne restent que index.html et les renderers exigeant un hex concret).
2026-07-17 16:50:58 +02:00
johanleroy 65ef616867 chore(typo): retire tous les tirets cadratins/demi-cadratins + garde CI
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / No em/en dashes (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Deploy site (production) / build-and-deploy (push) Successful in 20s
Remplace les 547 tirets cadratins (U+2014) et demi-cadratins (U+2013) des fichiers versionnés par la ponctuation contextuelle adaptée (point médian, deux-points, virgule, parenthèses ; tiret simple pour les plages), sur 122 fichiers (appli, vitrine, doc, tests, workflows, scripts).

Ajoute le job CI « lint-dashes » (git grep -P) qui échoue si un tiret cadratin/demi-cadratin réapparaît, hors logo binaire et captures brutes du terminal (fidélité des fixtures de détection de dialogue).
2026-07-17 16:44:00 +02:00
johanleroy 985531a986 release: git-arboretum 2.0.0
CI / Build & test (Node 22) (push) Successful in 10m10s
CI / Build & test (Node 24) (push) Successful in 10m6s
Deploy site (production) / build-and-deploy (push) Successful in 17s
Release / Publish to Gitea npm registry (push) Successful in 10m1s
VSCode Release / Package VSIX (push) Successful in 9m41s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m58s
Refonte « vrai IDE IA worktree » (P7→P12) : additif et rétrocompatible
(PROTOCOL_VERSION inchangé), majeure pour marquer le cap produit.
2026-06-27 16:04:37 +02:00
johanleroy d4e3ab47cd feat(vscode): statut git détaillé, sessions archivées, lien IDE web, fetch/pull (0.2.0)
Reflète la refonte IDE en supervision légère, sans dupliquer l'éditeur :
- statut git fin dans l'arbre (staged/unstaged/conflits + dernier commit) ;
- commande « Open Worktree IDE » → deep-link /workspace/:repoId/:wt ;
- commandes fetch / pull (ff-only|rebase) sur les worktrees ;
- event WS session_archived + réglage showArchivedSessions (badge + filtre).
README/CHANGELOG + tests (config/rest-client/ws-client).
2026-06-27 16:04:28 +02:00
johanleroy 8a8fac75e6 feat(site): showcase IDE workspace, diff/staging et services git distants
- WorkspaceShowcase.vue : maquette fidèle de la vue /workspace (arbre de
  fichiers + panneau commit staging/amend + diff coloré + terminal corrélé).
- RemoteGitSection.vue : connexions GitHub/GitLab/Gitea (chiffrées at-rest)
  + barre de progression de clone.
- 5 cartes features, pilier sécurité « Encrypted secrets », 3 FAQ, ancre nav.
- i18n EN/FR à parité ; meta description orientée IDE. Bump 0.2.0.
2026-06-27 16:04:19 +02:00
johanleroy ac4d098b53 docs: README EN/FR — refonte « IDE worktree » (P7→P12)
Workspace IDE (arbre + Monaco + diff + terminal), moteur git détaillé +
watcher FS temps réel, commit/push avancé, archivage auto des sessions,
sync des réglages en temps réel, services git distants chiffrés + clone.
Section VS Code mise à jour (fetch/pull, lien IDE web, VSIX 0.2.0).
2026-06-27 16:04:11 +02:00
johanleroy 08695a707d feat(p12a): services git distants (PAT/app_password) + clone HTTPS
Modèle de données :
- migration #11 git_credentials (secrets chiffrés SecretBox : secret_encrypted ; colonnes ssh/oauth posées pour P12b/P12c) ; #12 repos ALTER remote_url/git_service/credential_id (pas de FK)
- types partagés api.ts (GitCredentialSummary sans secret + hasSecret/secretLast4, CRUD, RemoteRepoSummary, Clone*) ; protocole additif : topic 'clones' + message clone_update (CloneOperation)

Backend :
- core/git-credentials.ts (GitCredentialsManager(db, box)) : CRUD chiffré, test() (GET /user), getSecret()/authContext() internes, NULLification de repos.credential_id à la suppression
- core/git-clients/ (github/gitlab/gitea) via fetch, sans dépendance : verify()+listRepos() paginés, erreurs typées AUTH_FAILED/RATE_LIMITED/UNREACHABLE, SSRF base_url http(s)
- core/git-auth.ts : withGitAuth (GIT_ASKPASS éphémère 0o700, secret par env, GIT_TERMINAL_PROMPT=0, jamais dans l'URL/.git/config, nettoyage finally)
- core/git.ts cloneRepo (spawn git clone --progress, parse progression, timeout)
- core/clone-manager.ts (EventEmitter) : clone async, dest confiné sous scanRoots + non existant, auto-enregistrement via addRepo + métadonnées de provenance, nettoyage du clone partiel, events topic 'clones'
- routes/git-connections.ts (CRUD + /test + /:id/repos + POST /repos/clone 202 + GET /repos/clone/:id) ; app.ts câble box→GitCredentialsManager + CloneManager→gateway ; gateway relaie 'clones'

Frontend :
- ws-client subscribeClones ; stores git-connections + clone (suivi WS)
- components/settings/GitConnectionsSection (liste + formulaire pat/app_password, secret jamais ré-affiché) inséré dans SettingsView ; CloneRepoModal (connexion → repos distants paginés → dest scanRoots[0] → barre de progression WS → redirection) ; bouton « Cloner » dans DashboardView ; i18n EN+FR

Tests : git-credentials (round-trip SecretBox, résumé sans secret, NULLification) ; acceptance-p12.mjs (clone bare local file:// → clone_update done + repo enregistré + secret ABSENT de l'API, de la DB et du .git/config)

Sous-phases restantes : P12b (SSH), P12c (OAuth device flow).
2026-06-27 14:27:18 +02:00
johanleroy e8d10b7ec0 feat(p11): temps réel complet (watcher checkout principal + topic settings)
P11-A — branche du checkout principal modifiée hors Arboretum :
- fs-watcher: pin « permanent » non évinçable (pinRepo/unpinRepo, repoPins dans evictIfNeeded)
- worktree-manager: armMainCheckoutWatchers() + arm/désarm sur addRepo/découverte/removeRepo/hidden
- index.ts: armMainCheckoutWatchers() dans runDaemon → git checkout CLI sur le principal → worktree_update <500ms sans watch client

P11-B — réglages en temps réel :
- protocole additif: type SettingsBroadcast (source unique, réutilisé par SettingsResponse), topic 'settings', message settings_update (validés parseClientMessage + gateway)
- core/settings-bus.ts (EventEmitter) ; routes/settings émet après PATCH ; gateway relaie aux abonnés 'settings'
- web: ws-client subscribeSettings + routage ; store settings applySettings/startRealtime ; AppShell abonne globalement ; SettingsView re-sync des drafts scalaires sans écraser une saisie en cours
- tests: protocol (topic settings) + fs-watcher (pinRepo non évincé) ; acceptance-p11.mjs (checkout principal <500ms + settings_update)
2026-06-27 14:08:44 +02:00
johanleroy 92670a796a feat(p9): commit/push avancé dans l'IDE (staging sélectif, discard, amend, fetch/pull)
- components/workspace/CommitPanel.vue : staging sélectif par fichier (stage/unstage/stage all/unstage all), discard avec confirmation (includeUntracked), zone de commit (message + amend), commit mode 'staged', push, fetch, pull --ff-only (rebase proposé en cas de divergence), gestion 409 ALREADY_PUSHED
- components/workspace/FileRow.vue : ligne de fichier réutilisable (badge statut M/A/D/?/U + clic → diff + slot actions)
- WorkspaceView : CommitPanel remplace ChangedFilesPanel ; @changed → reload des changements
- stores/worktrees : applyWorktree (upsert depuis les mutations git → header live)
- i18n EN+FR (commit.*) ; acceptance-p9.mjs (staging sélectif, amend OK/409, pull ff-only OK + divergence refusée)
2026-06-27 13:53:05 +02:00
johanleroy 75efecf93f feat(p8): vue IDE /workspace (arbre + Monaco + diff + terminal)
- backend: garde-fou conflit d'édition par mtime (GET renvoie mtime, PUT refuse en 409 STALE_FILE si baseMtime périmé)
- lib: wt-key (base64url du chemin worktree), diff-parse (parseur pur du diff unifié → hunks)
- composables: useMonaco (import dynamique → chunk isolé), useWorkspaceLayout (largeurs/panneau persistés)
- components/workspace: GitStatusBadge, FileTree+FileTreeNode (lazy fs/list includeFiles), ChangedFilesPanel, DiffViewer (coloration +/-), MonacoEditor (Ctrl+S + bannière conflit reload/overwrite)
- views/WorkspaceView: 3 colonnes desktop redimensionnables + SegmentedControl mobile, header live (GitStatusBadge), watchWorktree → refresh diff/changements, terminal de la session corrélée
- router meta 'ide' + route /workspace/:repoId/:wt ; App.vue plein écran sans AppShell ; WorktreeCard bouton « Ouvrir l'IDE »
- deps: monaco-editor (lazy, vendor-monaco isolé, 0 impact bundle initial) ; vite manualChunks
- i18n EN+FR (workspace/editor/diff/git) ; tests diff-parse + wt-key ; acceptance-p8.mjs (mtime/409 + diff)
2026-06-27 13:47:10 +02:00
johanleroy c8dd539571 feat(p10): archivage automatique des sessions terminées (rétention configurable)
- DB: migration #10 (sessions.archived_at + index), helpers archive/unarchive/archiveExpired (soft-archive, jamais de DELETE)
- core/retention-settings.ts: session_retention_days (défaut 30, 0=jamais, 1-3650) + session_purge_days (off)
- core/session-archive.ts: scheduler start/stop/sweep (calqué DiscoveryService), câblé dans runDaemon
- pty-manager.list({includeArchived}) + SessionSummary.archived + emitHistoricalUpdate
- routes: GET /sessions?includeArchived, POST/DELETE /sessions/:id/archive, POST /sessions/archive-now
- protocole additif: message WS session_archived (relayé par la gateway, abonnés 'sessions')
- settings: retentionDays/purgeDays exposés et validés dans PATCH /settings
- web: store sessions (showArchived + archive/unarchive), SessionsListView (toggle/badge/actions), SettingsView (slider rétention), i18n EN+FR
- tests: retention-settings + session-archive (vitest) + settings-routes étendu ; acceptance-p10.mjs (sweep, event WS, resume d'une session archivée → 201, rétention=0)
2026-06-27 13:31:28 +02:00
johanleroy be43911dc0 feat(p7): moteur git détaillé, API fichiers et watcher FS temps réel
Fondations de la refonte « vrai IDE IA worktree » (chantier P7→P12).

- git.ts : listChanges (status --porcelain=v2 -z + --numstat fusionnés),
  fileDiff (diff unifié borné, refus binaire, untracked via --no-index),
  stage/unstage/restore/clean, commitStaged, amendCommit (refus si poussé),
  fetchRemote, pull (ff-only|rebase), lastCommit, resolveGitDir,
  isSafeRelativePath ; worktreeStatus enrichi (compteurs staged/unstaged/
  conflict + dernier commit), champs additifs WorktreeGitStatus.
- core/fs-watcher.ts : FsWatcherService (chokidar, refcount + pool LRU borné,
  ignore .git sauf HEAD/index, débounce) → invalide factsCache, rediffuse
  worktree_update et émet worktree_changes.
- WorktreeManager : getWorktreeChanges/getFileDiff/stage/unstage/discard/
  fetch/pull/watch/unwatch/assertPathInWorktree ; commitWorktree { mode, amend }.
- routes/git.ts (changes/diff/stage/unstage/discard/fetch/pull) et
  routes/files.ts (GET/PUT contenu fichier, bornage strict au worktree) ;
  fs/list?includeFiles=1 (flag isFile).
- protocole ADDITIF (PROTOCOL_VERSION inchangé) : messages WS watch/unwatch
  (validés dans parseClientMessage) + worktree_changes poussé ciblé par la
  gateway ; front wsClient.watchWorktree + lib/git-api.ts + api.put.
- tests git/fs-watcher/protocole + acceptance-p7.mjs (ALL GREEN).
- dépendance : chokidar (serveur).
2026-06-27 12:15:00 +02:00
johanleroy 062bb64d41 release: git-arboretum 0.1.1
CI / Build & test (Node 22) (push) Successful in 10m6s
CI / Build & test (Node 24) (push) Successful in 9m58s
Deploy site (production) / build-and-deploy (push) Successful in 15s
VSCode Release / Package VSIX (push) Successful in 9m37s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m50s
2026-06-24 10:28:44 +02:00
johanleroy a67871b9b9 release: @johanleroy/git-arboretum 1.11.0
Release / Publish to Gitea npm registry (push) Successful in 9m52s
2026-06-24 10:28:28 +02:00
johanleroy 69123eaf0e feat(site): renomme l'état de session « inactif » en « disponible »
Aligne le site marketing sur le renommage de l'app (idle → disponible /
available), badges d'état et FAQ (EN + FR).
2026-06-24 10:28:28 +02:00
johanleroy 0f126cf911 fix(web): repeindre les terminaux au retour-visible + flush ACK ciblé
CI / Build & test (Node 24) (push) Has been cancelled
CI / Pack & boot smoke (Node 22) (push) Has been cancelled
CI / Build & test (Node 22) (push) Has been cancelled
Un terminal caché dans une grille de groupe (ou hors-écran) n'était pas repeint
au retour — `visibilitychange` ne couvre que l'onglet — d'où l'écran noir avec
curseur ; et son ACK ne progressait plus (callback xterm.write throttlé) → le
serveur mettait le PTY en pause → sortie « par à-coups ». Ajoute un
IntersectionObserver (repaint + flushAck ciblé au retour-visible) et expose
Attachment.flushAck (factorisé avec flushAcks).
2026-06-24 10:15:29 +02:00
johanleroy b5236b41c8 feat(settings): réglages Claude CLI (binaire + ~/.claude) & notif « disponible »
- Réglages → Claude CLI : override du chemin du binaire `claude` (effet à la
  prochaine session, fallback `which claude`), diagnostic de détection, et
  override de la racine ~/.claude (effet au redémarrage). Validateurs stricts.
- Push : notifie aussi sur le front busy→idle (session redevenue disponible).
- Renomme l'état affiché idle → « disponible » / « available » (web EN/FR + VS Code) ;
  l'enum SessionActivity du protocole reste inchangé.
2026-06-24 10:15:29 +02:00
johanleroy 2506dfb1f3 fix(cli): figer le PATH d'installation dans l'unit systemd / plist launchd
Un service systemd user / LaunchAgent démarre avec un PATH minimal qui n'inclut
pas ~/.local/bin (où vit le binaire `claude`) → resolveClaudeBin (`which claude`)
échouait avec « Claude Code CLI not found in PATH ». `arboretum install` fige
désormais le PATH de l'environnement d'installation dans l'unit/plist.
2026-06-24 10:15:29 +02:00
johanleroy 7d618c30d5 release: @johanleroy/git-arboretum 1.10.0
CI / Build & test (Node 22) (push) Successful in 10m6s
CI / Build & test (Node 24) (push) Successful in 9m58s
Deploy site (production) / build-and-deploy (push) Successful in 15s
Release / Publish to Gitea npm registry (push) Successful in 9m51s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m50s
2026-06-23 18:52:39 +02:00
johanleroy 529c136199 docs(site): carte feature « créer un projet » 2026-06-23 18:52:39 +02:00
johanleroy 7fc1f6f747 fix(ci): restreindre la release daemon aux tags v[0-9]*
Le trigger 'v*' capturait aussi les tags 'vscode-v*' de l'extension : le workflow strippait alors
'v' (→ scode-v0.1.0) et échouait contre la version du daemon. 'v[0-9]*' n'écoute que les tags vX.Y.Z.
2026-06-23 18:52:39 +02:00
johanleroy 8b9060e0c0 feat: création de projet (nouveau dossier + session) & en-tête de session enrichi
- POST /api/v1/projects : crée <root>/<name> (mkdir non récursif, 409 si existant),
  git init optionnel, puis lance une session dedans. Anti-traversal sur le nom (core/project.ts).
- Web : NewProjectModal (racine préremplie scanRoots[0], case git init) + bouton dans SessionsListView.
- SessionContextBar : badge du groupe (cliquable) + repos couverts avec leur branche dans l'en-tête
  de session ; session simple = repo+branche déduits du cwd.
- 14 tests (unitaires + route).
2026-06-23 18:52:22 +02:00
johanleroy 06a400acc7 ci(vscode): réutiliser NPM_TOKEN pour l'asset de release du VSIX
CI / Build & test (Node 22) (push) Successful in 10m1s
CI / Build & test (Node 24) (push) Successful in 9m53s
Release / Publish to Gitea npm registry (push) Failing after 5m5s
VSCode Release / Package VSIX (push) Successful in 9m39s
CI / Pack & boot smoke (Node 22) (push) Successful in 9m54s
Le token Gitea NPM_TOKEN (déjà utilisé pour publier le daemon) a les droits repository
suffisants pour l'API release → pas de secret RELEASE_TOKEN dédié à configurer.
2026-06-23 17:48:45 +02:00
368 changed files with 31390 additions and 4176 deletions
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
# Attache des fichiers à une release Gitea, de façon idempotente (re-run friendly).
#
# Usage : attach-release-assets.sh <tag> <release-name> <fichier...>
# Env : RELEASE_TOKEN (token Gitea avec write:repository), GITHUB_SERVER_URL, GITHUB_REPOSITORY.
#
# Partagé par tous les jobs de release desktop et par le VSIX : la logique était dupliquée, et toute
# correction devait être faite trois fois.
set -uo pipefail
tag="${1:?tag manquant}"
release_name="${2:?nom de release manquant}"
shift 2
# Token ABSENT : cas légitime (fork, run sans secret) → on sort proprement.
# Token PRÉSENT mais refusé par l'API : anomalie, on doit ÉCHOUER. Sinon le job reste vert alors
# qu'aucun asset n'est attaché et qu'aucune release n'est créée, ce qui s'est produit avec un token
# expiré : trois workflows « réussis » et zéro fichier publié.
if [ -z "${RELEASE_TOKEN:-}" ]; then
echo "::notice::RELEASE_TOKEN absent, aucun asset attaché (les artefacts du run restent disponibles)."
exit 0
fi
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
auth="Authorization: token ${RELEASE_TOKEN}"
body=$(mktemp)
trap 'rm -f "$body"' EXIT
# Lecture d'un champ JSON TOLÉRANTE : une réponse vide ou non-JSON (401, 403, 404) doit donner une
# chaîne vide, pas une pile d'appels Node. Sans ça, deux `SyntaxError: Unexpected end of JSON input`
# s'affichaient avant le vrai message d'erreur et noyaient le diagnostic.
json_field() {
node -e "let s='';process.stdin.on('data',(d)=>{s+=d}).on('end',()=>{try{const o=JSON.parse(s);const v=o?.[process.argv[1]];process.stdout.write(v==null?'':String(v))}catch{process.stdout.write('')}})" "$1"
}
# `curl` silencieux qui écrit le corps dans $body et renvoie le code HTTP sur stdout.
http_call() {
curl -sS -o "$body" -w '%{http_code}' "$@"
}
# --- résolution de la release (existante, sinon création) -------------------------------------
code=$(http_call -H "$auth" "${api}/releases/tags/${tag}")
release_id=$(json_field id < "$body")
if [ -z "$release_id" ]; then
# 401/403 sur une simple lecture : inutile de tenter la création, le token est en cause.
case "$code" in
401)
echo "::error::le token de release est refusé (HTTP 401) : il est invalide, révoqué ou expiré."
echo "::error::régénérer un token Gitea et mettre à jour le secret NPM_TOKEN du dépôt."
exit 1
;;
403)
echo "::error::le token de release manque de droits (HTTP 403) sur ${GITHUB_REPOSITORY}."
echo "::error::portées attendues : write:repository (releases et assets) et write:package (publication npm)."
exit 1
;;
esac
create_code=$(http_call -X POST -H "$auth" -H 'Content-Type: application/json' \
-d "{\"tag_name\":\"${tag}\",\"name\":\"${release_name}\"}" "${api}/releases")
release_id=$(json_field id < "$body")
if [ -z "$release_id" ]; then
echo "::error::impossible de créer la release ${tag} (HTTP ${create_code})."
echo "::error::réponse de l'API : $(head -c 300 "$body")"
exit 1
fi
echo "release ${tag} créée (id ${release_id})."
else
echo "release ${tag} trouvée (id ${release_id})."
fi
# --- attache des fichiers ----------------------------------------------------------------------
failed=0
for f in "$@"; do
[ -f "$f" ] || continue
name=$(basename "$f")
# L'API Gitea refuse un asset de même nom : on supprime l'ancien pour que le dernier build gagne.
http_call -H "$auth" "${api}/releases/${release_id}/assets" > /dev/null
existing=$(node -e "let s='';process.stdin.on('data',(d)=>{s+=d}).on('end',()=>{try{const a=JSON.parse(s);const m=Array.isArray(a)?a.find((x)=>x.name===process.argv[1]):null;process.stdout.write(m?String(m.id):'')}catch{process.stdout.write('')}})" "$name" < "$body")
if [ -n "$existing" ]; then
echo "remplacement de $name (asset $existing)"
http_call -X DELETE -H "$auth" "${api}/releases/${release_id}/assets/${existing}" > /dev/null
fi
upload_code=$(http_call -X POST -H "$auth" -F "attachment=@${f}" "${api}/releases/${release_id}/assets?name=${name}")
if [ "$upload_code" -ge 200 ] && [ "$upload_code" -lt 300 ]; then
echo "attaché : $name"
else
echo "::error::échec de l'upload de ${name} (HTTP ${upload_code}) : $(head -c 200 "$body")"
failed=1
fi
done
if [ "$failed" != "0" ]; then
echo "::error::au moins un asset n'a pas pu être attaché à ${tag}."
exit 1
fi
echo "Assets attachés à la release ${tag}."
+36 -5
View File
@@ -29,6 +29,17 @@ jobs:
- run: npm run build
- run: npm run build:site
- run: npx vitest run
# packages/desktop est HORS des workspaces (CI daemon allégée) : sans cette étape, son code
# n'était JAMAIS typechecké avant un tag de release. Une seule version de Node suffit, et
# ELECTRON_SKIP_BINARY_DOWNLOAD évite de télécharger ~100 Mo de binaire Electron dont un
# typecheck n'a aucun besoin (c'est ce qui rendait le job très long).
- name: Typecheck desktop shell
if: matrix.node == '22'
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
run: |
npm --prefix packages/desktop ci
npm run typecheck:desktop
pack-smoke:
name: Pack & boot smoke (Node 22)
@@ -43,7 +54,7 @@ jobs:
- run: npm ci
- run: npm run build
# @arboretum/shared (paquet workspace NON publié) est INLINÉ dans dist/_shared au prepack
# (scripts/inline-shared.mjs) : le tarball est 100 % autonome — aucun node_modules embarqué,
# (scripts/inline-shared.mjs) : le tarball est 100 % autonome : aucun node_modules embarqué,
# aucune bundleDependency, aucun symlink. On packe en mode workspace (-w), EXACTEMENT comme
# le fait « npm publish » dans release.yml, puis on l'installe seul comme un vrai consommateur.
- name: Pack tarball
@@ -56,12 +67,14 @@ jobs:
tgz=$(ls /tmp/tarballs/*.tgz)
rm -rf /tmp/inspect && mkdir -p /tmp/inspect && tar -xzf "$tgz" -C /tmp/inspect
test -f /tmp/inspect/package/dist/_shared/index.js \
|| { echo "ERREUR: dist/_shared/index.js absent de $tgz — inline-shared n'a pas tourné ?"; exit 1; }
if grep -rq '@arboretum/shared' /tmp/inspect/package/dist; then
|| { echo "ERREUR: dist/_shared/index.js absent de $tgz : inline-shared n'a pas tourné ?"; exit 1; }
# On cherche les vraies formes d'IMPORT, pas la simple chaîne : un commentaire de code qui
# mentionne le paquet (pour dire où vit la règle partagée) est légitime et ne casse rien.
if grep -rqE "(from|require\(|import\()[[:space:]]*['\"]@arboretum/shared" /tmp/inspect/package/dist; then
echo "ERREUR: import bare '@arboretum/shared' encore présent dans le JS publié"
grep -rn '@arboretum/shared' /tmp/inspect/package/dist; exit 1
grep -rnE "(from|require\(|import\()[[:space:]]*['\"]@arboretum/shared" /tmp/inspect/package/dist; exit 1
fi
echo "OK: paquet autonome — shared inliné dans dist/_shared, aucun import externe"
echo "OK: paquet autonome : shared inliné dans dist/_shared, aucun import externe"
- name: Install tarball in an empty project
run: |
mkdir /tmp/smoke
@@ -82,3 +95,21 @@ jobs:
echo "GET /api/v1/sessions -> HTTP $code"
kill "$server_pid" 2>/dev/null || true
test "$code" = "401"
lint-dashes:
# Interdit tout tiret cadratin (U+2014) ou demi-cadratin (U+2013) dans les fichiers suivis.
# Utiliser a la place : point median, deux-points, virgule, ou tiret simple pour les plages.
# `-I` ignore les fichiers BINAIRES : une icone PNG/ICO peut contenir ces octets par hasard, ce
# qui faisait echouer la garde sans aucun texte fautif. Exclusion restante : les captures brutes
# du terminal (fichiers texte, fidelite des fixtures de dialogue).
name: No em/en dashes
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Fail on U+2014 / U+2013 (outside allow-list)
run: |
if git grep -nPI '[\x{2014}\x{2013}]' -- . \
':(exclude)packages/server/test/fixtures/dialogs/*.raw'; then
echo "::error::Tiret cadratin/demi-cadratin trouve. Utiliser point median, deux-points, virgule ou tiret simple (plages)."
exit 1
fi
+139
View File
@@ -0,0 +1,139 @@
# Packaging de l'app de bureau Electron, déclenché par un tag desktop-vX.Y.Z (séparé de la release du
# daemon qui écoute v*, et du VSIX qui écoute vscode-v*).
#
# Linux (AppImage + deb) : toujours automatisé.
# Windows (NSIS + portable) : job RETIRÉ tant qu'aucun runner `windows-latest` n'est enregistré sur le
# forge. Un job conditionné par une variable de dépôt ne suffisait pas : la release entière tombait
# en erreur. Le repli est un build manuel attaché à la release. Pour le rétablir : enregistrer un
# runner (docs/CI_RUNNERS.md) puis restaurer le job depuis l'historique git (tag desktop-v0.2.3).
# Le cross-build depuis Linux est IMPOSSIBLE : node-pty ne copie conpty.dll / OpenConsole.exe que si
# l'hôte de build est Windows, et son tarball ne contient que les prebuilds linux.
# macOS (dmg + zip) : non automatisé (aucun runner) ; build manuel documenté dans le README desktop.
#
# `workflow_dispatch` permet de tester les jobs sans créer de tag (le garde-fou tag == version est
# alors ignoré, puisqu'il n'y a pas de tag à comparer).
name: Desktop Release
on:
push:
tags: ['desktop-v*']
workflow_dispatch:
permissions:
contents: write
env:
NODE_VERSION: '22.21.1'
jobs:
linux:
name: Build Linux (AppImage + deb)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
cache: npm
# Garde-fou : le tag (sans "desktop-v") doit correspondre à la version du paquet desktop.
- name: Verify tag matches desktop version
if: github.event_name == 'push'
run: |
pkg=$(node -p "require('./packages/desktop/package.json').version")
tag="${GITHUB_REF_NAME#desktop-v}"
if [ "$pkg" != "$tag" ]; then
echo "ERREUR: tag '$tag' != version desktop '$pkg'"
exit 1
fi
echo "OK: tag $tag == version $pkg"
# Deps racine (build/pack du daemon) puis deps du paquet desktop (hors workspaces racine).
- run: npm ci
- name: Install desktop deps
run: cd packages/desktop && npm ci
# Build complet : shell + daemon empaqueté + Node standalone + AppImage/deb (electron-builder).
- name: Build installers
run: cd packages/desktop && npm run dist:linux
- name: Compute checksums
run: |
cd packages/desktop/release
sha256sum *.AppImage *.deb > SHA256SUMS-linux.txt
cat SHA256SUMS-linux.txt
# Artefacts du run : canal fiable, indépendant de l'API release.
- uses: actions/upload-artifact@v3
with:
name: desktop-linux
path: |
packages/desktop/release/*.AppImage
packages/desktop/release/*.deb
packages/desktop/release/*.blockmap
packages/desktop/release/latest-linux.yml
packages/desktop/release/SHA256SUMS-linux.txt
# Attache les installeurs (+ latest-linux.yml pour l'auto-update) à la release du tag. Réutilise
# NPM_TOKEN (même token Gitea) : il doit porter write:repository en plus de write:package, sinon
# l'API release renvoie 403. Pas de continue-on-error : les artefacts du run sont déjà uploadés à
# l'étape précédente, donc un échec ici ne perd rien et doit être VU (avec un token expiré, la
# release ressortait verte et vide).
- name: Attach installers to the tag release
if: github.event_name == 'push'
env:
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
version=$(node -p "require('./packages/desktop/package.json').version")
bash .gitea/scripts/attach-release-assets.sh "${GITHUB_REF_NAME}" "Arboretum Desktop ${version}" \
packages/desktop/release/*.AppImage \
packages/desktop/release/*.deb \
packages/desktop/release/*.blockmap \
packages/desktop/release/latest-linux.yml \
packages/desktop/release/SHA256SUMS-linux.txt
# Le job Windows (NSIS + portable) est RETIRÉ pour le moment : aucun runner Windows n'est
# enregistré sur ce Gitea, et `runs-on: windows-latest` fait échouer la release entière au lieu
# d'être simplement ignoré. Le job complet reste dans l'historique git (dernier état : tag
# desktop-v0.2.3) et la procédure d'enregistrement d'un runner est dans docs/CI_RUNNERS.md : le
# rétablir revient à restaurer ce job, puis à réactiver le téléchargement de son artefact et ses
# assets dans le canal flottant ci-dessous.
# Canal d'auto-update : electron-updater interroge une URL FIXE
# (.../releases/download/desktop-latest, cf. electron-builder.yml). Ce tag flottant doit donc exister
# et porter les latest*.yml de la dernière version, sinon l'updater reçoit un 404 · c'était le cas
# jusqu'en 0.1.3, où l'auto-update annoncé ne fonctionnait pour personne.
latest-channel:
name: Publish floating desktop-latest release
if: github.event_name == 'push'
runs-on: ubuntu-latest
needs: [linux]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ env.NODE_VERSION }}
- uses: actions/download-artifact@v3
with:
name: desktop-linux
path: dl
# On repart d'une release flottante VIERGE : sinon les assets de la version précédente y
# restent (mêmes noms de fichiers uniquement remplacés, un ancien numéro de version subsisterait).
# La recréation est faite par le script suivant, via l'API (Gitea crée le tag au besoin).
- name: Reset the floating release
env:
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "$RELEASE_TOKEN" ]; then
echo "::notice::NPM_TOKEN absent, canal desktop-latest non publié."
exit 0
fi
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
auth="Authorization: token ${RELEASE_TOKEN}"
old=$(curl -fsSL -H "$auth" "${api}/releases/tags/desktop-latest" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''" || true)
if [ -n "$old" ]; then
echo "suppression de l'ancienne release flottante (id ${old})"
curl -fsSL -X DELETE -H "$auth" "${api}/releases/${old}" || true
fi
curl -fsSL -X DELETE -H "$auth" "${api}/tags/desktop-latest" || true
- name: Attach installers to the floating release
env:
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
version=$(node -p "require('./packages/desktop/package.json').version")
bash .gitea/scripts/attach-release-assets.sh desktop-latest "Arboretum Desktop (latest, ${version})" \
dl/*.AppImage dl/*.deb dl/*.blockmap dl/latest-linux.yml dl/SHA256SUMS-*.txt
+6 -4
View File
@@ -4,7 +4,9 @@ name: Release
on:
push:
tags: ['v*']
# `v[0-9]*` (et non `v*`) : sinon ce workflow capture aussi les tags `vscode-v*` de l'extension
# : il stripperait alors `v` (→ `scode-v0.1.0`) et échouerait contre la version du daemon.
tags: ['v[0-9]*']
permissions:
contents: read
@@ -37,12 +39,12 @@ jobs:
echo "OK: tag $tag == version $pkg"
# Publication idempotente : le signal faisant autorité d'une version déjà présente est le
# 409 « already exists » renvoyé par npm publish lui-même (npm view est non fiable contre le
# registre npm de Gitea — faux négatif masqué par >/dev/null). On tente toujours le publish ;
# registre npm de Gitea : faux négatif masqué par >/dev/null). On tente toujours le publish ;
# un 409 = succès idempotent, tout autre échec reste fatal. Le shell Actions tourne en
# `bash -eo pipefail` : on isole l'échec attendu dans la condition d'un `if` pour ne pas
# déclencher `set -e`. Le secret du registre est mappé sur NODE_AUTH_TOKEN lu par le .npmrc
# de setup-node.
- name: Publish (idempotent — tolère un 409 « already exists »)
- name: Publish (idempotent, tolère un 409 « already exists »)
run: |
if out="$(npm publish -w @johanleroy/git-arboretum 2>&1)"; then
printf '%s\n' "$out"
@@ -51,7 +53,7 @@ jobs:
code=$?
printf '%s\n' "$out"
if printf '%s' "$out" | grep -qiE 'E409|409 Conflict|already exists'; then
echo "::notice::Version déjà présente sur le registre (409) — publication idempotente, étape ignorée."
echo "::notice::Version déjà présente sur le registre (409) : publication idempotente, étape ignorée."
else
echo "::error::Échec de la publication (code $code)."
exit "$code"
+8 -22
View File
@@ -45,29 +45,15 @@ jobs:
with:
name: vsix
path: packages/vscode/*.vsix
# Best-effort : attache le VSIX à la release Gitea du tag (crée la release si absente).
# Nécessite un secret RELEASE_TOKEN (token Gitea avec write:repository) ; sans lui, l'étape est
# ignorée sans faire échouer le job (continue-on-error).
# Attache le VSIX à la release Gitea du tag (créée si absente), via le script partagé avec la
# release desktop : la logique était dupliquée, avec le même angle mort. Réutilise le secret
# NPM_TOKEN (même token Gitea que la publication du daemon), qui doit porter write:repository en
# plus de write:package. Sans token du tout, le script sort proprement ; avec un token REFUSÉ, il
# échoue, pour que l'anomalie soit visible (le VSIX reste dans les artefacts du run).
- name: Attach VSIX to Gitea release
continue-on-error: true
env:
RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
if [ -z "$RELEASE_TOKEN" ]; then
echo "::notice::RELEASE_TOKEN absent — VSIX disponible en artefact uniquement."
exit 0
fi
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
auth="Authorization: token ${RELEASE_TOKEN}"
version=$(node -p "require('./packages/vscode/package.json').version")
vsix="packages/vscode/git-arboretum-${version}.vsix"
# id de release du tag, sinon création
rid=$(curl -fsSL -H "$auth" "${api}/releases/tags/${GITHUB_REF_NAME}" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''" || true)
if [ -z "$rid" ]; then
rid=$(curl -fsSL -X POST -H "$auth" -H 'Content-Type: application/json' \
-d "{\"tag_name\":\"${GITHUB_REF_NAME}\",\"name\":\"Arboretum VSCode ${version}\"}" \
"${api}/releases" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''")
fi
curl -fsSL -X POST -H "$auth" -F "attachment=@${vsix}" \
"${api}/releases/${rid}/assets?name=git-arboretum-${version}.vsix"
echo "VSIX attaché à la release ${GITHUB_REF_NAME}."
bash .gitea/scripts/attach-release-assets.sh "${GITHUB_REF_NAME}" "Arboretum VSCode ${version}" \
"packages/vscode/git-arboretum-${version}.vsix"
+4 -1
View File
@@ -26,7 +26,7 @@ coverage/
.vscode/
.DS_Store
# Claude Code / agent tooling (local only — do not commit)
# Claude Code / agent tooling (local only, do not commit)
CLAUDE.md
.claude/
.remember/
@@ -34,3 +34,6 @@ CLAUDE.md
# Spike scratch output
spikes/**/tmp/
spikes/**/captures/
# captures des scripts de verification visuelle (verify-ui.mjs)
.ui-shots/
+195 -41
View File
@@ -3,14 +3,32 @@
</p>
<p align="center">
Un dashboard web auto-hébergé pour vos worktrees git et les sessions Claude Code qui tournent dessus — depuis n'importe quel appareil.
Un IDE IA multi-projet auto-hébergé pour vos worktrees git et les sessions Claude Code qui tournent dessus : une app de bureau native et une interface web, depuis n'importe quel appareil.
</p>
<p align="center">
<a href="README.md">English</a> · <strong>Français</strong>
</p>
**Statut : MVP.** Le dashboard worktree-first, la découverte et la reprise de sessions, le cycle de vie des worktrees multi-repo, le démarrage de sessions sur votre branche principale ou n'importe quel worktree, les états de session en temps réel, le terminal web, la supervision mobile (PWA installable, Web Push quand une session vous attend, répondre à une demande sans ouvrir de terminal) et les groupes de travail (piloter plusieurs repos liés depuis une seule session Claude) sont implémentés et testés.
La découverte et la reprise de sessions, le cycle de vie des worktrees multi-repo, le démarrage de sessions sur votre branche principale ou n'importe quel worktree, les états de session en temps réel, le terminal web, la supervision mobile (PWA installable, Web Push quand une session vous attend, répondre à une demande sans ouvrir de terminal) et les groupes de travail (piloter plusieurs repos liés depuis une seule session Claude) sont tous implémentés et testés.
La dernière étape transforme Arboretum en véritable **IDE IA multi-projet** : un espace de travail unique (route `/ide`, la vue par défaut sur desktop) qui réunit **tous** vos projets ouverts à la fois, fini l'IDE par projet. Un arbre unique à gauche (projet, puis checkout principal et worktrees, puis session Claude), un éditeur Monaco à onglets au centre (plusieurs fichiers de projets différents côte à côte, diffs inline), les terminaux Claude en dock bas, et des panneaux Git / Sessions / Groupes via une barre d'activité. Il est fourni à la fois en **app de bureau native** (Linux, Windows, macOS) et en interface web, adossé à un watcher de système de fichiers en temps réel, au staging sélectif / discard / amend / fetch / pull, à l'archivage automatique des sessions, à la synchronisation des réglages en temps réel, et à des services git distants chiffrés (GitHub / GitLab / Gitea) avec clone HTTPS.
---
## Captures d'écran
<p align="center">
<img src="brand/screenshot-ide-dark.png" alt="Arboretum, l'IDE IA multi-projet (thème sombre)" width="900">
</p>
<p align="center">
<em>Un espace de travail pour tous les projets : arbre unifié, éditeur Monaco à onglets avec diffs inline, terminaux Claude en dock. Thèmes sombre et clair.</em>
</p>
<p align="center">
<img src="brand/screenshot-ide-light.png" alt="Arboretum, l'IDE IA multi-projet (thème clair)" width="900">
</p>
---
@@ -24,40 +42,44 @@ Travailler avec des agents de code IA a changé notre usage de git : une feature
## Ce que fait Arboretum
Un unique daemon Node.js que vous lancez sur votre machine de dev (`npx @johanleroy/git-arboretum`), servant une interface web utilisable depuis votre ordinateur, téléphone ou tablette :
Un unique daemon Node.js que vous lancez sur votre machine de dev (en app de bureau native, ou via `npx @johanleroy/git-arboretum`), servant une interface utilisable depuis votre ordinateur, téléphone ou tablette :
- **Dashboard worktree-first, multi-repo** — chaque worktree de chaque repo enregistré, avec son état git (branche, ahead/behind, fichiers modifiés) *et* l'état de sa session Claude Code (busy / en attente d'entrée / idle / reprenable).
- **Cycle de vie complet des worktrees** — créer (avec des hooks post-création par repo : `npm ci`, copie de `.env`…), adopter des worktrees créés à la main, supprimer avec garde-fous, élaguer les orphelins.
- **Découverte & reprise de sessions** — les sessions lancées dans votre propre terminal apparaissent automatiquement ; reprenez les sessions mortes, observez ou forkez les vivantes. Ne corrompt jamais une session vivante. Masquez les anciennes qui encombrent la liste (un clic efface tout l'historique externe ; elles restent reprenables).
- **Terminal web** — terminal xterm.js complet vers chaque session managée, qui survit aux déconnexions du navigateur ; vraiment plein écran, avec l'invite ancrée en bas et tout l'historique défilable au-dessus.
- **Supervision depuis votre téléphone** — PWA installable avec notifications push quand une session vous attend ; répondez à une demande (ses options, ou refusez) sans ouvrir de terminal.
- **Groupes de travail** — regroupez des repos liés (ex. une API, son frontend web et sa doc) dans un groupe nommé, puis lancez **une seule session Claude qui les couvre tous à la fois** (via le flag `--add-dir` du CLI) : une conversation unique avec un contexte partagé travaillant à travers chaque repo, plus une vue unifiée de tous leurs worktrees et une grille multi-terminaux côte à côte. Une session de groupe peut d'abord créer le même worktree de branche dans chaque repo, ou tourner directement sur les checkouts principaux.
- **Extension VS Code** — une extension native (pas un webview) qui amène l'arbre en direct, les terminaux de session natifs, les alertes d'attente et les actions git directement dans votre éditeur. Voir [Extension VS Code](#extension-vs-code).
- **Dashboard worktree multi-repo** : chaque worktree de chaque repo enregistré, avec son état git (branche, ahead/behind, fichiers modifiés) *et* l'état de sa session Claude Code (busy / en attente d'entrée / idle / reprenable).
- **Cycle de vie complet des worktrees** : créer (avec des hooks post-création par repo : `npm ci`, copie de `.env`…), adopter des worktrees créés à la main, supprimer avec garde-fous, élaguer les orphelins.
- **Découverte & reprise de sessions** : les sessions lancées dans votre propre terminal apparaissent automatiquement ; reprenez les sessions mortes, observez ou forkez les vivantes. Ne corrompt jamais une session vivante. Masquez les anciennes qui encombrent la liste (un clic efface tout l'historique externe ; elles restent reprenables).
- **Terminal web** : terminal xterm.js complet vers chaque session managée, qui survit aux déconnexions du navigateur ; vraiment plein écran, avec l'invite ancrée en bas et tout l'historique défilable au-dessus.
- **IDE multi-projet** : un espace de travail pour tous les projets ouverts à la fois (pas de fenêtre par projet). Un arbre unique (projet, worktrees, sessions Claude), un éditeur Monaco à onglets (plusieurs fichiers de projets différents côte à côte, avec diffs inline par fichier), un dock bas de terminaux de session, et des panneaux Git / Sessions / Groupes. Éditez les fichiers, indexez les changements sélectivement, committez (ou amendez), fetch/pull et push, au même endroit. Un watcher de système de fichiers en temps réel garde la vue à jour au fil des éditions de l'agent. Disponible en app de bureau native et dans le navigateur.
- **Démarrez un projet en un clic** : beaucoup de projets exigent plusieurs commandes longue durée pour démarrer (serveur de dev, API, base de données). Définissez-les une fois par projet (libellés, commandes shell, sous-dossier optionnel), auto-détectées depuis les scripts `package.json`, un `Procfile` ou `docker-compose`, puis lancez-les toutes d'un coup, un terminal attaché par commande. Chacune tourne dans votre shell de login (donc `npm`, `docker`, nvm/asdf sont dans le `PATH`) et reste vivante après la fin de la commande, pour que les échecs restent à l'écran ; arrêtez tout le lot en une action.
- **Supervision depuis votre téléphone** : PWA installable avec notifications push quand une session vous attend ; répondez à une demande (ses options, ou refusez) sans ouvrir de terminal.
- **Groupes de travail** : regroupez des repos liés (ex. une API, son frontend web et sa doc) dans un groupe nommé, puis lancez **une seule session Claude qui les couvre tous à la fois** (via le flag `--add-dir` du CLI) : une conversation unique avec un contexte partagé travaillant à travers chaque repo, plus une vue unifiée de tous leurs worktrees et une grille multi-terminaux côte à côte. Une session de groupe peut d'abord créer le même worktree de branche dans chaque repo, ou tourner directement sur les checkouts principaux.
- **Services git distants** : connectez vos comptes GitHub, GitLab ou Gitea (personal access token ou app password), stockés **chiffrés au repos** (AES-256-GCM) ; parcourez vos dépôts distants et clonez-les en HTTPS avec progression en direct, directement depuis le dashboard.
- **Archivage automatique** : les sessions terminées sont archivées automatiquement après une fenêtre de rétention configurable (30 jours par défaut), pour que la liste reste centrée sur ce qui est vivant tandis que l'historique reste à un clic.
- **Extension VS Code** : une extension native (pas un webview) qui amène l'arbre en direct, les terminaux de session natifs, les alertes d'attente et les actions git directement dans votre éditeur. Voir [Extension VS Code](#extension-vs-code).
---
## Prérequis
- **Node.js ≥ 22.16** — requis, pas seulement recommandé. Arboretum persiste son état avec `node:sqlite` (`DatabaseSync`), natif et stable seulement à partir de cette version. (`.nvmrc` fixe `22`.)
- **Le CLI `claude`** sur votre `PATH` si vous voulez qu'Arboretum lance et gère des sessions Claude Code. Arboretum enveloppe le CLI interactif que vous utilisez déjà — installez-le et authentifiez-le comme d'habitude.
- **Node.js ≥ 22.16** pour l'usage `npx` / depuis les sources : requis, pas seulement recommandé. Arboretum persiste son état avec `node:sqlite` (`DatabaseSync`), natif et stable seulement à partir de cette version. (`.nvmrc` fixe `22`.) L'**app de bureau embarque son propre runtime Node**, donc ses utilisateurs finaux n'ont pas besoin d'installer Node.
- **Le CLI `claude`** sur votre `PATH` si vous voulez qu'Arboretum lance et gère des sessions Claude Code. Arboretum enveloppe le CLI interactif que vous utilisez déjà, installez-le et authentifiez-le comme d'habitude.
- Un **dépôt git** (ou plusieurs) que vous voulez gérer.
## Démarrage rapide
Deux chemins, selon ce que vous voulez :
- **Juste l'utiliser (la plupart des gens).** Arboretum est un paquet npm publié — vous **n'avez pas besoin de cloner ce dépôt**. Pointez npm vers le registre et lancez-le (ci-dessous). À faire sur la machine où tournent vos sessions Claude Code.
- **Juste l'utiliser (la plupart des gens).** Arboretum est un paquet npm publié : vous **n'avez pas besoin de cloner ce dépôt**. Pointez npm vers le registre et lancez-le (ci-dessous). À faire sur la machine où tournent vos sessions Claude Code.
- **Lancer depuis les sources.** Ne clonez le dépôt que pour développer Arboretum ou lancer une version non publiée.
### Le lancer (recommandé)
Arboretum est publié sur un registre npm Gitea auto-hébergé. Pointez le scope `@johanleroy` dessus une fois par machine — ajoutez à `~/.npmrc` :
Arboretum est publié sur un registre npm Gitea auto-hébergé. Pointez le scope `@johanleroy` dessus une fois par machine, ajoutez à `~/.npmrc` :
```
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
```
Aucun token nécessaire — le paquet est en lecture publique. Puis lancez-le depuis n'importe où :
Aucun token nécessaire, le paquet est en lecture publique. Puis lancez-le depuis n'importe où :
```bash
npx @johanleroy/git-arboretum
@@ -67,7 +89,7 @@ Au premier démarrage, Arboretum affiche un **token d'accès** unique et l'URL
```
┌──────────────────────────────────────────────────────────────────┐
│ First start — your access token (shown once, store it safely): │
│ First start · your access token (shown once, store it safely): │
└──────────────────────────────────────────────────────────────────┘
<votre-token-ici>
@@ -75,9 +97,9 @@ Au premier démarrage, Arboretum affiche un **token d'accès** unique et l'URL
Login at: http://127.0.0.1:7317/
```
Ouvrez l'URL, collez le token pour vous connecter, et c'est parti. Le token est stocké **hashé** — il n'est affiché qu'une seule fois, alors gardez-le en lieu sûr (un gestionnaire de mots de passe). Vous pourrez gérer vos tokens plus tard depuis les **Réglages**.
Ouvrez l'URL, collez le token pour vous connecter, et c'est parti. Le token est stocké **hashé** : il n'est affiché qu'une seule fois, alors gardez-le en lieu sûr (un gestionnaire de mots de passe). Vous pourrez gérer vos tokens plus tard depuis les **Réglages**.
`npx` télécharge et lance la dernière version publiée à chaque fois. Pour l'installer une bonne fois — et obtenir la commande `arboretum` sur votre `PATH`, dont se sert le [service d'arrière-plan](#le-faire-tourner-en-service-darrière-plan) —, installez-le plutôt globalement :
`npx` télécharge et lance la dernière version publiée à chaque fois. Pour l'installer une bonne fois (et obtenir la commande `arboretum` sur votre `PATH`, dont se sert le [service d'arrière-plan](#le-faire-tourner-en-service-darrière-plan)), installez-le plutôt globalement :
```bash
npm i -g @johanleroy/git-arboretum
@@ -86,7 +108,7 @@ arboretum # identique à la commande npx, depuis le binaire installé
### Lancer depuis les sources
Nécessaire uniquement pour **développer** Arboretum ou lancer une version non publiée — pas pour simplement l'utiliser. Clonez le dépôt, installez les dépendances, buildez, puis démarrez le daemon :
Nécessaire uniquement pour **développer** Arboretum ou lancer une version non publiée, pas pour simplement l'utiliser. Clonez le dépôt, installez les dépendances, buildez, puis démarrez le daemon :
```bash
git clone https://git.lidge.fr/johanleroy/arboretum.git
@@ -97,35 +119,72 @@ npm run build # build shared → server → web (l'ordre compte)
node packages/server/dist/index.js
```
## Application de bureau
Vous préférez une app native au daemon-dans-un-terminal ? Arboretum fournit une **app de bureau Electron** (`packages/desktop`) pour **Linux, Windows et macOS**. Elle lance le daemon en process enfant et ouvre son interface dans une fenêtre native, déjà connectée (aucun écran de login), et elle **embarque son propre runtime Node** : pas besoin d'avoir Node installé pour l'utiliser.
- **Installer.** Les installeurs sont publiés sur la [page des releases](https://git.lidge.fr/johanleroy/arboretum/releases) dès qu'une release desktop est taguée : un AppImage et un `.deb` sous Linux, un installeur NSIS (et un build portable) sous Windows, un `.dmg` sous macOS. Vous préférez les builder vous-même ? Voir [`packages/desktop/README.md`](packages/desktop/README.md).
- **Premier lancement.** L'app n'est pas encore signée : sous **Windows**, SmartScreen affiche « éditeur inconnu », choisissez « Informations complémentaires » puis « Exécuter quand même » ; sous **macOS**, Gatekeeper la bloque, clic droit sur l'app puis « Ouvrir » (ou lancez `xattr -dr com.apple.quarantine /Applications/Arboretum.app`).
- **Vit dans le tray.** Fermer la fenêtre garde Arboretum actif dans la barre système ; quittez depuis le menu du tray, où vous pouvez aussi activer le lancement au login. L'auto-update est intégré sous Windows et Linux (les mises à jour macOS restent manuelles tant que l'app n'est pas signée).
L'app de bureau n'est qu'une coquille autour du même daemon et de la même interface web : tout ce qui suit (espace de travail, git, sessions) fonctionne à l'identique.
### Installer selon la plateforme
| Plateforme | Artefact | Notes |
|---|---|---|
| **Debian / Ubuntu** | `Arboretum-<version>-amd64.deb` | `sudo apt install ./Arboretum-*.deb`. Installe la dépendance `git`. À préférer à l'AppImage sous Debian : il pose l'entrée de lanceur et ses icônes. |
| **Autres Linux** | `Arboretum-<version>-x86_64.AppImage` | `chmod +x` puis lancer. Aucune entrée de menu sans un outil d'intégration comme `appimaged`. |
| **Windows** | `Arboretum-<version>-x64.exe` (NSIS) ou le build portable | Non signé : SmartScreen affiche « éditeur inconnu », choisissez **Informations complémentaires → Exécuter quand même**. Nécessite Windows 10 1809+ (ConPTY). |
| **macOS** | `Arboretum-<version>.dmg` | Ni signé ni notarisé : clic droit sur l'app → **Ouvrir**, ou `xattr -dr com.apple.quarantine /Applications/Arboretum.app`. Buildé à la demande, voir `packages/desktop/README.md`. |
Sous Windows aussi, le CLI `claude` doit être dans votre PATH ; si l'app ne le trouve pas, renseignez son
chemin dans **Réglages → CLI Claude**. Le lancement du daemon à l'ouverture de session y est également
géré (`arboretum install` enregistre une tâche planifiée).
## Utiliser Arboretum
1. **Ajoutez un dépôt.** Depuis le dashboard, enregistrez un repo git local par son chemin. Configurez éventuellement des **hooks post-création** (ex. `npm ci`, `cp ../.env .env`) exécutés automatiquement à chaque création d'un nouveau worktree pour ce repo.
2. **Créez ou adoptez des worktrees.** Créez un nouveau worktree + branche en un clic (les hooks s'exécutent pour vous), ou adoptez un worktree créé à la main. Chaque worktree affiche sa branche, son ahead/behind et son nombre de fichiers modifiés.
3. **Démarrez ou reprenez une session.** Lancez une session Claude Code sur la branche principale du repo ou n'importe quel worktree, ou reprenez-en une démarrée dans votre terminal — Arboretum découvre les sessions existantes automatiquement et les reprend toujours dans leur répertoire de travail d'origine.
3. **Démarrez ou reprenez une session.** Lancez une session Claude Code sur la branche principale du repo ou n'importe quel worktree, ou reprenez-en une démarrée dans votre terminal : Arboretum découvre les sessions existantes automatiquement et les reprend toujours dans leur répertoire de travail d'origine.
4. **Suivez les états en direct.** Chaque session indique si elle est *busy*, *en attente de votre entrée* ou *idle*. Ouvrez le **terminal web** pour interagir directement ; il survit aux déconnexions du navigateur (fermer l'onglet ne tue pas la session).
5. **Supervisez depuis votre téléphone.** Installez la PWA, et quand une session bascule en *attente*, vous recevez une notification push. Répondez à la demande — choisissez l'une de ses options ou refusez-la — directement depuis le dashboard, sans terminal.
5. **Supervisez depuis votre téléphone.** Installez la PWA, et quand une session bascule en *attente*, vous recevez une notification push. Répondez à la demande (choisissez l'une de ses options ou refusez-la) directement depuis le dashboard, sans terminal.
## L'IDE, espace de travail & opérations git
Au-delà de la supervision, Arboretum est un véritable **IDE multi-projet** (route `/ide`, la vue par défaut sur desktop). Il réunit tous les projets ouverts à la fois, pour ne plus jongler avec une fenêtre d'IDE par projet :
- **Arbre de projets unifié.** Un arbre unique à gauche liste chaque projet enregistré, son checkout principal et ses worktrees, et la session Claude corrélée à chacun. Dépliez un worktree pour parcourir ses fichiers inline. Une barre d'activité bascule le panneau gauche entre Explorateur, Git, Sessions et Groupes.
- **Éditeur à onglets.** Ouvrez des fichiers dans un **éditeur Monaco** à onglets, plusieurs fichiers de **projets différents** côte à côte, coloration syntaxique, détection du langage, enregistrement avec détection de conflit. Chaque onglet bascule entre éditeur et **diff par fichier** inline (arbre de travail ou index, ajouts/suppressions colorés, diffs binaires et énormes refusés).
- **Dock de terminaux.** Les terminaux de session Claude vivent dans un dock bas, un onglet par session ; ouvrez-en plusieurs à la fois (à travers les projets), répondez à une demande en attente directement là. Les terminaux survivent aux changements d'onglet et aux déconnexions du navigateur.
- **Panneau Git.** Indexez ou désindexez des fichiers individuels, jetez des changements, écrivez un message et **committez** (tout ou seulement l'indexé), **amendez** le dernier commit (refusé une fois poussé), puis **fetch**, **pull** (fast-forward ou rebase) et **push**. Les compteurs indexés / non indexés / conflits détaillés et le dernier commit restent à jour via un **watcher de système de fichiers en temps réel** : la vue s'actualise dès qu'une session Claude touche un fichier.
- **Deep links & mobile.** `/workspace/:repoId/:wt` ouvre toujours un worktree précis directement dans l'IDE (utilisé par l'extension VS Code). Sur mobile, l'IDE dégrade en panneau unique, et le dashboard des worktrees et les vues de session restent la PWA de supervision installable.
- **Clair ou sombre, au choix.** Un langage visuel épuré et cohérent (le design system « Emerald » : Inter + JetBrains Mono, un accent emerald) avec une bascule de thème **clair / sombre / système** mémorisée d'une session à l'autre. L'éditeur Monaco, les terminaux et les diffs suivent tous le thème actif.
Comme toute action git dans Arboretum, ces opérations s'exécutent **en tant que vous** (le daemon tourne sous votre compte), cohérent avec le modèle de sécurité : un terminal web, c'est de l'exécution de code à distance par conception.
## Extension VS Code
Vous préférez rester dans votre éditeur ? Arboretum fournit une **extension VS Code native** (`packages/vscode`) — pas un webview. Elle se connecte au même daemon et l'expose avec les primitives natives de VS Code :
Vous préférez rester dans votre éditeur ? Arboretum fournit une **extension VS Code native** (`packages/vscode`), pas un webview. Elle se connecte au même daemon et l'expose avec les primitives natives de VS Code :
- Un arbre **Repositories** et **Groups** en direct (repos → worktrees → sessions) dans l'Activity Bar, mis à jour en temps réel via le WebSocket du daemon.
- **Terminaux natifs** : attachez-vous (ou observez) n'importe quelle session dans un vrai terminal VS Code — vous bénéficiez du rendu, du scrollback et du copier-coller de VS Code gratuitement.
- **Terminaux natifs** : attachez-vous (ou observez) n'importe quelle session dans un vrai terminal VS Code, vous bénéficiez du rendu, du scrollback et du copier-coller de VS Code gratuitement.
- Un compteur en **status bar** et des **notifications** natives quand une session attend, avec réponses Oui/Non sans ouvrir de terminal.
- Les mutations git (créer un worktree, commit, push, promouvoir) et la **conscience du workspace** — le worktree de votre dossier ouvert est mis en évidence, avec « démarrer une session / créer un worktree ici » en un clic.
- Les mutations git (créer un worktree, commit, push, promouvoir, **fetch / pull**) avec un **statut git détaillé** dans l'arbre (indexés / non indexés / conflits et dernier commit), et la **conscience du workspace** : le worktree de votre dossier ouvert est mis en évidence, avec « démarrer une session / créer un worktree ici » en un clic.
- **Ouvrir dans l'IDE web** : sautez de n'importe quel worktree directement vers sa vue `/workspace` complète dans le navigateur. L'extension reste un gestionnaire de worktrees visuel et léger ; l'édition lourde vit dans l'IDE web.
Elle est distribuée en **VSIX privé**. Buildez-la et packagez-la depuis le monorepo :
```bash
npm run build:vscode
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.1.0.vsix
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-<version>.vsix
```
Puis installez-la via **Extensions : Installer à partir d'un VSIX…** (ou `code --install-extension git-arboretum-0.1.0.vsix`), lancez **Arboretum: Sign In** et collez un token. Détails complets dans [`packages/vscode/README.md`](packages/vscode/README.md).
Puis installez-la via **Extensions : Installer à partir d'un VSIX…** (ou `code --install-extension git-arboretum-<version>.vsix`), lancez **Arboretum: Sign In** et collez un token. Détails complets dans [`packages/vscode/README.md`](packages/vscode/README.md).
## Accès distant depuis votre téléphone
Arboretum se bind sur `127.0.0.1` par défaut et **refuse** de se binder sur une adresse non-loopback sans dérogation explicite. La façon recommandée (et sûre) de l'atteindre depuis d'autres appareils est **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)** — HTTPS valide, identité tailnet, aucun port ouvert :
Arboretum se bind sur `127.0.0.1` par défaut et **refuse** de se binder sur une adresse non-loopback sans dérogation explicite. La façon recommandée (et sûre) de l'atteindre depuis d'autres appareils est **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)**, HTTPS valide, identité tailnet, aucun port ouvert :
```bash
# Expose le daemon local en HTTPS dans votre tailnet
@@ -142,16 +201,57 @@ Ouvrez `https://<machine>.<tailnet>.ts.net` depuis n'importe quel appareil de vo
> ⚠️ Un terminal web, c'est de l'exécution de code à distance **par conception**. N'exposez jamais Arboretum directement sur l'internet public.
### Mode serveur web (réseau local, reverse proxy)
Quel que soit le front que vous mettez devant, retenez la règle qui piège tout le monde en premier : **le
daemon rejette toute requête dont il ne connaît pas l'`Origin`**, avec un `403 BAD_ORIGIN`. L'adresse que
vous tapez dans le navigateur doit être passée en `--allow-origin` (répétable). Réglages → **Accès
distant** affiche l'origine courante, la liste autorisée, et la commande exacte pour en ajouter une.
**Derrière un reverse proxy** (nginx, Caddy, Traefik), avec terminaison TLS sur votre domaine :
```nginx
# nginx : l'upgrade WebSocket ET X-Forwarded-Proto sont nécessaires
location / {
proxy_pass http://127.0.0.1:7317;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme; # rend le cookie de session Secure
proxy_read_timeout 3600s; # terminaux longue durée
}
```
```bash
npx @johanleroy/git-arboretum --allow-origin https://arboretum.exemple.com
```
C'est `X-Forwarded-Proto: https` qui indique à Arboretum de marquer son cookie de session `Secure` ; sans
cet en-tête, le cookie reste non-Secure derrière votre front HTTPS. Gardez un timeout de lecture large :
un WebSocket de terminal reste inactif de longs moments.
**Sur le réseau local, sans proxy** (le moins recommandé : HTTP simple, pas de Web Push, pas d'install PWA) :
```bash
npx @johanleroy/git-arboretum \
--bind 0.0.0.0 --i-know-this-exposes-a-terminal \
--allow-origin http://192.168.1.42:7317
```
Le flag d'acquittement est obligatoire et n'est jamais ajouté pour vous : sortir de la boucle locale doit
être un acte délibéré. Restreignez l'accès au niveau réseau (pare-feu, VPN) et préférez Tailscale.
## Le faire tourner en service d'arrière-plan
Le plus rapide pour faire tourner Arboretum en service qui survit à la déconnexion et redémarre au boot, c'est l'installeur intégré. Installez une version figée globalement, puis lancez `install` — il détecte votre OS, écrit le fichier de service, le démarre et affiche le token unique :
Le plus rapide pour faire tourner Arboretum en service qui survit à la déconnexion et redémarre au boot, c'est l'installeur intégré. Installez une version figée globalement, puis lancez `install`. Il détecte votre OS, écrit le fichier de service, le démarre et affiche le token unique :
```bash
npm i -g @johanleroy/git-arboretum
arboretum install --allow-origin https://MACHINE.TAILNET.ts.net
```
Cela met en place un **service systemd utilisateur** sous Linux (`~/.config/systemd/user/arboretum.service`) ou un **LaunchAgent launchd** sous macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`). Tous les flags du daemon (`--port`, `--allow-origin`, `--db`, …) sont propagés au service. Gérez-le avec :
Cela met en place un **service systemd utilisateur** sous Linux (`~/.config/systemd/user/arboretum.service`), un **LaunchAgent launchd** sous macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`), ou une **tâche planifiée** sous Windows (`Arboretum`, déclenchée à l'ouverture de session, enregistrée par `schtasks`). Toujours sous votre compte utilisateur, jamais en root ni SYSTEM. Tous les flags du daemon (`--port`, `--allow-origin`, `--db`, …) sont propagés au service. Gérez-le avec :
```bash
arboretum status # état du service (+ où lire les logs)
@@ -167,7 +267,7 @@ Créez `~/.config/systemd/user/arboretum.service` :
```ini
[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
Description=Arboretum · git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
@@ -192,7 +292,7 @@ journalctl --user -u arboretum -f # logs
```
</details>
> Le **token d'accès** unique est affiché par `arboretum install` (et au tout premier lancement manuel sur base vierge). Le token est hashé et n'est jamais réaffiché — conservez-le en lieu sûr.
> Le **token d'accès** unique est affiché par `arboretum install` (et au tout premier lancement manuel sur base vierge). Le token est hashé et n'est jamais réaffiché, conservez-le en lieu sûr.
## Configuration
@@ -204,11 +304,13 @@ Les options du daemon sont des flags CLI :
|---|---|---|
| `--port <n>` | `7317` | Port d'écoute. |
| `--bind <addr>` | `127.0.0.1` | Adresse de bind. Une adresse non-loopback est refusée sauf si `--i-know-this-exposes-a-terminal` est défini. |
| `--allow-origin <url>` | — | Origine `Origin` autorisée supplémentaire (répétable). Nécessaire pour l'accès Tailscale/HTTPS. |
| `--allow-origin <url>` | aucun | Origine `Origin` autorisée supplémentaire (répétable). Nécessaire pour l'accès Tailscale/HTTPS. |
| `--db <path>` | `<data>/arboretum.db` | Chemin de la base SQLite. |
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | Sujet de contact VAPID pour le Web Push. |
| `--print-token` | `false` | Indication sur le réaffichage du token (les tokens sont hashés et ne peuvent pas être réaffichés). |
| `--i-know-this-exposes-a-terminal` | `false` | Reconnaître le bind sur une adresse non-loopback. **À éviter** — préférez Tailscale Serve. |
| `--print-token` | `false` | Affiche le jeton d'accès au démarrage (et le crée si la base n'en a aucun). |
| `--claude-home <chemin>` | `~/.claude` | Surcharge la racine d'installation de Claude (registre de sessions et transcripts). |
| `--no-discover` | `false` | Désactive la découverte auto des dépôts (scan au démarrage et re-scan périodique). |
| `--i-know-this-exposes-a-terminal` | `false` | Reconnaître le bind sur une adresse non-loopback. **À éviter** : préférez Tailscale Serve. |
`arboretum install` accepte tous les flags du daemon ci-dessus (propagés tels quels au service), plus :
@@ -219,22 +321,57 @@ Les options du daemon sont des flags CLI :
| `--dry-run` | Affiche le unit/plist et les commandes sans rien appliquer. |
| `--no-enable` | Écrit le fichier de service sans l'activer/le démarrer. |
L'état (la base SQLite) vit dans `$XDG_DATA_HOME/arboretum` (par défaut `~/.local/share/arboretum`).
L'état (la base SQLite) vit dans `$XDG_DATA_HOME/arboretum`, avec pour défaut
`~/.local/share/arboretum` sous Linux et macOS, et `%APPDATA%\arboretum` sous Windows.
Variables d'environnement :
| Variable | Utilisée par | Description |
|---|---|---|
| `ARBORETUM_LOG` | daemon | Niveau de log (`fatal`, `error`, `warn`, `info`, `debug`, `trace`). Défaut `info`. |
| `ARBORETUM_SECRET_KEY` | daemon | Clé de 32 octets (base64 ou hex) chiffrant les identifiants git stockés. Générée et conservée en base si absente. |
| `ARBORETUM_EMIT_TOKEN_FD` | daemon | Écrit le jeton d'accès sur ce descripteur de fichier au démarrage. Utilisé par l'app de bureau pour s'auto-connecter ; pas destiné à un usage manuel. |
| `XDG_DATA_HOME` | daemon | Racine du répertoire de données (voir ci-dessus). |
| `ARBORETUM_SHELL` | daemon (Windows) | Shell utilisé pour les commandes de projet. Défaut `powershell.exe`. |
| `ARBORETUM_DESKTOP_PORT` | app de bureau | Port sur lequel l'app de bureau lance son propre daemon. Défaut `7317`. À définir quand un autre Arboretum occupe ce port en permanence (service installé par `arboretum install`, ou daemon lancé en terminal). |
Les réglages au-delà des flags CLI (les répertoires qu'Arboretum scanne pour trouver des repos et à quelle fréquence, le chemin et le home du binaire `claude`, et les fenêtres de rétention / purge des sessions) vivent dans les **Réglages** de l'UI. Ils sont diffusés via le WebSocket, donc chaque navigateur connecté reflète un changement en temps réel, sans rechargement.
## Services git distants & clone
Arboretum peut se connecter à vos fournisseurs d'hébergement git pour parcourir et cloner des dépôts sans quitter le dashboard :
- **Fournisseurs & auth.** GitHub, GitLab et Gitea, authentifiés par un **personal access token** ou un **app password** (clés SSH et OAuth prévus). Ajoutez une connexion depuis **Réglages → Services git**, donnez-lui un libellé, et testez-la sur place : Arboretum rapporte `ok`, `auth failed`, `rate limited` ou `unreachable`.
- **Les secrets restent secrets.** Les identifiants sont **chiffrés au repos** (AES-256-GCM, `SecretBox`) et **jamais** renvoyés en clair par l'API REST : les réponses ne portent qu'un indice `…last4` et un drapeau « a un secret ».
- **Parcourir & cloner.** Listez les dépôts qu'une connexion peut voir, choisissez-en un, et clonez-le en HTTPS vers la destination de votre choix. Le clone tourne comme une opération suivie, avec **progression et phase** poussées en direct via le WebSocket, et le nouveau repo est enregistré automatiquement une fois terminé.
## Modèle de sécurité
Un terminal web, c'est de l'exécution de code à distance *par conception*. Les garde-fous d'Arboretum sont structurants :
- Se bind sur `127.0.0.1` par défaut ; refuse les binds non-loopback sans flag explicite.
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket — c'est le garde-fou anti cross-site hijacking).
- Authentifie **chaque** requête `/api/**` **et** chaque upgrade `/ws` avec des tokens révocables, et applique un **check `Origin` strict** (le cookie `SameSite=Strict` ne couvre pas les upgrades WebSocket : c'est le garde-fou anti cross-site hijacking).
- Les tokens sont stockés **hashés** (sha256) et comparés en temps constant ; le bootstrap token n'est affiché qu'une seule fois. Le cookie de session est un payload signé HMAC, `HttpOnly` et `SameSite=Strict`, et reçoit automatiquement le flag `Secure` quand la requête arrive en HTTPS (p. ex. derrière Tailscale Serve). Le login est rate-limité avec backoff exponentiel.
- Envoie des en-têtes HTTP durcis (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, HSTS conditionnel, `no-store` sur l'API), restreint le dossier de données à `0o700` et la base à `0o600`, et **chiffre les secrets sensibles au repos** (AES-256-GCM).
- Tient un **journal d'audit** des opérations sensibles et offre l'**export/effacement RGPD** des données (Réglages → Sécurité & conformité).
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils — pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
Tailscale Serve est **la** façon d'atteindre Arboretum depuis d'autres appareils, pas seulement une recommandation : HTTPS valide, identité tailnet, aucun port ouvert. Le flag `--i-know-this-exposes-a-terminal` est une trappe de secours, pas un mode de déploiement ; n'exposez jamais Arboretum directement sur internet.
Voir [`SECURITY.md`](SECURITY.md) pour le modèle de menace complet et [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) pour le durcissement en environnement réglementé.
## Dépannage
| Symptôme | Cause & correction |
|---|---|
| `npm error 404 Not Found @johanleroy/git-arboretum` | Le paquet vit sur un registre privé. Déclarez le scope dans votre `~/.npmrc` : `@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/` |
| `403 BAD_ORIGIN` dans la console, interface blanche | L'adresse utilisée n'est pas dans la liste autorisée. Redémarrez avec `--allow-origin <cette origine exacte>` (schéma, hôte et port doivent correspondre). |
| `ERR_UNKNOWN_BUILTIN_MODULE node:sqlite` ou plantage au démarrage | Node est antérieur à 22.16. Vérifiez avec `node --version` : `node:sqlite` n'est stable qu'à partir de là. L'app de bureau embarque son runtime et n'est pas concernée. |
| « Claude Code CLI not found in PATH » | Le daemon tourne avec un PATH minimal (cas typique sous systemd/launchd). Renseignez le chemin du binaire dans **Réglages → CLI Claude**, ou réinstallez le service avec `arboretum install`, qui fige votre PATH interactif. |
| Impossible d'activer les notifications | Le Web Push exige HTTPS. Utilisez Tailscale Serve ou un reverse proxy ; sur iOS, installez d'abord la PWA. |
| Le lanceur affiche une icône générique (Linux) | Corrigé en desktop 0.2.0 : les paquets antérieurs installaient une taille d'icône non standard, ignorée par la spécification freedesktop. Mettez le `.deb` à jour ; si l'icône persiste, lancez `gtk-update-icon-cache -f /usr/share/icons/hicolor` ou reconnectez-vous. |
| SmartScreen ou Gatekeeper bloque l'app | Attendu : les binaires ne sont pas signés. Voir le tableau par plateforme plus haut. |
| Un terminal reste vide après « Démarrer le projet » | La commande a été tapée dans un shell de login qui n'a pas démarré. Regardez l'onglet : le shell survit volontairement à l'échec, l'erreur y est donc visible. |
## Ce qui le distingue
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
@@ -242,7 +379,7 @@ Voir [`SECURITY.md`](SECURITY.md) pour le modèle de menace complet et [`docs/EN
| Interface web, tout appareil | ✅ | ❌ apps desktop | ✅ | ✅ |
| Gestion visuelle des worktrees (multi-repo) | ✅ | ✅ (mono-repo, desktop) | ❌ | ❌ |
| Découvre & reprend les sessions de terminal *existantes* | ✅ | ❌ | partiel | ❌ |
| 100 % auto-hébergé — zéro trafic via des serveurs tiers | ✅ | ✅ | serveur relais | ❌ relayé via Anthropic |
| 100 % auto-hébergé, zéro trafic via des serveurs tiers | ✅ | ✅ | serveur relais | ❌ relayé via Anthropic |
| Linux-first | ✅ | variable | ✅ | l'app desktop n'a pas de build Linux |
| Open source | MIT | ❌ / partiel | MIT / AGPL | ❌ |
@@ -250,11 +387,11 @@ Le Remote Control d'Anthropic est excellent pour piloter *une* session depuis vo
## Une note sur l'usage de Claude
Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY — la même chose que vous lancez dans votre terminal, affichée dans votre navigateur. Il n'utilise pas l'Agent SDK ni le mode headless. Les politiques d'usage d'Anthropic autour de l'usage programmatique peuvent évoluer ; Arboretum suivra les sorties du CLI et documentera tout impact de façon transparente.
Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY : la même chose que vous lancez dans votre terminal, affichée dans votre navigateur. Il n'utilise pas l'Agent SDK ni le mode headless. Les politiques d'usage d'Anthropic autour de l'usage programmatique peuvent évoluer ; Arboretum suivra les sorties du CLI et documentera tout impact de façon transparente.
## Développement
Arboretum est un monorepo npm workspaces : `@arboretum/shared` (protocole WS/REST, source de vérité), `@johanleroy/git-arboretum` (le daemon Fastify, le paquet publié), `@arboretum/web` (la SPA Vue 3) et `git-arboretum` (l'extension VS Code — buildée séparément avec `npm run build:vscode`).
Arboretum est un monorepo npm workspaces : `@arboretum/shared` (protocole WS/REST, source de vérité), `@johanleroy/git-arboretum` (le daemon Fastify, le paquet publié), `@arboretum/web` (la SPA Vue 3) et `git-arboretum` (l'extension VS Code, buildée séparément avec `npm run build:vscode`).
```bash
npm run build # build shared → server → web (l'ordre compte)
@@ -272,8 +409,25 @@ node packages/server/scripts/acceptance-p2.mjs # découverte & reprise de sess
node packages/server/scripts/acceptance-p3.mjs # worktrees & corrélation de sessions
node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answer`
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
node packages/server/scripts/acceptance-p7.mjs # moteur git, API fichiers & watcher FS temps réel
node packages/server/scripts/acceptance-p8.mjs # IDE workspace : changes / diff / staging / commit
node packages/server/scripts/acceptance-p9.mjs # commit/push avancé : staging sélectif, amend, fetch/pull
node packages/server/scripts/acceptance-p10.mjs # archivage automatique des sessions
node packages/server/scripts/acceptance-p11.mjs # synchronisation des réglages en temps réel
node packages/server/scripts/acceptance-p12.mjs # services git distants + clone HTTPS
node packages/server/scripts/acceptance-p13.mjs # démarrer le projet : commandes de lancement, multi-terminaux
node packages/server/scripts/acceptance-p14.mjs # temps réel armé : watcher épinglé par session, corrélation cwd
node packages/server/scripts/acceptance-p15.mjs # historisation : log de commits & diff par commit
```
Contrôle de rendu (Chromium headless via CDP, sans Playwright) : après `npm run build`, lancez
`node packages/server/scripts/copy-web.mjs` puis
`node packages/server/scripts/verify-ui.mjs [dossier]`. Le script démarre un daemon isolé, crée un dépôt
de démonstration et écrit des captures de l'IDE dans les deux thèmes, en largeurs desktop et mobile, en
échouant sur toute erreur console.
Le protocole s'est enrichi (de façon additive, sans bump de version) pour porter ces nouveautés : messages client `watch` / `unwatch` et signal ciblé `worktree_changes` (P7), plus les broadcasts `session_archived` (P10), `settings_update` (P11) et `clone_update` (P12). Côté serveur, le tout s'appuie sur `core/git.ts` (le moteur git pur), `core/fs-watcher.ts` (chokidar), `core/git-credentials.ts` + `core/clone-manager.ts` (identifiants chiffrés & clone), et les services d'archivage de sessions et de réglages.
## Soutenir le projet
Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner du temps, vous pouvez soutenir son développement :
@@ -282,4 +436,4 @@ Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner
## Licence
MIT — voir [LICENSE](LICENSE).
MIT, voir [LICENSE](LICENSE).
+195 -41
View File
@@ -3,14 +3,32 @@
</p>
<p align="center">
A self-hosted web dashboard for your git worktrees and the Claude Code sessions running on them — from any device.
A self-hosted, multi-project AI IDE for your git worktrees and the Claude Code sessions running on them: a native desktop app and a web UI, from any device.
</p>
<p align="center">
<strong>English</strong> · <a href="README.fr.md">Français</a>
</p>
**Status: MVP.** The worktree-first dashboard, session discovery & resume, multi-repo worktree lifecycle, sessions on your main branch or any worktree, live session states, the web terminal, mobile supervision (installable PWA, Web Push when a session needs you, answer a prompt without opening a terminal), and work groups (drive several related repos from a single Claude session) are implemented and tested.
Session discovery & resume, multi-repo worktree lifecycle, sessions on your main branch or any worktree, live session states, the web terminal, mobile supervision (installable PWA, Web Push when a session needs you, answer a prompt without opening a terminal), and work groups (drive several related repos from a single Claude session) are all implemented and tested.
The latest milestone turns Arboretum into a real **multi-project AI IDE**: a single workspace (route `/ide`, the default view on desktop) that holds **all** your open projects at once, no more one IDE window per project. A single left tree (project, then main checkout and worktrees, then Claude session), a tabbed Monaco editor at the center (several files from different projects side by side, inline diffs), Claude terminals in a bottom dock, and Git / Sessions / Groups panels via an activity bar. It ships both as a **native desktop app** (Linux, Windows, macOS) and the same web UI, backed by a real-time file-system watcher, selective staging / discard / amend / fetch / pull, automatic session archival, real-time settings sync, and encrypted remote git services (GitHub / GitLab / Gitea) with HTTPS clone.
---
## Screenshots
<p align="center">
<img src="brand/screenshot-ide-dark.png" alt="Arboretum, the multi-project AI IDE (dark theme)" width="900">
</p>
<p align="center">
<em>One workspace for every project: a unified tree, a tabbed Monaco editor with inline diffs, and docked Claude terminals. Dark and light themes.</em>
</p>
<p align="center">
<img src="brand/screenshot-ide-light.png" alt="Arboretum, the multi-project AI IDE (light theme)" width="900">
</p>
---
@@ -24,40 +42,44 @@ Working with AI coding agents changed how we use git: one feature = one worktree
## What Arboretum does
A single Node.js daemon you run on your dev machine (`npx @johanleroy/git-arboretum`), serving a web UI usable from your desktop, phone or tablet:
A single Node.js daemon you run on your dev machine (as a native desktop app, or via `npx @johanleroy/git-arboretum`), serving a UI usable from your desktop, phone or tablet:
- **Worktree-first, multi-repo dashboard** — every worktree of every registered repo, with its git state (branch, ahead/behind, dirty files) *and* the state of its Claude Code session (busy / waiting for input / idle / resumable).
- **Full worktree lifecycle** — create (with per-repo post-create hooks: `npm ci`, copy `.env`…), adopt worktrees created by hand, delete with guardrails, prune orphans.
- **Session discovery & resume** — sessions you launched in your own terminal show up automatically; resume dead ones, observe or fork live ones. Never corrupts a live session. Hide the old ones that clutter the list (one click clears the whole external history; they stay resumable).
- **Web terminal** — full xterm.js terminal to every managed session, surviving browser disconnects; truly fullscreen, with the prompt pinned to the bottom and full scrollback above.
- **Supervision from your phone** — installable PWA with push notifications when a session needs you; answer a prompt (its options, or deny) without opening a terminal.
- **Work groups** — bundle related repos (e.g. an API, its web frontend and its docs) into a named group, then launch **one Claude session that spans all of them at once** (via the CLI's `--add-dir`): a single conversation with one shared context working across every repo, plus a unified view of all their worktrees and a side-by-side multi-terminal grid. Group sessions can either create the same branch worktree in each repo first, or run straight on the main checkouts.
- **VS Code extension** — a native extension (not a webview) that brings the live tree, native session terminals, waiting alerts and git actions right into your editor. See [VS Code extension](#vs-code-extension).
- **Multi-repo worktree dashboard**: every worktree of every registered repo, with its git state (branch, ahead/behind, dirty files) *and* the state of its Claude Code session (busy / waiting for input / idle / resumable).
- **Full worktree lifecycle**: create (with per-repo post-create hooks: `npm ci`, copy `.env`…), adopt worktrees created by hand, delete with guardrails, prune orphans.
- **Session discovery & resume**: sessions you launched in your own terminal show up automatically; resume dead ones, observe or fork live ones. Never corrupts a live session. Hide the old ones that clutter the list (one click clears the whole external history; they stay resumable).
- **Web terminal**: full xterm.js terminal to every managed session, surviving browser disconnects; truly fullscreen, with the prompt pinned to the bottom and full scrollback above.
- **Multi-project IDE**: one workspace for every open project at once (no per-project window). A single tree (project, worktrees, Claude sessions), a tabbed Monaco editor (several files from different projects side by side, with inline per-file diffs), a bottom dock of session terminals, and Git / Sessions / Groups panels. Edit files, stage changes selectively, commit (or amend), fetch/pull and push, all in one place. A real-time file-system watcher keeps the view live as the agent edits. Available as a native desktop app and in the browser.
- **Start a project in one click**: many projects need several long-running commands to boot (dev server, API, database). Define them once per project (labels, shell commands, optional subdir), auto-detected from `package.json` scripts, a `Procfile` or `docker-compose`, then launch them all at once, one attached terminal per command. Each runs in your login shell (so `npm`, `docker`, nvm/asdf are on `PATH`) and stays live after the command exits, so failures stay on screen; stop the whole set in one action.
- **Supervision from your phone**: installable PWA with push notifications when a session needs you; answer a prompt (its options, or deny) without opening a terminal.
- **Work groups**: bundle related repos (e.g. an API, its web frontend and its docs) into a named group, then launch **one Claude session that spans all of them at once** (via the CLI's `--add-dir`): a single conversation with one shared context working across every repo, plus a unified view of all their worktrees and a side-by-side multi-terminal grid. Group sessions can either create the same branch worktree in each repo first, or run straight on the main checkouts.
- **Remote git services**: connect your GitHub, GitLab or Gitea accounts (personal access token or app password), stored **encrypted at rest** (AES-256-GCM); browse your remote repositories and clone them over HTTPS with live progress, straight from the dashboard.
- **Automatic archival**: finished sessions are archived automatically after a configurable retention window (30 days by default), so the list stays focused on what's live while the history is one toggle away.
- **VS Code extension**: a native extension (not a webview) that brings the live tree, native session terminals, waiting alerts and git actions right into your editor. See [VS Code extension](#vs-code-extension).
---
## Requirements
- **Node.js ≥ 22.16** — required, not just recommended. Arboretum persists state with `node:sqlite` (`DatabaseSync`), which is native and stable only from this version. (`.nvmrc` pins `22`.)
- **The `claude` CLI** on your `PATH` if you want Arboretum to launch and manage Claude Code sessions. Arboretum wraps the interactive CLI you already use — install and authenticate it as usual.
- **Node.js ≥ 22.16** for the `npx` / from-source usage: required, not just recommended. Arboretum persists state with `node:sqlite` (`DatabaseSync`), which is native and stable only from this version. (`.nvmrc` pins `22`.) The **desktop app bundles its own Node runtime**, so its end users do not need to install Node.
- **The `claude` CLI** on your `PATH` if you want Arboretum to launch and manage Claude Code sessions. Arboretum wraps the interactive CLI you already use, install and authenticate it as usual.
- A **git** repository (or several) you want to manage.
## Quick start
Two paths, depending on what you want:
- **Just use it (most people).** Arboretum is a published npm package — you **don't need to clone this repo**. Point npm at the registry and run it (below). Do this on the machine where your Claude Code sessions run.
- **Just use it (most people).** Arboretum is a published npm package: you **don't need to clone this repo**. Point npm at the registry and run it (below). Do this on the machine where your Claude Code sessions run.
- **Run from source.** Clone the repo only to hack on Arboretum or run an unreleased build.
### Run it (recommended)
Arboretum is published to a self-hosted Gitea npm registry. Point the `@johanleroy` scope at it once per machine — add to `~/.npmrc`:
Arboretum is published to a self-hosted Gitea npm registry. Point the `@johanleroy` scope at it once per machine, add to `~/.npmrc`:
```
@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/
```
No token needed — the package is publicly readable. Then run it from anywhere:
No token needed, the package is publicly readable. Then run it from anywhere:
```bash
npx @johanleroy/git-arboretum
@@ -67,7 +89,7 @@ On first start, Arboretum prints a one-time **access token** and the URL to open
```
┌──────────────────────────────────────────────────────────────────┐
│ First start — your access token (shown once, store it safely): │
│ First start · your access token (shown once, store it safely): │
└──────────────────────────────────────────────────────────────────┘
<your-token-here>
@@ -75,9 +97,9 @@ On first start, Arboretum prints a one-time **access token** and the URL to open
Login at: http://127.0.0.1:7317/
```
Open the URL, paste the token to log in, and you're in. The token is stored **hashed** — it is shown only once, so save it somewhere safe (a password manager). You can manage tokens later from **Settings**.
Open the URL, paste the token to log in, and you're in. The token is stored **hashed**: it is shown only once, so save it somewhere safe (a password manager). You can manage tokens later from **Settings**.
`npx` fetches and runs the latest published version each time. To install it once — and get the `arboretum` command on your `PATH`, which the [background service](#running-it-as-a-background-service) relies on — install it globally instead:
`npx` fetches and runs the latest published version each time. To install it once (and get the `arboretum` command on your `PATH`, which the [background service](#running-it-as-a-background-service) relies on), install it globally instead:
```bash
npm i -g @johanleroy/git-arboretum
@@ -86,7 +108,7 @@ arboretum # identical to the npx command, from the installed binary
### Run from source
Only needed to **develop** Arboretum or run an unreleased build — not required just to use it. Clone the repo, install dependencies, build, then start the daemon:
Only needed to **develop** Arboretum or run an unreleased build, not required just to use it. Clone the repo, install dependencies, build, then start the daemon:
```bash
git clone https://git.lidge.fr/johanleroy/arboretum.git
@@ -97,35 +119,72 @@ npm run build # builds shared → server → web (order matters)
node packages/server/dist/index.js
```
## Desktop app
Prefer a native app to the daemon-in-a-terminal? Arboretum ships an **Electron desktop app** (`packages/desktop`) for **Linux, Windows and macOS**. It runs the daemon as a child process and opens its UI in a native window, already signed in (no login screen), and it **bundles its own Node runtime**, so you do not need Node installed to use it.
- **Install.** Installers are published on the [releases page](https://git.lidge.fr/johanleroy/arboretum/releases) when a desktop release is tagged: an AppImage and a `.deb` on Linux, an NSIS installer (and a portable build) on Windows, a `.dmg` on macOS. Prefer to build them yourself? See [`packages/desktop/README.md`](packages/desktop/README.md).
- **First launch.** The app is not code-signed yet: on **Windows**, SmartScreen shows "unknown publisher", choose "More info" then "Run anyway"; on **macOS**, Gatekeeper blocks it, right-click the app then "Open" (or run `xattr -dr com.apple.quarantine /Applications/Arboretum.app`).
- **Lives in the tray.** Closing the window keeps Arboretum running in the system tray; quit from the tray menu, where you can also toggle launch-at-login. Auto-update is built in on Windows and Linux (macOS updates are manual while unsigned).
The desktop app is just a shell around the same daemon and web UI, so everything below (workspace, git, sessions) works identically.
### Installing per platform
| Platform | Artifact | Notes |
|---|---|---|
| **Debian / Ubuntu** | `Arboretum-<version>-amd64.deb` | `sudo apt install ./Arboretum-*.deb`. Pulls in `git`. Preferred over the AppImage on Debian: it installs the launcher entry and its icons. |
| **Other Linux** | `Arboretum-<version>-x86_64.AppImage` | `chmod +x` then run. No desktop entry unless you use a tool like `appimaged`. |
| **Windows** | `Arboretum-<version>-x64.exe` (NSIS) or the portable build | Not code-signed: SmartScreen shows "unknown publisher", choose **More info → Run anyway**. Needs Windows 10 1809+ (ConPTY). |
| **macOS** | `Arboretum-<version>.dmg` | Not signed or notarized: right-click the app → **Open**, or `xattr -dr com.apple.quarantine /Applications/Arboretum.app`. Built on demand, see `packages/desktop/README.md`. |
Windows also needs the `claude` CLI on your PATH like any other platform; if the app cannot find it,
set its path in **Settings → Claude CLI**. Running the daemon at logon is supported there too
(`arboretum install` registers a scheduled task).
## Using Arboretum
1. **Add a repository.** From the dashboard, register a local git repo by its path. Optionally configure **post-create hooks** (e.g. `npm ci`, `cp ../.env .env`) that run automatically every time you create a new worktree for that repo.
2. **Create or adopt worktrees.** Spin up a new worktree + branch in one click (hooks run for you), or adopt a worktree you created by hand. Each worktree shows its branch, ahead/behind, and dirty-file count.
3. **Start or resume a session.** Launch a Claude Code session on the repo's main branch or any worktree, or resume one that was started in your terminal — Arboretum discovers existing sessions automatically and always resumes them in their original working directory.
3. **Start or resume a session.** Launch a Claude Code session on the repo's main branch or any worktree, or resume one that was started in your terminal: Arboretum discovers existing sessions automatically and always resumes them in their original working directory.
4. **Watch the live states.** Each session reports whether it's *busy*, *waiting for your input*, or *idle*. Open the **web terminal** to interact directly; it survives browser disconnects (closing the tab does not kill the session).
5. **Supervise from your phone.** Install the PWA, and when a session flips to *waiting* you get a push notification. Answer the prompt — pick one of its options or deny it — straight from the dashboard, no terminal required.
5. **Supervise from your phone.** Install the PWA, and when a session flips to *waiting* you get a push notification. Answer the prompt (pick one of its options or deny it) straight from the dashboard, no terminal required.
## The IDE, workspace & git operations
Beyond supervising, Arboretum is a full **multi-project IDE** (route `/ide`, the default view on desktop). It holds every open project at once, so you never juggle one IDE window per project:
- **Unified project tree.** A single left tree lists every registered project, its main checkout and worktrees, and the Claude session correlated with each. Expand a worktree to browse its files inline. An activity bar switches the left panel between Explorer, Git, Sessions and Groups.
- **Tabbed editor.** Open files in a **Monaco editor** with tabs, several files from **different projects** side by side, syntax highlighting, language detection, save with conflict detection. Each tab toggles between editor and an inline **per-file diff** (working tree or index, additions/deletions colour-coded, binary and huge diffs refused).
- **Terminal dock.** Claude session terminals live in a bottom dock with one tab per session; open several at once (across projects), answer a waiting prompt right there. Terminals survive tab switches and browser disconnects.
- **Git panel.** Stage or unstage individual files, discard changes, write a message and **commit** (everything or just what's staged), **amend** the last commit (refused once pushed), then **fetch**, **pull** (fast-forward or rebase) and **push**. Detailed staged / unstaged / conflict counts and the last commit stay current via a **real-time file-system watcher**, so the view updates the moment a Claude session touches a file.
- **Deep links & mobile.** `/workspace/:repoId/:wt` still opens a specific worktree straight in the IDE (used by the VS Code extension). On mobile the IDE degrades to a single panel, and the worktree dashboard and session views remain the installable supervision PWA.
- **Light or dark, your call.** A clean, consistent visual language (the "Emerald" design system: Inter + JetBrains Mono, an emerald accent) with a **light / dark / system** theme toggle remembered across sessions. The Monaco editor, the terminals and the diffs all follow the active theme.
Like every git action in Arboretum, these run **as you** (the daemon runs under your account), consistent with the security model: a web terminal is remote code execution by design.
## VS Code extension
Prefer to stay in your editor? Arboretum ships a **native VS Code extension** (`packages/vscode`) — not a webview. It connects to the same daemon and surfaces it with VS Code's own primitives:
Prefer to stay in your editor? Arboretum ships a **native VS Code extension** (`packages/vscode`), not a webview. It connects to the same daemon and surfaces it with VS Code's own primitives:
- A live **Repositories** and **Groups** tree (repos → worktrees → sessions) in the Activity Bar, updated in real time over the daemon's WebSocket.
- **Native terminals**: attach to (or observe) any session in a real VS Code terminal — you get VS Code's rendering, scrollback and copy/paste for free.
- **Native terminals**: attach to (or observe) any session in a real VS Code terminal, you get VS Code's rendering, scrollback and copy/paste for free.
- A **status-bar** counter and native **notifications** when a session is waiting, with Yes/No answers without opening a terminal.
- Git mutations (create worktree, commit, push, promote) and **workspace awareness** — the worktree for your open folder is highlighted, with one-click "start session / create worktree here".
- Git mutations (create worktree, commit, push, promote, **fetch / pull**) with **detailed git status** in the tree (staged / unstaged / conflicts and the last commit), and **workspace awareness**: the worktree for your open folder is highlighted, with one-click "start session / create worktree here".
- **Open in the web IDE**: jump from any worktree straight to its full `/workspace` view in the browser. The extension stays a lightweight, visual worktree manager; the heavy editing lives in the web IDE.
It is distributed as a **private VSIX**. Build and package it from the monorepo:
```bash
npm run build:vscode
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.1.0.vsix
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-<version>.vsix
```
Then install it via **Extensions: Install from VSIX…** (or `code --install-extension git-arboretum-0.1.0.vsix`), run **Arboretum: Sign In** and paste a token. Full details in [`packages/vscode/README.md`](packages/vscode/README.md).
Then install it via **Extensions: Install from VSIX…** (or `code --install-extension git-arboretum-<version>.vsix`), run **Arboretum: Sign In** and paste a token. Full details in [`packages/vscode/README.md`](packages/vscode/README.md).
## Remote access from your phone
Arboretum binds to `127.0.0.1` by default and **refuses** to bind to a non-loopback address without an explicit override. The recommended (and safe) way to reach it from other devices is **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)** — valid HTTPS, tailnet identity, no open ports:
Arboretum binds to `127.0.0.1` by default and **refuses** to bind to a non-loopback address without an explicit override. The recommended (and safe) way to reach it from other devices is **[Tailscale Serve](https://tailscale.com/kb/1242/tailscale-serve)**, valid HTTPS, tailnet identity, no open ports:
```bash
# Expose the local daemon over HTTPS inside your tailnet
@@ -142,16 +201,57 @@ Open `https://<machine>.<tailnet>.ts.net` from any device on your tailnet. **Web
> ⚠️ A web terminal is remote code execution **by design**. Never expose Arboretum directly to the public internet.
### Web server mode (LAN, reverse proxy)
Whatever front you put in place, remember the rule that trips everyone up first: **the daemon rejects any
request whose `Origin` it does not know**, with `403 BAD_ORIGIN`. The address you type in the browser must
be passed with `--allow-origin` (repeatable). Settings → **Remote access** shows the current origin, the
allowed list, and the exact command to add one.
**Behind a reverse proxy** (nginx, Caddy, Traefik), terminating TLS on your own domain:
```nginx
# nginx: the WebSocket upgrade and X-Forwarded-Proto are both required
location / {
proxy_pass http://127.0.0.1:7317;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme; # makes the session cookie Secure
proxy_read_timeout 3600s; # long-lived terminals
}
```
```bash
npx @johanleroy/git-arboretum --allow-origin https://arboretum.example.com
```
`X-Forwarded-Proto: https` is what tells Arboretum to mark its session cookie `Secure`; without it the
cookie stays non-Secure behind your HTTPS front. Keep the proxy read timeout generous, a terminal
WebSocket is idle for long stretches.
**On the LAN, without a proxy** (least recommended: plain HTTP, no Web Push, no PWA install):
```bash
npx @johanleroy/git-arboretum \
--bind 0.0.0.0 --i-know-this-exposes-a-terminal \
--allow-origin http://192.168.1.42:7317
```
The acknowledgement flag is mandatory and never added for you: binding beyond loopback must be a
deliberate act. Restrict access at the network level (firewall, VPN) and prefer Tailscale.
## Running it as a background service
The quickest way to run Arboretum as a service that survives logout and restarts on boot is the built-in installer. Install a pinned version globally, then run `install` — it detects your OS, writes the service file, starts it, and prints the one-time token:
The quickest way to run Arboretum as a service that survives logout and restarts on boot is the built-in installer. Install a pinned version globally, then run `install`. It detects your OS, writes the service file, starts it, and prints the one-time token:
```bash
npm i -g @johanleroy/git-arboretum
arboretum install --allow-origin https://MACHINE.TAILNET.ts.net
```
This sets up a **systemd user service** on Linux (`~/.config/systemd/user/arboretum.service`) or a **launchd LaunchAgent** on macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`). Every daemon flag (`--port`, `--allow-origin`, `--db`, …) is propagated to the service. Manage it with:
This sets up a **systemd user service** on Linux (`~/.config/systemd/user/arboretum.service`), a **launchd LaunchAgent** on macOS (`~/Library/LaunchAgents/fr.lidge.arboretum.plist`), or a **scheduled task** on Windows (`Arboretum`, triggered at logon, registered with `schtasks`). Always as your user, never as root or SYSTEM. Every daemon flag (`--port`, `--allow-origin`, `--db`, …) is propagated to the service. Manage it with:
```bash
arboretum status # service status (+ where to read logs)
@@ -167,7 +267,7 @@ Create `~/.config/systemd/user/arboretum.service`:
```ini
[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
Description=Arboretum · git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
@@ -192,7 +292,7 @@ journalctl --user -u arboretum -f # logs
```
</details>
> The one-time **access token is printed by `arboretum install`** (and on the very first manual run with an empty database). The token is hashed and never shown again — store it safely.
> The one-time **access token is printed by `arboretum install`** (and on the very first manual run with an empty database). The token is hashed and never shown again, store it safely.
## Configuration
@@ -204,11 +304,13 @@ Daemon options are CLI flags:
|---|---|---|
| `--port <n>` | `7317` | Port to listen on. |
| `--bind <addr>` | `127.0.0.1` | Bind address. Non-loopback is refused unless `--i-know-this-exposes-a-terminal` is set. |
| `--allow-origin <url>` | — | Additional allowed `Origin` (repeatable). Needed for Tailscale/HTTPS access. |
| `--allow-origin <url>` | none | Additional allowed `Origin` (repeatable). Needed for Tailscale/HTTPS access. |
| `--db <path>` | `<data>/arboretum.db` | SQLite database path. |
| `--vapid-contact <mailto/url>` | `mailto:arboretum@localhost` | VAPID contact subject for Web Push. |
| `--print-token` | `false` | Hint about token re-printing (tokens are hashed and cannot be re-shown). |
| `--i-know-this-exposes-a-terminal` | `false` | Acknowledge binding to a non-loopback address. **Avoid** — prefer Tailscale Serve. |
| `--print-token` | `false` | Print the access token on start (bootstraps one if the database has none). |
| `--claude-home <path>` | `~/.claude` | Override the Claude install root (session registry and transcripts). |
| `--no-discover` | `false` | Disable repository auto-discovery (start-up scan and periodic re-scan). |
| `--i-know-this-exposes-a-terminal` | `false` | Acknowledge binding to a non-loopback address. **Avoid**: prefer Tailscale Serve. |
`arboretum install` accepts every daemon flag above (propagated verbatim to the service) plus:
@@ -219,22 +321,57 @@ Daemon options are CLI flags:
| `--dry-run` | Print the unit/plist and commands without applying anything. |
| `--no-enable` | Write the service file but do not enable/start it. |
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum` (default `~/.local/share/arboretum`).
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum`, defaulting to
`~/.local/share/arboretum` on Linux and macOS and `%APPDATA%\arboretum` on Windows.
Environment variables:
| Variable | Used by | Description |
|---|---|---|
| `ARBORETUM_LOG` | daemon | Log level (`fatal`, `error`, `warn`, `info`, `debug`, `trace`). Default `info`. |
| `ARBORETUM_SECRET_KEY` | daemon | 32-byte key (base64 or hex) encrypting stored git credentials. Generated and stored in the database when absent. |
| `ARBORETUM_EMIT_TOKEN_FD` | daemon | Write the access token to this file descriptor at start-up. Used by the desktop app to sign itself in; not meant for manual use. |
| `XDG_DATA_HOME` | daemon | Root of the data directory (see above). |
| `ARBORETUM_SHELL` | daemon (Windows) | Shell used to run project commands. Default `powershell.exe`. |
| `ARBORETUM_DESKTOP_PORT` | desktop app | Port the desktop app starts its own daemon on. Default `7317`. Set it when another Arboretum permanently holds that port (a service installed with `arboretum install`, or one you run in a terminal). |
Settings beyond CLI flags (the directories Arboretum scans for repos and how often, the `claude` binary path and home, and the session retention / purge windows) live in **Settings** in the UI. They are broadcast over the WebSocket, so every connected browser reflects a change in real time, no reload needed.
## Remote git services & clone
Arboretum can connect to your git hosting providers so you can browse and clone repositories without leaving the dashboard:
- **Providers & auth.** GitHub, GitLab and Gitea, authenticated with a **personal access token** or an **app password** (SSH keys and OAuth are planned). Add a connection from **Settings → Git services**, give it a label, and test it in place: Arboretum reports `ok`, `auth failed`, `rate limited` or `unreachable`.
- **Secrets stay secret.** Credentials are **encrypted at rest** (AES-256-GCM, `SecretBox`) and **never** returned in clear by the REST API: responses carry only a `…last4` hint and a "has secret" flag.
- **Browse & clone.** List the repositories a connection can see, pick one, and clone it over HTTPS into a destination of your choice. The clone runs as a tracked operation with live **progress and phase** pushed over the WebSocket, and the new repo is registered automatically when it completes.
## Security model
A web terminal is remote code execution *by design*. Arboretum's guardrails are structural:
- Binds to `127.0.0.1` by default; refuses non-loopback binds without an explicit flag.
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades — this is the anti cross-site hijacking guard).
- Authenticates **every** `/api/**` request **and** every `/ws` upgrade with revocable tokens, and applies a **strict `Origin` check** (the `SameSite=Strict` cookie does not cover WebSocket upgrades: this is the anti cross-site hijacking guard).
- Tokens are stored **hashed** (sha256) and compared in constant time; the bootstrap token is shown only once. The session cookie is an HMAC-signed payload, `HttpOnly` and `SameSite=Strict`, and it automatically gains the `Secure` flag when the request arrives over HTTPS (e.g. behind Tailscale Serve). Login is rate-limited with exponential backoff.
- Sends hardened HTTP headers (CSP, `X-Frame-Options`, `nosniff`, `Referrer-Policy`, conditional HSTS, `no-store` on the API), restricts the data directory to `0o700` and the database to `0o600`, and **encrypts sensitive secrets at rest** (AES-256-GCM).
- Keeps an **audit log** of sensitive operations and offers **GDPR** data export/erasure (Settings → Security & compliance).
Tailscale Serve is **the** way to reach Arboretum from other devices — not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
Tailscale Serve is **the** way to reach Arboretum from other devices, not just a recommendation: valid HTTPS, tailnet identity, no open ports. The `--i-know-this-exposes-a-terminal` flag is an escape hatch, not a deployment mode; never expose Arboretum directly to the internet.
See [`SECURITY.md`](SECURITY.md) for the full threat model and [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md) for hardening in regulated environments.
## Troubleshooting
| Symptom | Cause & fix |
|---|---|
| `npm error 404 Not Found @johanleroy/git-arboretum` | The package lives on a private registry. Add the scope to your `~/.npmrc`: `@johanleroy:registry=https://git.lidge.fr/api/packages/johanleroy/npm/` |
| `403 BAD_ORIGIN` in the browser console, blank UI | The address you are using is not in the allowed list. Restart with `--allow-origin <that exact origin>` (scheme, host and port must match). |
| `ERR_UNKNOWN_BUILTIN_MODULE node:sqlite` or a crash on start | Node is older than 22.16. Check with `node --version`; `node:sqlite` is only stable from there. The desktop app bundles its own runtime and is immune. |
| "Claude Code CLI not found in PATH" | The daemon runs with a minimal PATH (typical under systemd/launchd). Set the binary path in **Settings → Claude CLI**, or reinstall the service with `arboretum install`, which freezes your interactive PATH. |
| Notifications cannot be enabled | Web Push requires HTTPS. Use Tailscale Serve or a reverse proxy; on iOS, install the PWA first. |
| The app launcher shows a generic icon (Linux) | Fixed in desktop 0.2.0: earlier packages installed a single non-standard icon size that the freedesktop spec ignores. Upgrade the `.deb`; if the icon persists, run `gtk-update-icon-cache -f /usr/share/icons/hicolor` or log out and back in. |
| SmartScreen or Gatekeeper blocks the app | Expected: the binaries are not signed. See the per-platform table above. |
| A terminal stays blank after "Start project" | The command was typed into a login shell that failed to start. Check the tab: the shell survives the failure on purpose, so the error is visible in it. |
## What makes it different
| | Arboretum | GitKraken Agent Mode / Conductor / Nimbalyst | Happy / CloudCLI | Anthropic Remote Control |
@@ -242,7 +379,7 @@ See [`SECURITY.md`](SECURITY.md) for the full threat model and [`docs/ENTERPRISE
| Web UI, any device | ✅ | ❌ desktop apps | ✅ | ✅ |
| Visual worktree management (multi-repo) | ✅ | ✅ (single repo, desktop) | ❌ | ❌ |
| Discovers & resumes *existing* terminal sessions | ✅ | ❌ | partial | ❌ |
| 100% self-hosted — zero traffic through third-party servers | ✅ | ✅ | relay server | ❌ relayed through Anthropic |
| 100% self-hosted, zero traffic through third-party servers | ✅ | ✅ | relay server | ❌ relayed through Anthropic |
| Linux-first | ✅ | varies | ✅ | Desktop app has no Linux build |
| Open source | MIT | ❌ / partial | MIT / AGPL | ❌ |
@@ -250,11 +387,11 @@ Anthropic's Remote Control is great at piloting *one* session from your phone. A
## A note on Claude usage
Arboretum wraps the **interactive** Claude Code CLI in a PTY — the same thing you run in your terminal, displayed in your browser. It does not use the Agent SDK or headless mode. Anthropic's usage policies around programmatic use may evolve; Arboretum will track CLI releases and document any impact transparently.
Arboretum wraps the **interactive** Claude Code CLI in a PTY: the same thing you run in your terminal, displayed in your browser. It does not use the Agent SDK or headless mode. Anthropic's usage policies around programmatic use may evolve; Arboretum will track CLI releases and document any impact transparently.
## Development
Arboretum is an npm-workspaces monorepo: `@arboretum/shared` (WS/REST protocol, source of truth), `@johanleroy/git-arboretum` (the Fastify daemon, the published package), `@arboretum/web` (the Vue 3 SPA), and `git-arboretum` (the VS Code extension — built separately with `npm run build:vscode`).
Arboretum is an npm-workspaces monorepo: `@arboretum/shared` (WS/REST protocol, source of truth), `@johanleroy/git-arboretum` (the Fastify daemon, the published package), `@arboretum/web` (the Vue 3 SPA), and `git-arboretum` (the VS Code extension, built separately with `npm run build:vscode`).
```bash
npm run build # build shared → server → web (order matters)
@@ -272,8 +409,25 @@ node packages/server/scripts/acceptance-p2.mjs # session discovery & resume
node packages/server/scripts/acceptance-p3.mjs # worktrees & session correlation
node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` command
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
node packages/server/scripts/acceptance-p7.mjs # git engine, file API & real-time FS watcher
node packages/server/scripts/acceptance-p8.mjs # workspace IDE: changes / diff / staging / commit
node packages/server/scripts/acceptance-p9.mjs # advanced commit/push: selective staging, amend, fetch/pull
node packages/server/scripts/acceptance-p10.mjs # automatic session archival
node packages/server/scripts/acceptance-p11.mjs # real-time settings sync
node packages/server/scripts/acceptance-p12.mjs # remote git services + HTTPS clone
node packages/server/scripts/acceptance-p13.mjs # start the project: launch commands & multi-terminal
node packages/server/scripts/acceptance-p14.mjs # armed real-time: session-pinned watcher, cwd correlation
node packages/server/scripts/acceptance-p15.mjs # history: commit log & per-commit diff
```
Rendering check (headless Chromium over CDP, no Playwright): after `npm run build`, run
`node packages/server/scripts/copy-web.mjs` then
`node packages/server/scripts/verify-ui.mjs [outdir]`. It starts an isolated daemon, seeds a demo repo,
and writes screenshots of the IDE in both themes at desktop and mobile widths, failing on any console
error.
The protocol grew (additively, no version bump) to carry the new surface: client `watch` / `unwatch` messages and the targeted `worktree_changes` signal (P7), plus `session_archived` (P10), `settings_update` (P11) and `clone_update` (P12) broadcasts. Server-side, the work is backed by `core/git.ts` (the pure git engine), `core/fs-watcher.ts` (chokidar), `core/git-credentials.ts` + `core/clone-manager.ts` (encrypted credentials & clone), and the session-archive and settings services.
## Support
Arboretum is a free, self-funded side project. If it saves you time, you can support its development:
@@ -282,4 +436,4 @@ Arboretum is a free, self-funded side project. If it saves you time, you can sup
## License
MIT — see [LICENSE](LICENSE).
MIT, see [LICENSE](LICENSE).
+5 -5
View File
@@ -1,7 +1,7 @@
# Security Policy
Arboretum is a self-hosted daemon that serves a web dashboard to drive git worktrees and the
Claude Code sessions running on them. **A web terminal is remote code execution by design** — that
Claude Code sessions running on them. **A web terminal is remote code execution by design**: that
is the product, not a bug. Arboretum's security model is therefore built on *structural* guards
(loopback-only binding, authenticated access, strict Origin checks) far more than on cryptography
alone.
@@ -13,7 +13,7 @@ environment, see [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md
## Threat model
- **Single-user by design.** Arboretum runs on the owner's machine and is meant for one operator.
There is no multi-tenant isolation and no RBAC — and none is claimed.
There is no multi-tenant isolation and no RBAC, and none is claimed.
- **Loopback by default.** The server binds `127.0.0.1`; `config.ts` *refuses* any non-loopback bind
unless you pass `--i-know-this-exposes-a-terminal`. Remote access is expected via **Tailscale Serve**
(TLS + tailnet identity), never by opening a port.
@@ -31,7 +31,7 @@ environment, see [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md
| Sessions | Cookie is an HMAC-SHA256 signed payload, `HttpOnly` + `SameSite=Strict`, `Secure` when HTTPS | `packages/server/src/routes/auth.ts` |
| CSRF / WS | Strict `Origin` check on every `/api/**` and `/ws` request (anti cross-site WS hijacking) | `packages/server/src/app.ts` |
| CSRF | Mutations carrying a body must be `application/json` | `packages/server/src/app.ts` |
| Rate limit | Global login rate limit with exponential backoff (not per-IP — Tailscale fronts everything as 127.0.0.1) | `packages/server/src/auth/service.ts` |
| Rate limit | Global login rate limit with exponential backoff (not per-IP, Tailscale fronts everything as 127.0.0.1) | `packages/server/src/auth/service.ts` |
| HTTP headers | CSP, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy`, `Permissions-Policy`, conditional HSTS, `Cache-Control: no-store` on API; `Server` header stripped | `packages/server/src/app.ts` |
| Injection | All SQL is parameterized; all git calls use `execFile` (no shell); path-traversal guards | `packages/server/src/**` |
| Data at rest | DB file/dir forced to `0o600`/`0o700`; sensitive secrets (server secret, VAPID private key) encrypted with AES-256-GCM | `packages/server/src/db/index.ts`, `core/secret-box.ts` |
@@ -44,7 +44,7 @@ environment, see [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md
- **Long-lived API tokens.** Tokens do not expire by age (CLI automation stability) but can be revoked
instantly, and `last_used_at` is tracked. Review and rotate tokens periodically.
- **Encryption-at-rest key management.** With no `ARBORETUM_SECRET_KEY` set, the encryption key lives in
`dataDir/secret.key` (`0o600`) next to the database — this protects a leaked database *copy* (backup,
`dataDir/secret.key` (`0o600`) next to the database: this protects a leaked database *copy* (backup,
WAL) but not a full `dataDir` compromise. For strong protection, set `ARBORETUM_SECRET_KEY` and store it
separately from database backups. Full-DB SQLCipher is intentionally avoided (it breaks the `npx`
prebuilt portability).
@@ -52,7 +52,7 @@ environment, see [`docs/ENTERPRISE_DEPLOYMENT.md`](docs/ENTERPRISE_DEPLOYMENT.md
## Reporting a vulnerability
Please report security issues **privately** — do not open a public issue.
Please report security issues **privately**: do not open a public issue.
- Email: **security@johanleroy.fr** (or `contact@johanleroy.fr`).
- Include a description, affected version, and reproduction steps.
+7 -7
View File
@@ -7,8 +7,8 @@ branches, cyan session nodes, a `>_` prompt at the base) on a dark background.
| --- | --- |
| `arboretum-logo-source.png` | Master artwork (opaque dark background). Keep; everything else derives from it. |
| `arboretum-logo.png` | Full logo, **transparent**. Best on dark surfaces (the wordmark is light). |
| `arboretum-logo-on-dark.png` | Full logo on the app background `#09090b`. Safe on any theme — used in the README. |
| `arboretum-mark.png` | Square, **transparent**, tree only (no wordmark). Ideal **Gitea repo avatar** — reads on both light and dark. |
| `arboretum-logo-on-dark.png` | Full logo on a dark backdrop (`#09090b`, the app's dark theme; the UI now also ships a light theme on `#fafafa`). Safe on any theme, used in the README. |
| `arboretum-mark.png` | Square, **transparent**, tree only (no wordmark). Ideal **Gitea repo avatar**, reads on both light and dark. |
The transparent versions are extracted by luminance (alpha ∝ brightness), the clean
way to lift glow-on-black artwork: the dark background becomes fully transparent, the
@@ -26,11 +26,11 @@ when the surrounding background might be light.
The web-facing assets live in `packages/web/public/` and are wired into the SPA:
- `icon.svg` — scalable favicon, redrawn to match the brand (vector, glow, `>_`).
- `icon-192.png` / `icon-512.png` — maskable PWA icons (tree on `#09090b`, content in the safe zone).
- `apple-touch-icon.png` — iOS home-screen icon (180×180).
- `favicon.ico` — multi-size favicon (16/32/48), transparent.
- `logo.png` — transparent full logo for in-app use.
- `icon.svg`: scalable favicon, redrawn to match the brand (vector, glow, `>_`).
- `icon-192.png` / `icon-512.png`: maskable PWA icons (tree on `#09090b`, content in the safe zone).
- `apple-touch-icon.png`: iOS home-screen icon (180×180).
- `favicon.ico`: multi-size favicon (16/32/48), transparent.
- `logo.png`: transparent full logo for in-app use.
## Regenerate
+46 -4
View File
@@ -5,26 +5,34 @@ Source : un PNG « néon sur fond sombre » (arbre-circuit + texte « Arboretum
On extrait l'alpha par luminance (méthode propre pour ce type d'artwork glow-on-black) :
chaque pixel reçoit une transparence proportionnelle à sa luminosité, ce qui rend le
fond sombre totalement transparent, garde le cœur des traits opaque et conserve le halo
en semi-transparent — donc lisible sur n'importe quel fond.
en semi-transparent, donc lisible sur n'importe quel fond.
Sorties :
brand/arboretum-logo.png logo complet transparent (haute déf) — Gitea / README
brand/arboretum-mark.png marque carrée transparente (arbre seul) — avatar Gitea
brand/arboretum-logo.png logo complet transparent (haute déf) : Gitea / README
brand/arboretum-mark.png marque carrée transparente (arbre seul) : avatar Gitea
brand/arboretum-logo-on-dark.png logo complet sur fond #09090b (fallback fond clair)
packages/web/public/logo.png logo complet transparent, optimisé pour l'UI
packages/web/public/icon-192.png icône PWA maskable (arbre, fond #09090b)
packages/web/public/icon-512.png icône PWA maskable (arbre, fond #09090b)
packages/web/public/apple-touch-icon.png icône iOS 180 (arbre, fond #09090b)
packages/web/public/favicon.ico favicon transparent (arbre, 16/32/48)
packages/web/public/screenshot-ide-{dark,light}.png captures du manifeste PWA (copiées de brand/)
packages/desktop/resources/icon.png source 1024 (electron-builder : macOS + dérivations)
packages/desktop/resources/icon.ico icône Windows multi-tailles (NSIS + fenêtre)
packages/desktop/resources/icons/NNxNN.png jeu Linux aux TAILLES STANDARD hicolor
packages/desktop/resources/trayTemplate.png (+@2x) icône de barre de menus macOS (monochrome)
packages/vscode/media/icon.png icône du VSIX (128, requise par tout marketplace)
Usage : python3 brand/build-assets.py <source.png>
"""
import os
import shutil
import sys
import numpy as np
from PIL import Image
SRC = sys.argv[1] if len(sys.argv) > 1 else "brand/arboretum-logo-source.png"
BG = (9, 9, 11) # #09090b — couleur de fond du dashboard (manifest background_color/theme_color)
BG = (9, 9, 11) # #09090b : couleur de fond du dashboard (manifest background_color/theme_color)
# Découpe verticale arbre / texte (mesurée sur la source)
TREE_Y = (130, 930) # arbre + curseur >_
@@ -94,6 +102,40 @@ def main():
fav = square(tree, 0.04)
fav.save("packages/web/public/favicon.ico", sizes=[(16, 16), (32, 32), (48, 48)])
print(" packages/web/public/favicon.ico 16/32/48")
# captures utilisées par le manifeste PWA (installation enrichie Chrome/Edge)
for theme in ("dark", "light"):
src = f"brand/screenshot-ide-{theme}.png"
if os.path.exists(src):
shutil.copyfile(src, f"packages/web/public/screenshot-ide-{theme}.png")
print(f" packages/web/public/screenshot-ide-{theme}.png (copié)")
# --- app de bureau -------------------------------------------------------------------
# electron-builder n'invente RIEN pour Linux : sans un dossier d'icônes aux tailles standard
# hicolor, il installe l'unique taille source (ex. 895x895), répertoire que la spécification
# freedesktop ignore → aucun logo au lanceur. D'où la génération explicite ci-dessous.
print("packages/desktop/resources/")
os.makedirs("packages/desktop/resources/icons", exist_ok=True)
desk = square(tree, 0.08)
save(desk, "packages/desktop/resources/icon.png", 1024)
for size in (16, 24, 32, 48, 64, 128, 256, 512):
save(desk, f"packages/desktop/resources/icons/{size}x{size}.png", size)
desk.resize((256, 256), Image.LANCZOS).save(
"packages/desktop/resources/icon.ico", sizes=[(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (256, 256)]
)
print(" packages/desktop/resources/icon.ico 16→256")
# macOS : la barre de menus exige une image TEMPLATE (monochrome + alpha), sinon l'icône est
# illisible et ne suit pas le thème clair/sombre du système.
tpl = tree.copy()
tpl_alpha = tpl.getchannel("A")
template = Image.new("RGBA", tpl.size, (0, 0, 0, 0))
template.putalpha(tpl_alpha)
save(template, "packages/desktop/resources/trayTemplate.png", 16)
save(template, "packages/desktop/resources/trayTemplate@2x.png", 32)
# --- extension VS Code ---------------------------------------------------------------
print("packages/vscode/media/")
os.makedirs("packages/vscode/media", exist_ok=True)
save(square(tree, 0.10, bg=BG), "packages/vscode/media/icon.png", 128)
if __name__ == "__main__":
Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

+138
View File
@@ -0,0 +1,138 @@
# Runners Gitea Actions · ajouter Windows (et macOS)
Ce document explique comment activer le build **Windows** de l'app de bureau dans la CI. Il est écrit
pour être appliqué tel quel sur `git.lidge.fr` (Gitea 1.25).
## Pourquoi un runner Windows est obligatoire
Le cross-build Windows depuis Linux **ne peut pas fonctionner**, pour deux raisons vérifiées dans
`node_modules/@homebridge/node-pty-prebuilt-multiarch` :
1. `scripts/check-prebuild.js` sort en succès dès que le binaire de l'hôte existe, donc
`prebuild-install` n'est jamais appelé et aucun binaire `win32` n'est téléchargé (le tarball publié
ne contient que `prebuilds/linux-*`) ;
2. `scripts/post-install.js` ne copie `conpty.dll` et `OpenConsole.exe` **que si la plateforme de build
est win32**. Sans eux, pas de ConPTY, donc **aucun terminal** dans l'app.
Un build produit sous Wine serait donc installable mais inutilisable. C'est pour cela que
`packages/desktop/README.md` ne propose plus cette voie.
## État actuel
| Plateforme | Runner | Build |
|---|---|---|
| Linux | `ubuntu-latest` (déjà en place) | automatique à chaque tag `desktop-v*` |
| Windows | **à enregistrer** | job **retiré** du workflow ; manuel (`npm run dist:win` sur Windows) |
| macOS | aucun | manuel (`npm run dist:mac` sur un Mac) |
Le job Windows a d'abord été gardé dans le workflow, conditionné par
`if: vars.ENABLE_WINDOWS_BUILD == 'true'`. Cela **n'a pas suffi** : sans runner labellisé
`windows-latest`, la release entière tombait en erreur au lieu de sauter le job. Il est donc
**retiré** de `.gitea/workflows/desktop-release.yml`. Son dernier état complet est dans l'historique
git (tag `desktop-v0.2.3`) : après avoir enregistré le runner ci-dessous, restaurer ce job, puis
remettre dans `latest-channel` le `download-artifact` de `desktop-windows` ainsi que
`dl/*.exe dl/latest.yml` dans la liste d'assets du canal flottant.
## 1. Préparer la machine Windows
Prérequis (Windows 10 1809+ ou Windows 11, x64) :
- **Git pour Windows** (fournit aussi `bash`, utilisé par les étapes `shell: bash` du workflow) ;
- **Node.js 22.21.1** (même version que `NODE_VERSION` dans le workflow) ;
- rien d'autre : `node-pty` s'installe via des binaires précompilés, aucun compilateur C++ n'est requis.
Vérification rapide dans PowerShell :
```powershell
node --version # v22.21.1
git --version
bash --version # fourni par Git for Windows
```
## 2. Enregistrer le runner
Récupérer un jeton d'enregistrement dans Gitea : **Site Administration → Actions → Runners → Create new
runner** (jeton d'instance), ou au niveau du dépôt : **Settings → Actions → Runners**.
Puis, dans PowerShell (répertoire dédié, par exemple `C:\actions-runner`) :
```powershell
mkdir C:\actions-runner; cd C:\actions-runner
# Binaire act_runner pour Windows (adapter la version à celle de votre Gitea)
Invoke-WebRequest -Uri "https://gitea.com/gitea/act_runner/releases/download/v0.2.13/act_runner-0.2.13-windows-amd64.exe" -OutFile act_runner.exe
.\act_runner.exe register --no-interactive `
--instance https://git.lidge.fr `
--token <JETON_DENREGISTREMENT> `
--name windows-builder `
--labels windows-latest:host
```
Le label **`windows-latest:host`** est essentiel : `:host` signifie « exécuter directement sur la
machine », sans conteneur (il n'y a pas d'image Docker Windows utilisable ici), et `windows-latest` est
le nom attendu par `runs-on` dans le workflow.
Démarrage manuel pour un premier essai :
```powershell
.\act_runner.exe daemon
```
## 3. Exécuter le runner en service
Pour qu'il survive aux redémarrages, créer une tâche planifiée « à l'ouverture de session » (même
principe que `arboretum install` sur Windows) :
```powershell
schtasks /Create /TN "GiteaActRunner" /TR "C:\actions-runner\act_runner.exe daemon" `
/SC ONLOGON /RL LIMITED /F
schtasks /Run /TN "GiteaActRunner"
```
Alternative : [NSSM](https://nssm.cc/) pour un vrai service Windows, si le runner doit tourner sans
session ouverte. Attention : un service hors session n'a pas accès au profil utilisateur.
## 4. Activer le job dans la CI
Dans Gitea, sur le dépôt `johanleroy/arboretum` : **Settings → Actions → Variables → Add Variable**
| Nom | Valeur |
|---|---|
| `ENABLE_WINDOWS_BUILD` | `true` |
## 5. Vérifier sans créer de tag
Le workflow accepte `workflow_dispatch` : **Actions → Desktop Release → Run workflow**. Dans ce mode, le
garde-fou « tag == version » est ignoré et rien n'est attaché à une release ; les installeurs sont
récupérables dans les artefacts du run (`desktop-windows`).
Contrôles à faire sur l'installeur produit :
1. l'installeur NSIS s'exécute et propose le répertoire d'installation ;
2. l'app démarre et affiche l'IDE **sans écran de connexion** (le token passe par le descripteur 3 ;
c'est le point le plus susceptible de différer sur Windows, cf. `packages/desktop/src/main/daemon.ts`) ;
3. un terminal s'ouvre et répond (ConPTY présent) ;
4. le CLI `claude` est trouvé (sinon renseigner son chemin dans Réglages → Claude CLI) ;
5. « Démarrer le projet » lance bien les commandes sous PowerShell.
## 6. Signature de code
Aucun binaire n'est signé. SmartScreen affichera « éditeur inconnu » au premier lancement : choisir
« Informations complémentaires » puis « Exécuter quand même ». Pour signer plus tard, ajouter les
secrets `CSC_LINK` (certificat .pfx encodé en base64) et `CSC_KEY_PASSWORD` au dépôt : electron-builder
les utilise automatiquement, sans changement de workflow.
## Repli si aucun runner n'est possible
Sur une machine Windows, avec le dépôt cloné :
```powershell
npm ci
cd packages\desktop
npm ci
npm run dist:win
```
Puis attacher `packages\desktop\release\*.exe`, `latest.yml` et les `.blockmap` à la release
`desktop-vX.Y.Z` depuis l'interface Gitea. Le canal d'auto-update (`desktop-latest`) doit recevoir les
mêmes fichiers, sinon les utilisateurs Windows ne verront pas la mise à jour.
+10 -4
View File
@@ -3,6 +3,12 @@
This guide complements [`../SECURITY.md`](../SECURITY.md) with the operational steps a regulated or
security-conscious organization needs to deploy Arboretum with confidence.
> **Desktop app.** The Electron desktop app (`packages/desktop`) is an additive, self-contained
> client: it runs its own local daemon (child process) bound to `127.0.0.1` and shows the same web
> UI. It does not change the server deployment below; a shared or service daemon (systemd/launchd,
> reached over Tailscale Serve) is deployed exactly as described here, independently of whether
> developers also use the desktop app on their own machines.
## 1. Remote access: Tailscale Serve (recommended)
Never open a public port. Keep the default `127.0.0.1` bind and put Arboretum behind Tailscale Serve:
@@ -25,7 +31,7 @@ is **never** a deployment mode and is never injected automatically by `arboretum
## 2. Encryption at rest
Sensitive secrets (the HMAC server secret and the VAPID private key) are encrypted with AES-256-GCM
before being stored in SQLite. Token values are never stored — only their SHA-256 hashes.
before being stored in SQLite. Token values are never stored, only their SHA-256 hashes.
For **strong** protection (key not co-located with the database), provide a passphrase via the
environment instead of the on-disk key file:
@@ -64,7 +70,7 @@ curl -s -H "Authorization: Bearer $TOKEN" \
'http://127.0.0.1:7317/api/v1/audit-logs?limit=100'
```
The audit log never contains secret values — only non-sensitive metadata (ids, labels, counters). It is
The audit log never contains secret values, only non-sensitive metadata (ids, labels, counters). It is
also visible in the dashboard under **Settings → Security & compliance**.
## 5. GDPR (data subject requests)
@@ -72,14 +78,14 @@ also visible in the dashboard under **Settings → Security & compliance**.
- **Export**: `GET /api/v1/data/export` returns every record tied to the authenticated token (token
metadata, push subscriptions, session history, settings) as JSON. Also available as a one-click
download in **Settings → Security & compliance**.
- **Erasure**: `POST /api/v1/data/delete-my-data` is a two-step call — the first response returns a
- **Erasure**: `POST /api/v1/data/delete-my-data` is a two-step call: the first response returns a
`confirm` code that must be POSTed back to execute. It purges the token's push subscriptions and
revokes the token (unless it is the last active one).
## 6. Backups & retention
- Back up the SQLite database (`arboretum.db`) with the WAL checkpointed. Treat backups as sensitive.
- If you use `ARBORETUM_SECRET_KEY`, back the key up **separately** — a database backup is useless (and
- If you use `ARBORETUM_SECRET_KEY`, back the key up **separately**: a database backup is useless (and
safe) without it, which is the point.
- Session history is retained until the database is reset. To start clean, stop the service and remove
the database file.
+84 -10
View File
@@ -7,8 +7,13 @@
"": {
"name": "arboretum-monorepo",
"version": "0.0.0",
"license": "MIT",
"workspaces": [
"packages/*"
"packages/shared",
"packages/server",
"packages/web",
"packages/site",
"packages/vscode"
],
"devDependencies": {
"@types/node": "^22.10.0",
@@ -975,11 +980,19 @@
"ws": "^8.16.0"
}
},
"node_modules/@fontsource/jetbrains-mono": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource/jetbrains-mono/-/jetbrains-mono-5.2.8.tgz",
"integrity": "sha512-6w8/SG4kqvIMu7xd7wt6x3idn1Qux3p9N62s6G3rfldOUYHpWcc2FKrqf+Vo44jRvqWj2oAtTHrZXEP23oSKwQ==",
"dev": true,
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/jetbrains-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
"integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
@@ -3548,6 +3561,21 @@
"url": "https://github.com/sponsors/fb55"
}
},
"node_modules/chokidar": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
"license": "MIT",
"dependencies": {
"readdirp": "^4.0.1"
},
"engines": {
"node": ">= 14.16.0"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/chownr": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
@@ -3871,6 +3899,12 @@
"url": "https://github.com/fb55/domhandler?sponsor=1"
}
},
"node_modules/dompurify": {
"version": "3.1.7",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.7.tgz",
"integrity": "sha512-VaTstWtsneJY8xzy7DekmYWEOZcmzIe3Qb3zPd4STve1OBTa+e+WmS1ITQec1fZYXI3HCsOZZiSMpG6oxoWMWQ==",
"license": "(MPL-2.0 OR Apache-2.0)"
},
"node_modules/domutils": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
@@ -5497,6 +5531,18 @@
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/marked": {
"version": "14.0.0",
"resolved": "https://registry.npmjs.org/marked/-/marked-14.0.0.tgz",
"integrity": "sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==",
"license": "MIT",
"bin": {
"marked": "bin/marked.js"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@@ -5649,6 +5695,16 @@
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
"license": "MIT"
},
"node_modules/monaco-editor": {
"version": "0.54.0",
"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.54.0.tgz",
"integrity": "sha512-hx45SEUoLatgWxHKCmlLJH81xBo0uXP4sRkESUpmDQevfi+e7K1VuiSprK6UpQ8u4zOcKNiH0pMvHvlMWA/4cw==",
"license": "MIT",
"dependencies": {
"dompurify": "3.1.7",
"marked": "14.0.0"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -6302,6 +6358,19 @@
"node": ">= 6"
}
},
"node_modules/readdirp": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
"license": "MIT",
"engines": {
"node": ">= 14.18.0"
},
"funding": {
"type": "individual",
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/real-require": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
@@ -7864,7 +7933,7 @@
},
"packages/server": {
"name": "@johanleroy/git-arboretum",
"version": "1.9.0",
"version": "3.7.1",
"license": "MIT",
"dependencies": {
"@fastify/cookie": "^11.0.0",
@@ -7872,6 +7941,7 @@
"@fastify/websocket": "^11.0.0",
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
"@xterm/headless": "^6.0.0",
"chokidar": "^4.0.3",
"fastify": "^5.0.0",
"web-push": "^3.6.7"
},
@@ -7897,13 +7967,14 @@
},
"packages/site": {
"name": "@arboretum/site",
"version": "0.1.0",
"version": "0.4.0",
"dependencies": {
"vue": "^3.5.38",
"vue-i18n": "^11.4.5"
},
"devDependencies": {
"@fontsource/jetbrains-mono": "^5.1.0",
"@fontsource-variable/inter": "^5.0.0",
"@fontsource-variable/jetbrains-mono": "^5.0.0",
"@tailwindcss/vite": "^4.3.0",
"@vitejs/plugin-vue": "^6.0.7",
"tailwindcss": "^4.3.0",
@@ -7992,7 +8063,7 @@
},
"packages/vscode": {
"name": "git-arboretum",
"version": "0.1.0",
"version": "0.4.1",
"license": "MIT",
"devDependencies": {
"@arboretum/shared": "0.1.0",
@@ -8443,10 +8514,13 @@
"version": "0.1.0",
"dependencies": {
"@arboretum/shared": "*",
"@fontsource-variable/inter": "^5.0.0",
"@fontsource-variable/jetbrains-mono": "^5.0.0",
"@lucide/vue": "^1.21.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-webgl": "^0.19.0",
"@xterm/xterm": "^6.0.0",
"monaco-editor": "^0.54.0",
"pinia": "^3.0.4",
"vue": "^3.5.38",
"vue-i18n": "^11.4.5",
+10 -2
View File
@@ -2,9 +2,15 @@
"name": "arboretum-monorepo",
"private": true,
"version": "0.0.0",
"license": "MIT",
"author": "Johan LEROY <contact@johanleroy.fr>",
"type": "module",
"workspaces": [
"packages/*"
"packages/shared",
"packages/server",
"packages/web",
"packages/site",
"packages/vscode"
],
"engines": {
"node": ">=22.16"
@@ -20,7 +26,9 @@
"dev:site": "npm run dev -w @arboretum/site",
"preview:site": "npm run preview -w @arboretum/site",
"build:vscode": "npm run build -w @arboretum/shared -w git-arboretum",
"dev:vscode": "npm run dev -w git-arboretum"
"dev:vscode": "npm run dev -w git-arboretum",
"typecheck:desktop": "npm --prefix packages/desktop run typecheck",
"build:desktop": "npm --prefix packages/desktop run build"
},
"devDependencies": {
"@types/node": "^22.10.0",
+4
View File
@@ -0,0 +1,4 @@
node_modules/
dist/
build/
release/
+122
View File
@@ -0,0 +1,122 @@
# 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.5
Ships the daemon 3.7.1, and finishes the job started in 0.2.4: an update installed while the app runs
now applies **itself**.
- **The restart after an update no longer needs you.** 0.2.4 detected that the binary had been
replaced and offered a *Restart now* dialog. That still made the user do the work. The app now
restarts on its own when it costs nothing, which is the common case, and only asks when there is
something to lose: the dialog appears when live sessions would be interrupted (it says how many),
or when the daemon cannot be reached to find out. A previous *Later* is final for that version, so
nothing ever restarts behind your back.
- **The update is now noticed while the window is open.** Detection used to run only when the window
was re-shown (tray, Dock, second launch), so an update installed during a working session could go
unnoticed indefinitely. A cheap `stat` every 30 s covers it, by polling rather than `fs.watch`,
because a package replacing the binary or a whole directory often produces no watch event at all.
## 0.2.4
Ships the daemon 3.7.0: terminals no longer go black, they can sit side by side in resizable columns,
and the Changes view follows the terminal you are working in. This release also carries the start-up
fixes below, which is what makes an update installed over a running app recover on its own.
- **The app could refuse to start after an update, silently.** Installing a new version replaces the
files on disk but leaves the running app alone: its daemon kept port 7317, so the version you just
installed hit `EADDRINUSE`, its daemon died before the handshake, and the shell logged the failure to a
console nobody sees and quit. Clicking the launcher appeared to do nothing at all. Three fixes:
- **Every start-up failure now opens a dialog** with *Retry / Show log / Quit* instead of vanishing,
and the daemon's output is kept in `<userData>/logs/daemon.log`. A daemon that dies *after* start-up
is reported too, with an offer to restart it, instead of leaving a dead window on screen.
- **A busy port is diagnosed, not just fatal** (`src/main/port-guard.ts`). The daemon we spawn is
recorded in `<userData>/daemon/daemon.json`, so an *orphaned* daemon (its Electron gone after a
crash, a `kill -9` or an upgrade) is reclaimed - SIGTERM then SIGKILL, waiting for the port to be
effectively free - while a live sibling instance or third-party server is reported with the action
that unblocks it, and never killed.
- **An update installed while the app runs is announced** (`src/main/upgrade-watch.ts`). Until now the
single-instance lock quietly routed you back to the old version's window; the shell now notices its
own binary changed on disk and offers *Restart now*, which stops the daemon before relaunching.
- **`ARBORETUM_DESKTOP_PORT`** picks another port, for machines where a service or terminal daemon owns
7317 permanently.
## 0.2.3
Ships the daemon 3.6.0. Files open again (the editor area could stay blank), and uncommitted work
gets a real surface in the centre of the IDE: one block per project, with staging, commit and push.
The Electron shell itself is unchanged.
## 0.2.2
- **Clipboard bridge.** The renderer cannot use `navigator.clipboard` (Electron rejects it with
`NotAllowedError`), so copying a terminal selection did nothing in the app even after 0.2.1. The
preload now exposes `arboretumDesktop.clipboard`, relaying to Electron's `clipboard` module over IPC
(read and write, writes capped at 1M chars). Ships the daemon 3.5.1, whose SPA uses that bridge first.
## 0.2.1
Ships the daemon 3.5.0, which fixes the black window seen after updating the app.
- **Black window after an update, fixed.** The window loaded an `index.html` kept from the previous
version (revalidated as `304` because the tarball mtime is constant, so the etag did not change) whose
`/assets/<hash>` files no longer existed. Nothing painted. If you hit it before updating, the app
repairs itself now; clearing `~/.config/Arboretum/Partitions/arboretum/Cache` was the manual fix.
- **Copy & paste in session terminals.** `Ctrl+Shift+C` / `Ctrl+Shift+V` (`Cmd+C` / `Cmd+V` on macOS);
the Edit menu's Copy also works on a terminal selection now. `Ctrl+C` still interrupts.
- Browse the files of a group's worktrees straight from the Groups panel.
The Electron shell itself is unchanged.
## 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.
+155
View File
@@ -0,0 +1,155 @@
# Arboretum Desktop
Native desktop shell (Electron) for Arboretum. It runs the existing daemon as a child process and
shows its web UI in a window, already authenticated (no login screen). The heavy lifting stays in
the daemon; this package is a thin shell (window lifecycle, daemon supervision, auto auth).
This package is intentionally **outside the root npm workspaces** so the daemon CI stays light. It
has its own `package-lock.json` and is built on a developer machine (or a dedicated CI runner),
not by the main `npm run build`.
## How it works
1. The shell picks a data directory under the OS user-data path and spawns the bundled Node runtime
running the packaged daemon (`build/server/package/dist/index.js`) with `ARBORETUM_EMIT_TOKEN_FD=3`.
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 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.
## Prerequisites (all platforms)
- Node >= 22.16 to build.
- `git` on PATH at runtime (worktree operations). `claude` is discovered on PATH or via the
in-app Claude CLI setting; it is not bundled.
## Develop
```bash
cd packages/desktop
npm install # ELECTRON_SKIP_BINARY_DOWNLOAD=1 to skip the Electron binary if you only typecheck
npm run dev # bundles main/preload, then `electron .` against the repo's built daemon
```
`npm run dev` runs the daemon from the repo (`packages/server/dist`, so run `npm run build` at the
repo root first) using the system `node`.
## Build installers
Each command builds the shell, prepares the daemon (`npm pack` + runtime deps with the right
`node-pty` prebuild) and a standalone Node runtime, then runs electron-builder.
```bash
npm run dist:linux # AppImage + .deb (on Linux)
npm run dist:win # NSIS + portable (on Windows)
npm run dist:mac # dmg + zip (on macOS)
```
Artifacts land in `packages/desktop/release/`.
### Linux
Fully supported. `dist:linux` runs on a Linux host or the Gitea CI runner.
### Windows
**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); 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.
## Startup, and what happens when it fails
The shell owns the daemon: it spawns it on **port 7317** (`ARBORETUM_DESKTOP_PORT` overrides), waits for
the handshake on fd 3, seeds the session cookie, then loads the SPA. Since a fixed port is easy to hold
hostage, the port is checked *before* spawning (`src/main/port-guard.ts`) and the outcome decides:
| Who holds the port | What the app does |
| --- | --- |
| Nobody | Starts normally. |
| **Our own daemon, orphaned** (its Electron died: crash, `kill -9`, package upgrade) | Reclaims it: SIGTERM, then SIGKILL, waiting for the port to be *effectively* free, then starts. |
| **Another live instance** of the app | Says so, and points at the tray where that window is hiding. Never kills it. |
| A third party (`arboretum install` service, `npx @johanleroy/git-arboretum`, unrelated software) | Says so, and suggests stopping it or setting `ARBORETUM_DESKTOP_PORT`. |
Ownership is recorded in `<userData>/daemon/daemon.json` (`{pid, ownerPid, port}`): a live daemon whose
`ownerPid` is gone is an orphan, one whose owner is alive is another instance. Every failure now opens a
dialog with **Retry / Show log / Quit** instead of quitting silently, and the daemon's output is kept in
`<userData>/logs/daemon.log`. If the daemon dies *after* startup, the app offers to restart it rather
than leaving a dead window on screen.
`<userData>` is `~/.config/Arboretum` (Linux), `~/Library/Application Support/Arboretum` (macOS),
`%APPDATA%\Arboretum` (Windows).
## Installing a new version
Installers replace the files on disk; they never touch the running process. So after a `dpkg -i` (or an
NSIS run) **the open window keeps serving the old version**, and its daemon keeps port 7317 - which used
to make the freshly installed version unable to start at all.
The recommended order is therefore either one of:
1. Quit Arboretum from the tray, then install, then launch. Clean, nothing to think about.
2. Install while it runs, then click the launcher or the tray icon: the shell notices that its own
binary changed on disk (`src/main/upgrade-watch.ts`) and offers **Restart now**, which stops the
daemon before relaunching, so the new version finds its port free.
Answering *Later* keeps the old window; the prompt comes back only if yet another version is installed.
The check is inert in dev (`app.isPackaged` is false).
## Auto-update
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.
## Bundled Node runtime
`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.
+118
View File
@@ -0,0 +1,118 @@
appId: fr.lidge.arboretum
productName: Arboretum
copyright: Copyright © 2026 Johan Leroy
directories:
output: release
buildResources: resources
# Le bundle esbuild (dist/) va dans l'ASAR ; le daemon et le runtime Node restent des fichiers
# reels sur disque (extraResources, hors ASAR) : les binaires natifs (.node de node-pty) se
# chargent proprement, ce qu'un .asar interdirait.
files:
- dist/**/*
- "!**/*.map"
asar: true
extraResources:
- from: build/server
to: server
- from: build/node
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ô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
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:
- target: nsis
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}
# Le build portable produit lui aussi un .exe : sans nom distinct, il entrerait en collision avec
# l'installeur NSIS (les deux cibles héritent de `win.artifactName`) et l'un écraserait l'autre.
portable:
artifactName: ${productName}-${version}-${arch}-portable.${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) : 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
+24
View File
@@ -0,0 +1,24 @@
// Bundle du process principal + preload en CJS (comme l'extension VS Code). `electron` reste
// externe (fourni par le runtime Electron) ; les modules node natifs sont externes par platform:node.
import esbuild from 'esbuild';
const watch = process.argv.includes('--watch');
const options = {
entryPoints: { main: 'src/main/main.ts', preload: 'src/preload/preload.ts' },
outdir: 'dist',
bundle: true,
platform: 'node',
format: 'cjs',
target: 'node18',
sourcemap: true,
external: ['electron'],
logLevel: 'info',
};
if (watch) {
const ctx = await esbuild.context(options);
await ctx.watch();
} else {
await esbuild.build(options);
}
+5836
View File
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
{
"name": "@arboretum/desktop",
"private": true,
"version": "0.2.5",
"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",
"email": "contact@johanleroy.fr"
},
"main": "dist/main.js",
"type": "commonjs",
"scripts": {
"typecheck": "tsc -p . --noEmit",
"build": "npm run typecheck && node esbuild.mjs",
"dev": "node esbuild.mjs && electron .",
"prepare:server": "node scripts/prepare-server.mjs",
"prepare:node": "node scripts/fetch-node.mjs",
"dist:linux": "npm run build && npm run prepare:server -- --platform=linux && npm run prepare:node -- --platform=linux && electron-builder --linux",
"dist:win": "npm run build && npm run prepare:server -- --platform=win32 && npm run prepare:node -- --platform=win32 && electron-builder --win",
"dist:mac": "npm run build && npm run prepare:server -- --platform=darwin && npm run prepare:node -- --platform=darwin && electron-builder --mac"
},
"devDependencies": {
"@types/node": "^22.10.0",
"electron": "^33.0.0",
"electron-builder": "^25.1.0",
"electron-updater": "^6.3.0",
"esbuild": "^0.21.0",
"typescript": "^5.7.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

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

+85
View File
@@ -0,0 +1,85 @@
// Télécharge un runtime Node standalone (>= 22.16, épinglé) dans build/node, avec vérification
// 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 { 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';
const NODE_VERSION = '22.21.1';
const HERE = dirname(fileURLToPath(import.meta.url));
const BUILD = join(HERE, '..', 'build');
const NODE_DIR = join(BUILD, 'node');
const args = process.argv.slice(2);
const arg = (name, def) => args.find((a) => a.startsWith(`--${name}=`))?.split('=')[1] ?? def;
const platform = arg('platform', process.platform);
const arch = arg('arch', process.arch);
const OS = { linux: 'linux', darwin: 'darwin', win32: 'win' }[platform];
if (!OS) throw new Error(`plateforme non supportee: ${platform}`);
const ext = platform === 'win32' ? 'zip' : 'tar.xz';
const name = `node-v${NODE_VERSION}-${OS}-${arch}`;
const base = `https://nodejs.org/dist/v${NODE_VERSION}`;
async function get(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`);
return res;
}
rmSync(NODE_DIR, { recursive: true, force: true });
mkdirSync(NODE_DIR, { recursive: true });
const tarball = Buffer.from(await (await get(`${base}/${name}.${ext}`)).arrayBuffer());
const shasums = await (await get(`${base}/SHASUMS256.txt`)).text();
const expected = shasums.split('\n').find((l) => l.endsWith(`${name}.${ext}`))?.split(/\s+/)[0];
const actual = createHash('sha256').update(tarball).digest('hex');
if (!expected) throw new Error(`SHA introuvable pour ${name}.${ext}`);
if (expected !== actual) throw new Error(`SHA256 mismatch pour ${name}.${ext}`);
const archive = join(BUILD, `${name}.${ext}`);
writeFileSync(archive, tarball);
// `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' });
// 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);
}
@@ -0,0 +1,60 @@
// Prépare le daemon pour l'empaquetage Electron : réutilise INTÉGRALEMENT le pipeline npm du paquet
// publié (hooks prepack copy-web / inline-shared / copy-meta), donc aucune divergence de code.
// 1) build (shared + server + web) puis `npm pack` -> tarball 100 % autonome
// 2) extraction dans build/server/package
// 3) `npm install --omit=dev` -> deps runtime (node-pty avec le prebuild de la plateforme cible)
// Options : --platform=win32|darwin|linux et --arch=x64|arm64 pour un prebuild node-pty croisé
// (via npm_config_platform / npm_config_arch au moment du npm install).
import { execFileSync } from 'node:child_process';
import { mkdirSync, rmSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
const DESKTOP = join(HERE, '..');
const REPO = join(DESKTOP, '..', '..');
const SERVER_DIR = join(DESKTOP, 'build', 'server');
const args = process.argv.slice(2);
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(winShim(cmd), cmdArgs, { cwd, stdio: 'inherit', env: { ...process.env, ...env } });
rmSync(SERVER_DIR, { recursive: true, force: true });
mkdirSync(SERVER_DIR, { recursive: true });
// 1) build + pack (le tarball embarque dist + _shared inliné + public via prepack).
// Rebuild FORCÉ de shared+server : le prepack (inline-shared) mute le dist du serveur en place
// (imports réécrits vers ./_shared) ; un tsc -b incrémental ne le régénère pas au run suivant,
// d'où un pack qui échoue. --force garantit un dist propre à imports bare avant chaque pack.
run('npx', ['tsc', '-b', '--force', 'packages/shared', 'packages/server'], REPO);
run('npm', ['run', 'build', '-w', '@arboretum/web'], REPO);
run('npm', ['pack', '-w', '@johanleroy/git-arboretum', '--pack-destination', SERVER_DIR], REPO);
// 2) extraire le tarball -> build/server/package
const tgz = readdirSync(SERVER_DIR).find((f) => f.endsWith('.tgz'));
if (!tgz) throw new Error('tarball introuvable apres npm pack');
run('tar', ['-xzf', join(SERVER_DIR, tgz), '-C', SERVER_DIR]);
rmSync(join(SERVER_DIR, tgz));
// 3) deps runtime (node-pty prebuild). Cross-compile via npm_config_platform/arch si demandé.
const pkgDir = join(SERVER_DIR, 'package');
// Retirer les devDependencies du paquet extrait : inutiles au runtime, et @arboretum/shared
// (workspace non publié, déjà inliné dans dist/_shared) n'existe sur aucun registre -> 404.
const pkgJsonPath = join(pkgDir, 'package.json');
const pj = JSON.parse(readFileSync(pkgJsonPath, 'utf8'));
delete pj.devDependencies;
writeFileSync(pkgJsonPath, `${JSON.stringify(pj, null, 2)}\n`);
const env = {};
if (platform) env.npm_config_platform = platform;
if (arch) env.npm_config_arch = arch;
run('npm', ['install', '--omit=dev', '--no-audit', '--no-fund'], pkgDir, env);
console.log(`prepare-server: build/server/package pret${platform ? ` (${platform}-${arch ?? 'host'})` : ''}`);
+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',
});
}
+16
View File
@@ -0,0 +1,16 @@
import { session } from 'electron';
/**
* Pose le cookie de session dans la partition du renderer, sans écran de login : login
* server-to-server depuis la session Electron cible (le Set-Cookie atterrit dans son jar), avec le
* token frais reçu au handshake. Le token ne transite jamais par le renderer.
*/
export async function seedSessionCookie(partition: string, url: string, token: string): Promise<void> {
const ses = session.fromPartition(partition);
const res = await ses.fetch(`${url}/api/v1/auth/login`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token }),
});
if (!res.ok) throw new Error(`daemon login failed (HTTP ${res.status})`);
}
+44
View File
@@ -0,0 +1,44 @@
import { app } from 'electron';
import { existsSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';
// Lancement au login. Windows/macOS : API Electron (login items). Linux : fichier .desktop dans
// ~/.config/autostart (pas d'API Electron fiable pour l'autostart Linux).
function desktopFile(): string {
return join(homedir(), '.config', 'autostart', 'arboretum.desktop');
}
function desktopEntry(): string {
const exec = process.env.APPIMAGE ?? app.getPath('exe');
return `[Desktop Entry]
Type=Application
Name=Arboretum
Exec=${exec}
Terminal=false
X-GNOME-Autostart-enabled=true
`;
}
export function isAutoStartEnabled(): boolean {
if (process.platform === 'linux') return existsSync(desktopFile());
return app.getLoginItemSettings().openAtLogin;
}
export function setAutoStart(enabled: boolean): void {
if (process.platform === 'linux') {
if (enabled) {
mkdirSync(dirname(desktopFile()), { recursive: true });
writeFileSync(desktopFile(), desktopEntry());
} else {
try {
unlinkSync(desktopFile());
} catch {
/* déjà absent */
}
}
return;
}
app.setLoginItemSettings({ openAtLogin: enabled });
}
+23
View File
@@ -0,0 +1,23 @@
import { clipboard, ipcMain } from 'electron';
import { CLIPBOARD_READ, CLIPBOARD_WRITE } from '../shared/ipc';
// Pont presse-papier pour le renderer.
//
// Pourquoi il est nécessaire : dans Electron, `navigator.clipboard.writeText` ET `readText`
// échouent en `NotAllowedError` (vérifié dans l'app packagée). La SPA ne pouvait donc PAS copier
// la sélection d'un terminal, alors que la même page y arrive dans un navigateur. Le module
// `clipboard` n'étant pas exposé aux preloads sandboxés, on passe par IPC.
//
// Portée : l'app charge exclusivement sa propre SPA locale servie par son daemon, et un terminal
// web est déjà de l'exécution de code par conception : le presse-papier n'élargit pas la surface.
// On borne quand même la taille écrite pour qu'une boucle accidentelle ne remplisse pas la mémoire.
const MAX_WRITE_CHARS = 1_000_000;
export function registerClipboardBridge(): void {
ipcMain.handle(CLIPBOARD_READ, () => clipboard.readText());
ipcMain.handle(CLIPBOARD_WRITE, (_event, text: unknown) => {
if (typeof text !== 'string' || text.length === 0) return false;
clipboard.writeText(text.slice(0, MAX_WRITE_CHARS));
return true;
});
}
+191
View File
@@ -0,0 +1,191 @@
import { spawn, type ChildProcess } from 'node:child_process';
import { createWriteStream, mkdirSync, statSync, truncateSync, type WriteStream } from 'node:fs';
import { dirname, join } from 'node:path';
import { resolveNodeBin, resolveServerEntry } from './paths';
import { buildChildEnv } from './env';
import {
classifyPortConflict,
clearDaemonRecord,
isOurDaemonProcess,
isPortFree,
processAlive,
readDaemonRecord,
reclaimOrphanDaemon,
writeDaemonRecord,
} from './port-guard';
import { DaemonStartError } from './start-failure';
const HANDSHAKE_TIMEOUT_MS = 30_000;
/** Lignes de sortie conservées pour le diagnostic affiché en cas d'échec. */
const LOG_TAIL_LINES = 40;
/** Au-delà, le journal est tronqué au démarrage (fichier de dépannage, pas d'archive). */
const MAX_LOG_BYTES = 2_000_000;
export interface DaemonHandle {
url: string;
token: string;
/** Dernières lignes de sortie du daemon (diagnostic). */
logTail(): string;
stop(): Promise<void>;
}
interface Handshake {
token: string;
url: string;
}
export interface StartDaemonOptions {
dataDir: string;
port: number;
/** Empreinte du daemon lancé, pour récupérer un orphelin au démarrage suivant. */
pidfile?: string;
/** Journal persistant du daemon (dépannage hors terminal). */
logFile?: string;
onLog?: (line: string) => void;
/** Appelé si le daemon s'arrête APRÈS le handshake (mort inattendue). */
onExit?: (code: number | null) => void;
}
/**
* Lance le daemon en process enfant (Node bundlé) et attend son handshake sur le fd 3
* (ARBORETUM_EMIT_TOKEN_FD=3 côté serveur) : la réception du JSON {token,url} prouve que le
* serveur écoute (le handshake est écrit après app.listen). Arrêt propre : SIGTERM puis SIGKILL.
*
* Le port est vérifié AVANT le spawn : sans ça, un daemon resté seul après un crash ou une mise à
* jour rendait l'app définitivement inutilisable (EADDRINUSE, enfant mort, aucun message).
*/
export async function startDaemon(opts: StartDaemonOptions): Promise<DaemonHandle> {
const node = resolveNodeBin();
const entry = resolveServerEntry();
await ensurePortAvailable(opts.port, entry, opts.pidfile);
const dbPath = join(opts.dataDir, 'arboretum.db');
const env = buildChildEnv({ XDG_DATA_HOME: opts.dataDir, ARBORETUM_EMIT_TOKEN_FD: '3' });
const child: ChildProcess = spawn(node, [entry, '--port', String(opts.port), '--db', dbPath], {
env,
stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
});
const logSink = opts.logFile ? openLogFile(opts.logFile) : null;
const tail: string[] = [];
const collect = (chunk: Buffer): void => {
const text = chunk.toString();
opts.onLog?.(text);
logSink?.write(text);
for (const line of text.split('\n')) {
if (!line.trim()) continue;
tail.push(line);
if (tail.length > LOG_TAIL_LINES) tail.shift();
}
};
const logTail = (): string => tail.join('\n');
child.stdout?.on('data', collect);
child.stderr?.on('data', collect);
if (child.pid !== undefined && opts.pidfile) {
writeDaemonRecord(opts.pidfile, { pid: child.pid, ownerPid: process.pid, port: opts.port });
}
let stopped = false;
const stop = (): Promise<void> =>
new Promise((resolve) => {
const done = (): void => {
if (opts.pidfile) clearDaemonRecord(opts.pidfile);
logSink?.end();
resolve();
};
if (stopped || child.exitCode !== null) return done();
stopped = true;
const killTimer = setTimeout(() => child.kill('SIGKILL'), 3000);
child.once('exit', () => {
clearTimeout(killTimer);
done();
});
child.kill('SIGTERM');
});
return new Promise<DaemonHandle>((resolve, reject) => {
let buf = '';
let settled = false;
const fd3 = child.stdio[3] as NodeJS.ReadableStream | null;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
void stop();
reject(new DaemonStartError('handshake', 'daemon handshake timeout', logTail()));
}, HANDSHAKE_TIMEOUT_MS);
child.once('exit', (code) => {
if (settled) {
// Mort après le handshake : l'empreinte ne décrit plus rien de vivant.
if (opts.pidfile) clearDaemonRecord(opts.pidfile);
opts.onExit?.(code);
return;
}
settled = true;
clearTimeout(timer);
if (opts.pidfile) clearDaemonRecord(opts.pidfile);
logSink?.end();
// Course perdue entre la vérification du port et le bind du daemon : le motif reste « port pris »,
// pas un échec de handshake opaque.
const busy = /EADDRINUSE/.test(logTail());
reject(
busy
? new DaemonStartError('port-busy-foreign', `port ${opts.port} is already in use`, logTail())
: new DaemonStartError('handshake', `daemon exited before handshake (code ${code ?? 'null'})`, logTail()),
);
});
fd3?.on('data', (chunk: Buffer) => {
if (settled) return;
buf += chunk.toString();
const nl = buf.indexOf('\n');
if (nl < 0) return;
settled = true;
clearTimeout(timer);
try {
const hs = JSON.parse(buf.slice(0, nl)) as Handshake;
resolve({ url: hs.url, token: hs.token, logTail, stop });
} catch (err) {
void stop();
reject(new DaemonStartError('handshake', err instanceof Error ? err.message : String(err), logTail()));
}
});
});
}
/**
* Libère le port si l'occupant est un daemon à nous devenu orphelin ; sinon échoue avec un motif que
* le dialogue sait traduire en action (autre instance dans le tray, service, daemon en terminal).
*/
async function ensurePortAvailable(port: number, serverEntry: string, pidfile?: string): Promise<void> {
if (await isPortFree(port)) return;
const conflict = classifyPortConflict(pidfile ? readDaemonRecord(pidfile) : null, processAlive, port);
// La reprise exige DEUX preuves : l'empreinte désigne un daemon sans pilote, et le pid exécute
// effectivement notre serveur (un pid recyclé ne doit jamais être tué à sa place).
if (conflict.kind === 'orphan' && isOurDaemonProcess(conflict.pid, serverEntry)) {
// Daemon survivant à son Electron (crash, kill -9, paquet mis à jour) : plus personne ne le
// pilote et il tient la base ET le port. On le récupère au lieu de condamner l'app.
await reclaimOrphanDaemon(conflict.pid, port);
if (await isPortFree(port)) return;
}
throw new DaemonStartError(
conflict.kind === 'other-instance' ? 'port-busy-instance' : 'port-busy-foreign',
`port ${port} is already in use`,
);
}
function openLogFile(path: string): WriteStream | null {
try {
mkdirSync(dirname(path), { recursive: true });
const size = statSync(path, { throwIfNoEntry: false })?.size ?? 0;
if (size > MAX_LOG_BYTES) truncateSync(path, 0);
return createWriteStream(path, { flags: 'a' });
} catch {
return null; // un journal indisponible ne doit pas empêcher le démarrage
}
}
+35
View File
@@ -0,0 +1,35 @@
import { delimiter, join } from 'node:path';
import { homedir } from 'node:os';
// Env de l'enfant daemon. Une app GUI démarre souvent avec un PATH minimal (sans ~/.local/bin,
// /usr/local/bin, /opt/homebrew/bin) : on l'enrichit pour que le daemon retrouve `git` et le CLI
// `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 };
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'];
}
+392
View File
@@ -0,0 +1,392 @@
import {
app,
BrowserWindow,
dialog,
session,
shell,
type BrowserWindowConstructorOptions,
type Tray,
} from 'electron';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
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 { registerClipboardBridge } from './clipboard';
import { initUpdater } from './updater';
import { resolveIconPath } from './paths';
import { describeStartFailure } from './start-failure';
import { decideUpgradeAction, installChanged, pollInstall, readInstallStamp, type InstallStamp } from './upgrade-watch';
// WM_CLASS / app_id déterministe, posé AVANT app.whenReady(). Sous Wayland (défaut Debian/GNOME)
// l'option `icon:` de BrowserWindow est ignorée : l'icône de fenêtre/dock vient du fichier .desktop
// apparié à la fenêtre via son app_id. electron-builder écrit déjà StartupWMClass=Arboretum dans le
// .desktop ; encore faut-il que l'app_id runtime vaille aussi « Arboretum » (sinon Electron le
// dérive du name package.json et rien ne correspond → icône générique). D'où ce setName explicite.
app.setName('Arboretum');
const PARTITION = 'persist:arboretum';
const DEFAULT_PORT = 7317;
const PORT = resolvePort();
let daemon: DaemonHandle | null = null;
let win: BrowserWindow | null = null;
let tray: Tray | null = null;
let isQuitting = false;
let shuttingDown = false;
let relaunchAfterQuit = false;
let bridgeRegistered = false;
/** Le daemon a passé son handshake : sa mort devient un incident à signaler. */
let serverReady = false;
/** Empreinte du binaire au lancement, comparée plus tard pour repérer une mise à jour installée. */
const bootStamp = readInstallStamp(process.execPath);
let dismissedStamp: InstallStamp | null = null;
let restartPromptOpen = false;
/** Surveillance de l'installation : une mise à jour posée à chaud doit se voir sans que l'utilisateur
* ait à toucher à quoi que ce soit, fenêtre ouverte comprise. */
let installPoll: { stop: () => void } | null = null;
/** Intervalle du poll : un `stat` toutes les 30 s est indolore et suffit largement. */
const INSTALL_POLL_MS = 30_000;
// Instance unique : deux instances = deux daemons/ports en conflit.
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on('second-instance', showWindow);
void app.whenReady()
.then(startWithRetry)
.catch((err: unknown) => {
console.error('[arboretum-desktop] fatal:', err);
app.exit(1);
});
}
/**
* Port du daemon local. Surcharge par variable d'env pour cohabiter avec un Arboretum déjà installé
* en service (ou lancé en terminal) qui tient 7317 en permanence.
*/
function resolvePort(): number {
const n = Number(process.env.ARBORETUM_DESKTOP_PORT);
return Number.isInteger(n) && n >= 1024 && n <= 65535 ? n : DEFAULT_PORT;
}
function logFilePath(): string {
return join(app.getPath('userData'), 'logs', 'daemon.log');
}
/**
* Démarre l'app, et en cas d'échec propose une action au lieu de disparaître : un « rien ne se passe »
* au clic sur l'icône était le pire symptôme possible (port occupé, Node absent, base verrouillée).
*/
async function startWithRetry(): Promise<void> {
for (;;) {
try {
await bootstrap();
return;
} catch (err) {
console.error('[arboretum-desktop] bootstrap failed:', err);
await stopDaemonQuietly();
if ((await promptStartFailure(err)) === 'quit') {
isQuitting = true;
app.exit(1);
return;
}
}
}
}
async function bootstrap(): Promise<void> {
await startServer();
// Idempotent : un « Retry » après échec ne doit pas réenregistrer le pont IPC ni empiler un tray.
if (!bridgeRegistered) {
registerClipboardBridge();
bridgeRegistered = true;
}
if (!win) createWindow(daemonUrl());
installAppMenu({ url: daemonUrl(), onQuit: quitApp });
if (!tray) tray = createTray({ show: showWindow, quit: quitApp });
initUpdater();
// Détection CONTINUE : sans elle, une mise à jour installée pendant que la fenêtre est ouverte
// n'était remarquée qu'au prochain passage par le tray ou le Dock, donc parfois jamais.
if (app.isPackaged && !installPoll) {
installPoll = pollInstall({
path: process.execPath,
intervalMs: INSTALL_POLL_MS,
boot: bootStamp,
onChanged: () => void handleUpgradeInstalled(),
});
}
}
/** Daemon + cookie de session : le strict nécessaire pour charger la SPA (aussi utilisé au redémarrage). */
async function startServer(): Promise<void> {
const dataDir = join(app.getPath('userData'), 'daemon');
daemon = await startDaemon({
dataDir,
port: PORT,
pidfile: join(dataDir, 'daemon.json'),
logFile: logFilePath(),
onLog: (l) => process.stdout.write(l),
onExit: handleDaemonExit,
});
serverReady = true;
await seedSessionCookie(PARTITION, daemon.url, daemon.token);
}
function daemonUrl(): string {
return daemon?.url ?? `http://127.0.0.1:${PORT}`;
}
async function stopDaemonQuietly(): Promise<void> {
serverReady = false;
const handle = daemon;
daemon = null;
await handle?.stop();
}
/** Dialogue d'échec : motif traduit en action, avec accès au journal du daemon. */
async function promptStartFailure(err: unknown): Promise<'retry' | 'quit'> {
const { message, detail } = describeStartFailure(err, PORT);
const log = logFilePath();
for (;;) {
const buttons = existsSync(log) ? ['Retry', 'Show log', 'Quit'] : ['Retry', 'Quit'];
const { response } = await dialog.showMessageBox({
type: 'error',
title: 'Arboretum',
message,
detail,
buttons,
defaultId: 0,
cancelId: buttons.length - 1,
noLink: true,
});
if (buttons[response] === 'Show log') {
void shell.openPath(log);
continue;
}
return buttons[response] === 'Retry' ? 'retry' : 'quit';
}
}
/**
* Mort inattendue du daemon : la fenêtre resterait affichée sur une SPA qui ne répond plus. On le dit
* et on propose de le relancer (le token change, donc cookie re-semé et fenêtre rechargée).
*/
function handleDaemonExit(code: number | null): void {
if (!serverReady || isQuitting || shuttingDown) return;
serverReady = false;
const tail = daemon?.logTail() ?? '';
daemon = null;
void promptServerStopped(code, tail);
}
async function promptServerStopped(code: number | null, tail: string): Promise<void> {
const { response } = await dialog.showMessageBox({
type: 'error',
title: 'Arboretum',
message: 'The Arboretum server stopped',
detail: [`The local server exited (code ${code ?? 'null'}).`, tail && `Server output:\n${tail}`]
.filter(Boolean)
.join('\n\n'),
buttons: ['Restart server', 'Quit'],
defaultId: 0,
cancelId: 1,
noLink: true,
});
if (response !== 0) {
quitApp();
return;
}
for (;;) {
try {
await startServer();
await win?.loadURL(`${daemonUrl()}/`);
return;
} catch (err) {
await stopDaemonQuietly();
if ((await promptStartFailure(err)) === 'quit') {
quitApp();
return;
}
}
}
}
// 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 {
// Tray, second-instance et Dock passent tous ici : c'est le moment où l'utilisateur redemande
// l'app, donc le bon moment pour traiter une mise à jour installée entre-temps.
void handleUpgradeInstalled();
if (!win) return;
if (win.isMinimized()) win.restore();
win.show();
win.focus();
}
/**
* Nombre de sessions VIVANTES hébergées par le daemon : ce sont les seules choses qu'un redémarrage
* détruit. `null` quand on n'a pas pu savoir (daemon injoignable) : l'appelant demandera alors.
* Pas d'en-tête Origin sur ce fetch, donc le check Origin strict du serveur ne s'y applique pas.
*/
async function countLiveSessions(): Promise<number | null> {
const handle = daemon;
if (!handle || !serverReady) return null;
try {
const res = await fetch(`${handle.url}/api/v1/sessions`, { headers: { Authorization: `Bearer ${handle.token}` } });
if (!res.ok) return null;
const body = (await res.json()) as { sessions?: Array<{ live?: boolean }> };
return (body.sessions ?? []).filter((s) => s.live).length;
} catch {
return null;
}
}
/**
* Mise à jour installée pendant que l'app tournait : le lock d'instance unique renvoie les lancements
* suivants sur la fenêtre de l'ANCIENNE version, sans un mot, et l'utilisateur croit avoir migré.
*
* Objectif : zéro manipulation. Quand un redémarrage ne coûte RIEN (aucune session vivante), on
* redémarre tout seul. On ne demande que s'il y a du travail en cours à interrompre, ou si le daemon
* ne répond pas. Un « Later » précédent est définitif pour cette version.
*/
async function handleUpgradeInstalled(): Promise<void> {
if (restartPromptOpen || isQuitting || shuttingDown || !app.isPackaged) return;
const current = readInstallStamp(process.execPath);
if (!current || !installChanged(bootStamp, current)) return;
const dismissed = !!dismissedStamp && !installChanged(dismissedStamp, current);
const liveSessions = dismissed ? 0 : await countLiveSessions();
const action = decideUpgradeAction({ changed: true, liveSessions, dismissed });
if (action === 'none') return;
if (action === 'restart') {
// Rien à perdre : on applique la mise à jour sans rien demander. C'est le cas courant.
installPoll?.stop();
installPoll = null;
relaunchAfterQuit = true;
quitApp();
return;
}
restartPromptOpen = true;
try {
const running = liveSessions ?? 0;
const { response } = await dialog.showMessageBox({
type: 'info',
title: 'Arboretum',
message: 'A new version of Arboretum has been installed',
detail:
`This window still runs version ${app.getVersion()}, started before the update. ` +
(running > 0
? `Restarting stops ${running} running session${running > 1 ? 's' : ''}. They can be resumed afterwards.`
: 'Restart to load the installed version.'),
buttons: ['Restart now', 'Later'],
defaultId: 0,
cancelId: 1,
noLink: true,
});
if (response === 0) {
relaunchAfterQuit = true;
quitApp();
} else {
dismissedStamp = current;
}
} finally {
restartPromptOpen = false;
}
}
function quitApp(): void {
isQuitting = true;
app.quit();
}
function createWindow(url: string): void {
const state = loadWindowState();
const opts: BrowserWindowConstructorOptions = {
width: state.width,
height: state.height,
backgroundColor: '#09090b',
// Logo de la fenêtre / barre des tâches (sinon icône Electron générique sous Linux/Windows).
icon: resolveIconPath(),
webPreferences: {
partition: PARTITION,
contextIsolation: true,
sandbox: true,
nodeIntegration: false,
preload: join(__dirname, 'preload.js'),
},
};
if (state.x !== undefined) opts.x = state.x;
if (state.y !== undefined) opts.y = state.y;
win = new BrowserWindow(opts);
if (state.maximized) win.maximize();
// Liens externes -> navigateur système ; toute navigation hors origine locale est déviée.
win.webContents.setWindowOpenHandler(({ url: u }) => {
void shell.openExternal(u);
return { action: 'deny' };
});
win.webContents.on('will-navigate', (e, u) => {
if (!u.startsWith(url)) {
e.preventDefault();
void shell.openExternal(u);
}
});
// Permissions : n'autoriser que les notifications (cohérent avec la Permissions-Policy serveur).
session.fromPartition(PARTITION).setPermissionRequestHandler((_wc, permission, cb) => cb(permission === 'notifications'));
const persist = (): void => {
if (!win) return;
const b = win.getBounds();
saveWindowState({ width: b.width, height: b.height, x: b.x, y: b.y, maximized: win.isMaximized() });
};
// Fermer la fenêtre = réduire dans le tray (l'app continue en arrière-plan) ; quitter réellement
// se fait via le menu du tray ou le menu applicatif.
win.on('close', (e) => {
persist();
if (!isQuitting) {
e.preventDefault();
win?.hide();
}
});
win.on('closed', () => {
win = null;
});
void win.loadURL(`${url}/`);
}
app.on('before-quit', (e) => {
// Ne pas quitter avant l'arrêt propre du daemon enfant.
isQuitting = true;
if (daemon && !shuttingDown) {
e.preventDefault();
void shutdown();
}
});
async function shutdown(): Promise<void> {
if (shuttingDown) return;
shuttingDown = true;
try {
await daemon?.stop();
} finally {
daemon = null;
serverReady = false;
tray?.destroy();
tray = null;
// Relance demandée après une mise à jour : l'enregistrer une fois le daemon arrêté, sinon le
// nouveau process retrouverait le port occupé par l'ancien.
if (relaunchAfterQuit) app.relaunch();
app.quit();
}
}
+49
View File
@@ -0,0 +1,49 @@
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.
/** Entrée du serveur daemon (son dist/index.js). */
export function resolveServerEntry(): string {
if (app.isPackaged) {
// packagé : le tarball du daemon est extrait sous resources/server/package/
return join(process.resourcesPath, 'server', 'package', 'dist', 'index.js');
}
// dev : packages/desktop/dist/main.js -> packages/server/dist/index.js
return join(__dirname, '..', '..', 'server', 'dist', 'index.js');
}
/** Logo de l'app (fenêtre, tray, barre des tâches) : le mark Arboretum embarqué. */
export function resolveIconPath(): string {
// packagé : extraResources copie resources/icon.png à la racine de resources/.
// dev : depuis dist/main.js -> ../resources/icon.png.
return app.isPackaged
? join(process.resourcesPath, 'icon.png')
: 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) {
return process.platform === 'win32'
? join(process.resourcesPath, 'node', 'node.exe')
: join(process.resourcesPath, 'node', 'bin', 'node');
}
// dev : node du PATH (mêmes prebuilds node-pty que le repo).
return process.platform === 'win32' ? 'node.exe' : 'node';
}
+158
View File
@@ -0,0 +1,158 @@
import { spawnSync } from 'node:child_process';
import { createServer } from 'node:net';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
// Le daemon écoute sur un port FIXE (7317) : c'est ce qui rend l'URL locale mémorisable, mais aussi
// ce qui rend le démarrage fragile dès qu'un autre process le tient. Ce module répond à la seule
// question qui compte alors : qui l'occupe, et avons-nous le droit de le reprendre ?
/** Empreinte du daemon lancé par cette app : de quoi reconnaître un orphelin au démarrage suivant. */
export interface DaemonRecord {
/** pid du process Node du daemon. */
pid: number;
/** pid du process Electron qui l'a lancé : s'il est mort, le daemon n'a plus de pilote. */
ownerPid: number;
port: number;
}
export type PortConflict =
/** Notre daemon, dont l'Electron parent est mort : récupérable. */
| { kind: 'orphan'; pid: number }
/** Une autre instance vivante de l'app (fenêtre probablement dans le tray). */
| { kind: 'other-instance'; pid: number }
/** Un tiers : service `arboretum install`, `npx @johanleroy/git-arboretum`, autre logiciel. */
| { kind: 'foreign' };
const RECLAIM_GRACE_MS = 3_000;
const RECLAIM_POLL_MS = 100;
/** Le port est-il libre ? Bind réel sur l'interface exacte du daemon (aucune heuristique). */
export function isPortFree(port: number, host = '127.0.0.1'): Promise<boolean> {
return new Promise((resolve) => {
const probe = createServer();
probe.once('error', () => resolve(false));
probe.once('listening', () => probe.close(() => resolve(true)));
probe.listen({ port, host, exclusive: true });
});
}
/** Vivacité d'un pid. `EPERM` = process existant mais hors de notre portée, donc vivant. */
export function processAlive(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (err) {
return (err as NodeJS.ErrnoException).code === 'EPERM';
}
}
export function readDaemonRecord(file: string): DaemonRecord | null {
try {
const raw = JSON.parse(readFileSync(file, 'utf8')) as Partial<DaemonRecord>;
const { pid, ownerPid, port } = raw;
if (!Number.isInteger(pid) || !Number.isInteger(ownerPid) || !Number.isInteger(port)) return null;
return { pid: pid as number, ownerPid: ownerPid as number, port: port as number };
} catch {
return null;
}
}
// L'empreinte est un confort de diagnostic : son écriture ne doit jamais faire échouer un démarrage.
export function writeDaemonRecord(file: string, rec: DaemonRecord): void {
try {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, JSON.stringify(rec), 'utf8');
} catch {
/* best-effort */
}
}
export function clearDaemonRecord(file: string): void {
try {
rmSync(file, { force: true });
} catch {
/* best-effort */
}
}
/**
* Qui tient le port ? Fonction pure (vivacité injectée) : l'empreinte du dernier daemon lancé est le
* seul élément qui distingue notre propre orphelin d'une autre instance ou d'un logiciel tiers.
* À n'appeler que sur un port déjà constaté occupé.
*/
export function classifyPortConflict(
record: DaemonRecord | null,
alive: (pid: number) => boolean,
port: number,
): PortConflict {
if (!record || record.port !== port || !alive(record.pid)) return { kind: 'foreign' };
return alive(record.ownerPid) ? { kind: 'other-instance', pid: record.pid } : { kind: 'orphan', pid: record.pid };
}
/**
* Ligne de commande d'un pid, ou `null` si on ne peut pas la lire. Sert de preuve d'identité avant de
* tuer quoi que ce soit ; l'absence de preuve vaut refus.
*/
export function processCommandLine(pid: number): string | null {
if (!Number.isInteger(pid) || pid <= 0) return null;
try {
const res =
process.platform === 'win32'
? spawnSync(
'powershell.exe',
['-NoProfile', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`],
{ encoding: 'utf8', timeout: 5_000, windowsHide: true },
)
: // -ww : sortie NON tronquée. Les chemins en jeu (node bundlé + entrée du serveur dans les
// ressources de l'app) dépassent largement la largeur d'écran par défaut de ps.
spawnSync('ps', ['-ww', '-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 });
const out = (res.stdout ?? '').trim();
return out.length > 0 ? out : null;
} catch {
return null;
}
}
/**
* Le pid exécute-t-il BIEN notre daemon ? Un pidfile périmé peut désigner un pid recyclé entre-temps
* par n'importe quel programme de l'utilisateur : sans cette vérification, la reprise du port se
* changerait en « tuer un process innocent ». Pas de preuve lisible = pas de reprise.
*/
export function isOurDaemonProcess(pid: number, serverEntry: string): boolean {
const cmd = processCommandLine(pid);
return cmd !== null && cmd.includes(serverEntry);
}
/**
* Termine un daemon orphelin et attend la libération EFFECTIVE du port (SIGTERM, puis SIGKILL) :
* le pid disparu ne suffit pas, seul un bind réussi prouve que la voie est libre.
*/
export async function reclaimOrphanDaemon(pid: number, port: number, host = '127.0.0.1'): Promise<boolean> {
try {
process.kill(pid, 'SIGTERM');
} catch {
return isPortFree(port, host);
}
if (await waitForPortFree(port, RECLAIM_GRACE_MS, host)) return true;
try {
process.kill(pid, 'SIGKILL');
} catch {
/* déjà parti */
}
return waitForPortFree(port, RECLAIM_GRACE_MS, host);
}
export async function waitForPortFree(port: number, timeoutMs: number, host = '127.0.0.1'): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (await isPortFree(port, host)) return true;
if (Date.now() >= deadline) return false;
await sleep(RECLAIM_POLL_MS);
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -0,0 +1,62 @@
// Un démarrage raté doit se VOIR. Avant, l'échec du bootstrap se résumait à un console.error suivi
// d'un app.quit() : depuis le lanceur du bureau, l'utilisateur cliquait et « rien ne se passait ».
export type DaemonStartFailureKind = 'port-busy-instance' | 'port-busy-foreign' | 'handshake';
/** Échec de démarrage du daemon, porteur d'un motif exploitable par le dialogue utilisateur. */
export class DaemonStartError extends Error {
constructor(
readonly kind: DaemonStartFailureKind,
message: string,
readonly logTail = '',
) {
super(message);
this.name = 'DaemonStartError';
}
}
export interface StartFailureText {
message: string;
detail: string;
}
/**
* Texte du dialogue d'échec (en anglais : convention des messages utilisateur). Chaque motif porte
* l'action concrète qui débloque, jamais la seule trace technique.
*/
export function describeStartFailure(err: unknown, port: number): StartFailureText {
const kind = err instanceof DaemonStartError ? err.kind : 'handshake';
const tail = err instanceof DaemonStartError ? err.logTail : '';
const raw = err instanceof Error ? err.message : String(err);
if (kind === 'port-busy-instance') {
return {
message: 'Arboretum is already running',
detail:
`Another Arboretum instance is using port ${port}. Its window is probably hidden: ` +
'click the Arboretum icon in the system tray to bring it back, or quit it from there and retry. ' +
'If you just installed an update, quitting and retrying loads the new version.',
};
}
if (kind === 'port-busy-foreign') {
return {
message: `Port ${port} is already in use`,
detail: join([
`Another program is listening on 127.0.0.1:${port}, typically an Arboretum daemon started ` +
'from a terminal (npx @johanleroy/git-arboretum) or installed as a service (arboretum install).',
`Stop it and retry, or set ARBORETUM_DESKTOP_PORT to a free port before launching the app.`,
tail && `Server output:\n${tail}`,
]),
};
}
return {
message: 'Arboretum could not start its local server',
detail: join([raw, tail && `Server output:\n${tail}`]),
};
}
function join(parts: (string | false)[]): string {
return parts.filter((p): p is string => typeof p === 'string' && p.length > 0).join('\n\n');
}
+40
View File
@@ -0,0 +1,40 @@
import { Menu, Tray, nativeImage } from 'electron';
import { isAutoStartEnabled, setAutoStart } from './autostart';
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 {
// 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 => {
tray.setContextMenu(
Menu.buildFromTemplate([
{ label: 'Open Arboretum', click: opts.show },
{ type: 'separator' },
{
label: 'Launch at login',
type: 'checkbox',
checked: isAutoStartEnabled(),
click: (item) => {
setAutoStart(item.checked);
buildMenu();
},
},
{ type: 'separator' },
{ label: 'Quit', click: opts.quit },
]),
);
};
buildMenu();
tray.on('click', opts.show);
return tray;
}
+13
View File
@@ -0,0 +1,13 @@
import { app } from 'electron';
import { autoUpdater } from 'electron-updater';
// Vérifie les mises à jour (provider generic -> assets de release Gitea, cf. electron-builder.yml).
// No-op en dev (pas de app-update.yml). Auto-update effectif : Windows (nsis) + Linux (AppImage) ;
// macOS reste manuel tant que l'app n'est pas signée.
export function initUpdater(): void {
if (!app.isPackaged) return;
autoUpdater.autoDownload = true;
void autoUpdater.checkForUpdatesAndNotify().catch(() => {
/* hors ligne / pas de release publiée : silencieux */
});
}
@@ -0,0 +1,71 @@
import { statSync } from 'node:fs';
// Une mise à jour installée pendant que l'app tourne (dpkg -i, installeur nsis, .app remplacée)
// remplace le binaire sur disque sans toucher au process en cours. Le lock d'instance unique renvoie
// alors les lancements suivants vers la fenêtre de l'ANCIENNE version, silencieusement : l'utilisateur
// croit utiliser la nouvelle. Comparer une empreinte du binaire suffit à le détecter.
/** Empreinte du binaire installé. Un remplacement de fichier change l'inode (et souvent mtime/taille). */
export interface InstallStamp {
ino: number;
mtimeMs: number;
size: number;
}
export function readInstallStamp(path: string): InstallStamp | null {
try {
const st = statSync(path);
return { ino: Number(st.ino), mtimeMs: Math.floor(st.mtimeMs), size: st.size };
} catch {
return null;
}
}
/** L'installation a-t-elle changé sous nos pieds ? Une empreinte illisible ne conclut rien. */
export function installChanged(boot: InstallStamp | null, current: InstallStamp | null): boolean {
if (!boot || !current) return false;
return boot.ino !== current.ino || boot.mtimeMs !== current.mtimeMs || boot.size !== current.size;
}
/**
* Ce qu'il faut faire d'une mise à jour installée à chaud.
*
* Le but est de ne PAS faire porter la manipulation à l'utilisateur : quand redémarrer ne coûte rien,
* on redémarre. La seule chose qu'un redémarrage détruit, ce sont les sessions vivantes hébergées par
* le daemon (des agents en train de travailler) : là seulement, on demande.
*
* `liveSessions === null` = on n'a pas pu le savoir (daemon injoignable) : on demande, par prudence.
* Un refus précédent (« Later ») est respecté, y compris si les sessions se terminent ensuite : on ne
* redémarre jamais dans le dos de quelqu'un qui a dit non.
*/
export function decideUpgradeAction(input: {
changed: boolean;
liveSessions: number | null;
dismissed: boolean;
}): 'none' | 'restart' | 'ask' {
if (!input.changed || input.dismissed) return 'none';
return input.liveSessions === 0 ? 'restart' : 'ask';
}
/**
* Surveillance de l'installation par POLL, et non par `fs.watch` : un paquet remplace le binaire
* (nouvel inode) ou tout un répertoire, et selon le gestionnaire de paquets et le système de
* fichiers, `fs.watch` sur le fichier ne voit alors plus rien. Un `stat` périodique est trivial en
* coût et se comporte pareil partout. Le premier changement suffit : on arrête de surveiller.
*/
export function pollInstall(opts: {
path: string;
intervalMs: number;
boot: InstallStamp | null;
onChanged: (current: InstallStamp) => void;
}): { stop: () => void } {
const timer = setInterval(() => {
const current = readInstallStamp(opts.path);
if (!current || !installChanged(opts.boot, current)) return;
clearInterval(timer);
opts.onChanged(current);
}, opts.intervalMs);
// Ne retient pas la boucle d'événements : ce timer ne doit jamais empêcher l'app de quitter.
timer.unref?.();
return { stop: () => clearInterval(timer) };
}
+34
View File
@@ -0,0 +1,34 @@
import { app } from 'electron';
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
export interface WindowState {
width: number;
height: number;
x?: number;
y?: number;
maximized?: boolean;
}
const DEFAULT: WindowState = { width: 1400, height: 900 };
function stateFile(): string {
return join(app.getPath('userData'), 'window-state.json');
}
export function loadWindowState(): WindowState {
try {
const parsed = JSON.parse(readFileSync(stateFile(), 'utf8')) as Partial<WindowState>;
return { ...DEFAULT, ...parsed };
} catch {
return { ...DEFAULT };
}
}
export function saveWindowState(state: WindowState): void {
try {
writeFileSync(stateFile(), JSON.stringify(state));
} catch {
/* best effort : quota / permissions */
}
}
+16
View File
@@ -0,0 +1,16 @@
import { contextBridge, ipcRenderer } from 'electron';
import { CLIPBOARD_READ, CLIPBOARD_WRITE } from '../shared/ipc';
// Preload minimal (sandbox activé) : un marqueur permettant à la SPA de détecter qu'elle tourne dans
// l'app de bureau, plus un pont presse-papier. Aucun accès Node/fs exposé au renderer.
//
// Le pont existe parce que `navigator.clipboard` est refusé (NotAllowedError) dans le renderer
// Electron : sans lui, impossible de copier la sélection d'un terminal depuis l'app. Le module
// `clipboard` n'étant pas disponible dans un preload sandboxé, on relaie par IPC vers le main.
contextBridge.exposeInMainWorld('arboretumDesktop', {
isDesktop: true,
clipboard: {
readText: (): Promise<string> => ipcRenderer.invoke(CLIPBOARD_READ) as Promise<string>,
writeText: (text: string): Promise<boolean> => ipcRenderer.invoke(CLIPBOARD_WRITE, text) as Promise<boolean>,
},
});
+4
View File
@@ -0,0 +1,4 @@
// Noms des canaux IPC, partagés entre le process principal et le preload. Isolés ici pour que le
// bundle du preload n'ait pas à importer un module du main (qui tire `ipcMain` avec lui).
export const CLIPBOARD_READ = 'arboretum:clipboard-read';
export const CLIPBOARD_WRITE = 'arboretum:clipboard-write';
+174
View File
@@ -0,0 +1,174 @@
import { describe, expect, it } from 'vitest';
import { spawn } from 'node:child_process';
import { createServer } from 'node:net';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
classifyPortConflict,
clearDaemonRecord,
isOurDaemonProcess,
isPortFree,
processAlive,
readDaemonRecord,
reclaimOrphanDaemon,
waitForPortFree,
writeDaemonRecord,
type DaemonRecord,
} from '../src/main/port-guard';
const rec = (over: Partial<DaemonRecord> = {}): DaemonRecord => ({ pid: 111, ownerPid: 222, port: 7317, ...over });
/**
* Réserve un port libre HORS de la plage éphémère du noyau (32768+). Un `listen(0)` rendu puis
* réutilisé peut être réattribué entre-temps à un autre worker vitest : le test échouait alors une
* fois sur N. Ici le port est choisi dans une plage que personne n'obtient par tirage.
*/
async function reservePort(): Promise<number> {
for (let i = 0; i < 40; i++) {
const port = 7400 + Math.floor(Math.random() * 600);
if (await isPortFree(port)) return port;
}
throw new Error('aucun port libre dans 7400-7999');
}
/** Attend que le squatteur ait RÉELLEMENT bind (un spawn met quelques dizaines de ms à écouter). */
async function waitUntilBusy(port: number, timeoutMs = 5_000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (!(await isPortFree(port))) return true;
await new Promise((r) => setTimeout(r, 25));
}
return false;
}
describe('classifyPortConflict', () => {
it('sans empreinte, le port est tenu par un tiers', () => {
expect(classifyPortConflict(null, () => true, 7317)).toEqual({ kind: 'foreign' });
});
it('empreinte sur un AUTRE port : sans rapport avec le conflit courant', () => {
expect(classifyPortConflict(rec({ port: 7400 }), () => true, 7317)).toEqual({ kind: 'foreign' });
});
it('daemon de l’empreinte mort : le port est tenu par autre chose', () => {
expect(classifyPortConflict(rec(), () => false, 7317)).toEqual({ kind: 'foreign' });
});
it('daemon vivant + Electron parent vivant : autre instance de l’app', () => {
expect(classifyPortConflict(rec(), () => true, 7317)).toEqual({ kind: 'other-instance', pid: 111 });
});
it('daemon vivant mais Electron parent mort : orphelin récupérable', () => {
const alive = (pid: number): boolean => pid === 111;
expect(classifyPortConflict(rec(), alive, 7317)).toEqual({ kind: 'orphan', pid: 111 });
});
});
describe('empreinte du daemon', () => {
it('écrit, relit et efface', () => {
const file = join(mkdtempSync(join(tmpdir(), 'arb-pidfile-')), 'daemon.json');
writeDaemonRecord(file, rec());
expect(readDaemonRecord(file)).toEqual(rec());
clearDaemonRecord(file);
expect(readDaemonRecord(file)).toBeNull();
});
it('rejette un contenu illisible ou incomplet plutôt que de deviner', () => {
const dir = mkdtempSync(join(tmpdir(), 'arb-pidfile-'));
const bad = join(dir, 'bad.json');
writeFileSync(bad, 'pas du json', 'utf8');
expect(readDaemonRecord(bad)).toBeNull();
const partial = join(dir, 'partial.json');
writeFileSync(partial, JSON.stringify({ pid: 12 }), 'utf8');
expect(readDaemonRecord(partial)).toBeNull();
});
it('n’échoue pas si le chemin est inécrivable (diagnostic best-effort)', () => {
// Un fichier régulier en guise de répertoire parent : mkdir/write échouent (ENOTDIR) et
// l'écriture de l'empreinte doit rester silencieuse, jamais bloquer un démarrage.
const dir = mkdtempSync(join(tmpdir(), 'arb-pidfile-'));
const blocker = join(dir, 'pas-un-dossier');
writeFileSync(blocker, 'x', 'utf8');
expect(() => writeDaemonRecord(join(blocker, 'daemon.json'), rec())).not.toThrow();
expect(readDaemonRecord(join(blocker, 'daemon.json'))).toBeNull();
});
});
describe('processAlive', () => {
it('reconnaît le process courant et refuse les pid invalides', () => {
expect(processAlive(process.pid)).toBe(true);
expect(processAlive(0)).toBe(false);
expect(processAlive(-1)).toBe(false);
expect(processAlive(Number.NaN)).toBe(false);
});
});
describe('isPortFree', () => {
it('distingue un port libre d’un port occupé', async () => {
const port = await reservePort();
expect(await isPortFree(port)).toBe(true);
const srv = createServer();
await new Promise<void>((resolve) => srv.listen(port, '127.0.0.1', resolve));
expect(await isPortFree(port)).toBe(false);
await new Promise<void>((resolve) => srv.close(() => resolve()));
expect(await isPortFree(port)).toBe(true);
});
it('waitForPortFree rend la main sur expiration sans boucler indéfiniment', async () => {
const port = await reservePort();
const srv = createServer();
await new Promise<void>((resolve) => srv.listen(port, '127.0.0.1', resolve));
expect(await waitForPortFree(port, 250)).toBe(false);
await new Promise<void>((resolve) => srv.close(() => resolve()));
});
});
describe('isOurDaemonProcess', () => {
it('reconnaît un process dont la commande porte l’entrée du serveur', async () => {
const marker = join(mkdtempSync(join(tmpdir(), 'arb-entry-')), 'server-entry-marker.js');
writeFileSync(marker, 'setInterval(()=>{},1000)', 'utf8');
const child = spawn(process.execPath, [marker]);
await new Promise((r) => setTimeout(r, 400));
expect(isOurDaemonProcess(child.pid as number, marker)).toBe(true);
// Un pid recyclé par un programme quelconque ne doit PAS passer pour notre daemon.
expect(isOurDaemonProcess(child.pid as number, '/opt/ailleurs/dist/index.js')).toBe(false);
child.kill('SIGKILL');
});
it('refuse quand la commande est illisible (pid absent, pid invalide)', () => {
expect(isOurDaemonProcess(2_147_483_600, '/quelconque')).toBe(false);
expect(isOurDaemonProcess(0, '/quelconque')).toBe(false);
});
});
describe('reclaimOrphanDaemon', () => {
it('termine le squatteur et attend la libération EFFECTIVE du port', async () => {
const port = await reservePort();
const child = spawn(process.execPath, [
'-e',
`require('net').createServer().listen(${port},'127.0.0.1');setInterval(()=>{},1000)`,
]);
expect(await waitUntilBusy(port)).toBe(true); // l'enfant a bien pris le port
expect(await reclaimOrphanDaemon(child.pid as number, port)).toBe(true);
expect(await isPortFree(port)).toBe(true);
}, 12_000);
it('un pid déjà mort ne bloque rien', async () => {
const port = await reservePort();
const child = spawn(process.execPath, ['-e', 'process.exit(0)']);
await new Promise<void>((resolve) => child.once('exit', () => resolve()));
expect(await reclaimOrphanDaemon(child.pid as number, port)).toBe(true);
});
it('SIGKILL en dernier recours quand SIGTERM est ignoré', async () => {
const port = await reservePort();
const child = spawn(process.execPath, [
'-e',
`process.on('SIGTERM',()=>{});require('net').createServer().listen(${port},'127.0.0.1');setInterval(()=>{},1000)`,
]);
expect(await waitUntilBusy(port)).toBe(true);
expect(await reclaimOrphanDaemon(child.pid as number, port)).toBe(true);
expect(await isPortFree(port)).toBe(true);
}, 12_000);
});
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest';
import { DaemonStartError, describeStartFailure } from '../src/main/start-failure';
describe('describeStartFailure', () => {
it('port tenu par une autre instance : renvoie vers le tray, pas vers une trace technique', () => {
const err = new DaemonStartError('port-busy-instance', 'port 7317 is already in use');
const { message, detail } = describeStartFailure(err, 7317);
expect(message).toBe('Arboretum is already running');
expect(detail).toContain('7317');
expect(detail).toContain('system tray');
});
it('port tenu par un tiers : nomme les suspects et l’échappatoire (variable d’env)', () => {
const err = new DaemonStartError('port-busy-foreign', 'port 7317 is already in use', 'EADDRINUSE');
const { message, detail } = describeStartFailure(err, 7317);
expect(message).toBe('Port 7317 is already in use');
expect(detail).toContain('arboretum install');
expect(detail).toContain('ARBORETUM_DESKTOP_PORT');
expect(detail).toContain('EADDRINUSE');
});
it('échec de handshake : conserve le message et la queue de journal', () => {
const err = new DaemonStartError('handshake', 'daemon exited before handshake (code 1)', 'boom\nbadaboum');
const { message, detail } = describeStartFailure(err, 7317);
expect(message).toBe('Arboretum could not start its local server');
expect(detail).toContain('daemon exited before handshake (code 1)');
expect(detail).toContain('badaboum');
});
it('erreur quelconque (hors DaemonStartError) reste affichable', () => {
expect(describeStartFailure(new Error('ENOENT node'), 7317).detail).toContain('ENOENT node');
expect(describeStartFailure('cassé', 7317).detail).toContain('cassé');
});
it('sans queue de journal, aucun bloc « Server output » vide', () => {
const detail = describeStartFailure(new DaemonStartError('handshake', 'nope'), 7317).detail;
expect(detail).not.toContain('Server output');
});
});
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, it } from 'vitest';
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { decideUpgradeAction, installChanged, pollInstall, readInstallStamp } from '../src/main/upgrade-watch';
describe('upgrade-watch', () => {
it('lit une empreinte de fichier, et rien pour un chemin absent', () => {
const file = join(mkdtempSync(join(tmpdir(), 'arb-stamp-')), 'bin');
writeFileSync(file, 'v1', 'utf8');
const stamp = readInstallStamp(file);
expect(stamp?.size).toBe(2);
expect(readInstallStamp(join(file, 'nulle-part'))).toBeNull();
});
it('détecte le remplacement du binaire (mtime/taille)', () => {
const file = join(mkdtempSync(join(tmpdir(), 'arb-stamp-')), 'bin');
writeFileSync(file, 'v1', 'utf8');
const boot = readInstallStamp(file);
expect(installChanged(boot, readInstallStamp(file))).toBe(false);
writeFileSync(file, 'version deux', 'utf8');
utimesSync(file, new Date(), new Date(Date.now() + 5_000)); // dpkg pose un mtime plus récent
expect(installChanged(boot, readInstallStamp(file))).toBe(true);
});
it('une empreinte illisible ne conclut jamais à une mise à jour', () => {
const stamp = { ino: 1, mtimeMs: 2, size: 3 };
expect(installChanged(null, stamp)).toBe(false);
expect(installChanged(stamp, null)).toBe(false);
expect(installChanged(null, null)).toBe(false);
});
});
// Objectif produit : ZÉRO manipulation quand c'est sans risque. Un redémarrage ne détruit qu'une
// chose, les sessions vivantes hébergées par le daemon : elles seules justifient de demander.
describe('decideUpgradeAction', () => {
it('rien à faire si l’installation n’a pas changé', () => {
expect(decideUpgradeAction({ changed: false, liveSessions: 0, dismissed: false })).toBe('none');
expect(decideUpgradeAction({ changed: false, liveSessions: 3, dismissed: false })).toBe('none');
});
it('aucune session vivante : redémarrage automatique, sans dialogue', () => {
expect(decideUpgradeAction({ changed: true, liveSessions: 0, dismissed: false })).toBe('restart');
});
it('des sessions tournent : on demande avant de les interrompre', () => {
expect(decideUpgradeAction({ changed: true, liveSessions: 1, dismissed: false })).toBe('ask');
expect(decideUpgradeAction({ changed: true, liveSessions: 9, dismissed: false })).toBe('ask');
});
it('état inconnu (daemon injoignable) : on demande, par prudence', () => {
expect(decideUpgradeAction({ changed: true, liveSessions: null, dismissed: false })).toBe('ask');
});
it('un « Later » est définitif : jamais de redémarrage dans le dos de l’utilisateur', () => {
expect(decideUpgradeAction({ changed: true, liveSessions: 0, dismissed: true })).toBe('none');
expect(decideUpgradeAction({ changed: true, liveSessions: null, dismissed: true })).toBe('none');
});
});
describe('pollInstall', () => {
it('signale le premier changement, puis s’arrête de lui-même', async () => {
const dir = mkdtempSync(join(tmpdir(), 'arb-poll-'));
const file = join(dir, 'app');
try {
writeFileSync(file, 'v1');
const boot = readInstallStamp(file);
const seen: number[] = [];
const handle = pollInstall({ path: file, intervalMs: 10, boot, onChanged: (c) => seen.push(c.size) });
await new Promise((r) => setTimeout(r, 40));
expect(seen).toHaveLength(0); // rien n'a bougé
writeFileSync(file, 'v2-plus-long');
await new Promise((r) => setTimeout(r, 80));
expect(seen).toHaveLength(1);
// un second changement ne doit PAS rappeler : le poll s'arrête au premier
writeFileSync(file, 'v3-encore-plus-long');
await new Promise((r) => setTimeout(r, 60));
expect(seen).toHaveLength(1);
handle.stop();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it('un chemin illisible ne déclenche rien', async () => {
const seen: string[] = [];
const handle = pollInstall({
path: '/definitely/not/here',
intervalMs: 10,
boot: { ino: 1, mtimeMs: 1, size: 1 },
onChanged: () => seen.push('x'),
});
await new Promise((r) => setTimeout(r, 50));
expect(seen).toHaveLength(0);
handle.stop();
});
});
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"moduleResolution": "node",
"lib": ["ES2022"],
"strict": true,
"exactOptionalPropertyTypes": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}
+188
View File
@@ -0,0 +1,188 @@
# Changelog
Notable changes to `@johanleroy/git-arboretum` (the Arboretum daemon). The VS Code
extension keeps its own changelog in `packages/vscode/CHANGELOG.md`.
## 3.7.1
- **Sessions launched from Arboretum lost their transcript.** When the daemon itself was started from a
Claude Code session (an agent launching the desktop app, or `arboretum` started from a Claude
terminal), it inherited that session's runtime markers and passed them on to every session it
spawned. `CLAUDE_CODE_CHILD_SESSION=1` makes the CLI believe it is a sub-session, so it turns
transcript saving off: no history, no `--resume`, `claudeSessionId` stays null, and with it the fine
busy/waiting/idle state. The visible symptom was a warning in the terminal: *Transcript saving is
off, inherited CLAUDE_CODE_CHILD_SESSION marker*. The PTY environment is now stripped of those
markers (`CLAUDECODE`, `CLAUDE_CODE_CHILD_SESSION`, `CLAUDE_CODE_SESSION_ID`,
`CLAUDE_CODE_ENTRYPOINT`, `CLAUDE_CODE_EXECPATH`, `CLAUDE_PID`, `CLAUDE_EFFORT`) for `claude` **and**
for shells, since a `claude` typed by hand in a terminal would inherit them too. Legitimate user
configuration (`CLAUDE_CONFIG_DIR`, `ANTHROPIC_*`, proxies) is untouched.
## 3.7.0
Terminals stop going black, and they now sit side by side. Files and commits follow the terminal you
are actually looking at. Fully additive, no protocol version bump.
- **A terminal could stay completely black while its session was alive and running.** The attach
replay is a binary frame, but a client only learns its channel number from the `attached` message.
The server sent the replay *first*, so every client dropped it on an unknown channel: nothing was
painted, and a resting TUI (Claude at its prompt) never emits anything on its own. `attached` is now
sent before the replay, which fixes the web app, the desktop app and the VS Code extension at once.
A resize on attach used to hide the bug by triggering a repaint through SIGWINCH, which is why it
looked intermittent.
- **Screen-less attachments.** `attach` accepts an optional `screen` flag (default `true`). With
`screen: false`, a client that only wants to answer a dialog no longer takes control of the session,
no longer forces its own dimensions onto the PTY (which used to freeze the real terminal's geometry)
and no longer receives the output stream just to throw it away.
- **The reason a session died is now visible in the terminal**: a last line, `[arboretum] claude
exited with code 1`, is written to the stream before clients are detached. A process that died at
spawn time used to leave nothing but an empty screen.
- **A stale Claude CLI path is re-resolved.** The resolved binary was cached for the lifetime of the
daemon; after an nvm or asdf switch it pointed at a file that no longer existed, and the PTY died
without a single byte of output.
- **Terminal columns.** The dock holds up to three resizable columns, each with its own tabs. Alt+click
a session (tree, panels, attention list) or use the tab button to open it beside the current one.
Keystrokes always go to the focused column. The dock's height ceiling now follows the viewport
instead of a fixed 640 px, and opening the dock gives it a usable height.
- **Changes are scoped to the focused terminal.** The Changes view shows the worktree of the terminal
you are working in, or every repo of its group for a group session, with a one-click "show every
project" toggle. The Git index in the sidebar stays global on purpose: it is the way out of a narrow
scope. The activity-bar badge stays global too: it exists to surface work you are *not* looking at.
## 3.6.0
Files open again, and uncommitted work gets a real surface: one block per project, in the centre of
the IDE. Fully additive, no protocol version bump.
- **Opening a file showed an empty page.** The container of the single Monaco instance lived inside a
`v-if`, so mounting the IDE with no open tab (first use, or after closing everything) bailed out
silently and the editor was never created: the first file you opened rendered nothing, with no
spinner and no error. The container is now always mounted and the editor is created on demand.
Closing the last tab no longer destroys it either.
- **The editor now says when it cannot load.** A missing editor chunk (a stale `index.html` after an
update, a network drop) used to be memoized as a permanent failure, silently, for the whole
session. It reports the failure, offers Retry and Reload page, and shows a loading state while the
chunk and the file are fetched. A file that disappears under the editor is reported instead of
being swallowed.
- **No more console errors when opening TypeScript.** Only the base worker was provided, so the
TypeScript language service kept calling a worker that did not implement its methods, throwing on
every single file open. The language workers are shipped now (loaded on demand). Semantic
diagnostics stay off on purpose: with no tsconfig and no node_modules, they would invent errors.
- **Changes: your uncommitted work, per project, in the centre.** Two buttons on the right of the tab
bar switch the centre between Files and Changes. Changes shows one block per worktree across every
open project, each with its staged and unstaged files, its diff unfolded in place, its commit,
push, fetch and pull, and its own history. The Git panel in the sidebar becomes the index: what
each project is worth at a glance, one click to open the matching block. The activity bar badge
finally counts the worktrees that need attention.
- **Push and commit buttons tell the truth.** Push was enabled with nothing to push and disabled when
merely behind; it now follows what git will actually do. Amending just a message is allowed, as the
server already did. A rebase is offered as soon as the branch is behind, not only after a
fast-forward fails.
- **Commit, fetch and push refresh what they change.** They only broadcast a worktree update, so the
"n unpushed" counter stayed stale right after a push, and files just committed were still listed.
- On mobile, tapping a file in the explorer now brings the editor to the front, and the Git tab opens
the Changes view (the sidebar index is a desktop affordance).
## 3.5.1
Completes the terminal copy & paste of 3.5.0, which only worked in a browser.
- **Copy & paste inside the desktop app.** In the Electron renderer, `navigator.clipboard` rejects with
`NotAllowedError` for reads AND writes, so 3.5.0's copy silently did nothing there, exactly where the
problem had been reported. Clipboard access now goes through a cascade: the desktop app's own bridge
first (IPC to Electron's `clipboard` module, exposed by the preload), then `navigator.clipboard`, then
`document.execCommand('copy')` for writes, which also covers plain-HTTP access over a LAN where the
Clipboard API is unavailable.
## 3.5.0
Fixes a black screen after every update, gives the web terminal a working copy & paste, and lets you
browse a group's files without leaving the Groups panel. Fully additive, no protocol version bump.
- **No more black screen after an update.** The embedded SPA is served by `@fastify/static`, whose weak
etag derives from size + mtime, and `npm pack` pins the mtime of every file in the tarball to a
constant (1985-10-26). Two different `index.html` of equal size therefore shared an etag: clients got a
`304 Not Modified` and kept an index referencing `/assets/<hash>` files that no longer existed. The
fallback route then answered those module requests with `index.html` as `text/html`, the browser
refused the script, and nothing painted. `index.html` and every other unhashed file are now served
`no-store` with conditional validation disabled, so a client holding a stale copy repairs itself;
hashed `/assets/` are served `immutable` for a year.
- **Copy & paste in the terminal.** xterm's selection is not a DOM selection, so the native Copy (the
Electron Edit menu, the browser context menu) had nothing to copy and terminal output could not be
retrieved at all. `Ctrl+Shift+C` / `Ctrl+Shift+V` (`Cmd+C` / `Cmd+V` on macOS, plus
`Ctrl+Insert` / `Shift+Insert`) now copy the selection and paste the clipboard, and the DOM `copy`
event is intercepted so the native Copy works too. `Ctrl+C` is deliberately untouched: it stays SIGINT.
- **Theme applied before the first paint again.** The anti-FOUC script was inline in `index.html`, which
the daemon's own CSP (`script-src 'self'`) refused to execute; it moved to `/theme-boot.js`.
- **Browse files from the Groups panel.** A group's worktrees expand into their file tree, the same
component and the same expansion state as the Explorer, and those worktrees are now watched for
real-time changes too.
- **Sources are text again.** Three files embedded a literal NUL byte in a string separator, which made
git and grep treat them as binary: their diffs were unreviewable and the `lint-dashes` CI guard
(`git grep -I`) silently skipped them. Escaped as `\0`, same runtime value.
## 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.
- **Launch commands per repo.** A repo now carries reusable start commands (label, shell command, optional subdirectory), persisted as JSON and edited from the dashboard. They can be auto-detected from `package.json` scripts, a `Procfile` or a `docker-compose` file.
- **One terminal per command.** `POST /api/v1/repos/:id/launch` resolves the target worktree server-side (the client never passes a raw path) and opens one managed terminal per enabled command, all sharing a launch run id so you can stop the whole set in one action. Each command runs in your interactive login shell (so `npm`, `docker`, nvm/asdf are on `PATH`) and the shell stays live after the command exits, keeping failures on screen.
- **Surfaces.** Start a project from a repo or worktree menu, the sessions panel or the command palette. The VS Code extension exposes it too (see its changelog).
## 3.2.0
Visual overhaul: the web UI adopts the "Emerald" design system and gains a full theme system. No protocol or API change (fully additive, backward compatible).
- **Light and dark themes.** A `light` / `dark` / `system` toggle (in the activity bar and in Settings), remembered across sessions and applied before the first paint (no flash of the wrong theme). The Monaco editor, the xterm terminals (now with a full 16-color ANSI palette) and the diffs all re-theme live.
- **Emerald design language.** Self-hosted Inter + JetBrains Mono, an emerald accent, consistent rounded corners, mono status pills and dots, refined focus and text selection, thin scrollbars, and a terminal signature motif.
- **Marketing site aligned.** git-arboretum.com now mirrors the app: the same tokens, fonts and theme toggle, with up-to-date IDE mockups.
## 3.1.0
- The IDE becomes the single shell of the web UI; the legacy worktree-first dashboard is retired as the default surface (still reachable at `/dashboard`).
- Desktop app metadata fixes (window logo on Debian / Wayland).
## 3.0.0
- **Multi-project IDE** milestone: one workspace (route `/ide`, the default on desktop) holding every open project at once, a unified project / worktree / session tree, a tabbed Monaco editor with inline diffs, docked session terminals, and Git / Sessions / Groups panels. Ships as a **native Electron desktop app** (Linux, Windows, macOS) alongside the same web UI.
## 2.0.0
- "Real worktree IDE" foundations: a pure git engine, a real-time file-system watcher, the file API, selective staging / discard / amend / fetch / pull, automatic session archival, real-time settings sync, and encrypted remote git services (GitHub / GitLab / Gitea) with HTTPS clone.
+3 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@johanleroy/git-arboretum",
"version": "1.9.0",
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
"version": "3.7.1",
"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>",
@@ -57,6 +57,7 @@
"@fastify/websocket": "^11.0.0",
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
"@xterm/headless": "^6.0.0",
"chokidar": "^4.0.3",
"fastify": "^5.0.0",
"web-push": "^3.6.7"
},
+1 -1
View File
@@ -19,7 +19,7 @@ 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}` : ''}`);
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-'));
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env node
// Acceptation P10 (sans navigateur, sans quota Claude) : archivage automatique des sessions terminées.
// Vrai daemon + faux binaire `claude` (echo+sleep, comme p2) + 2e connexion sqlite (WAL) pour fabriquer
// des sessions managées terminées avec un ended_at ancien. Couvre : sweep archive-now (archived_at posé,
// event WS session_archived), exclusion par défaut + inclusion via ?includeArchived, archive/unarchive
// manuels, rétention=0 (no-op), et, preuve clé « pas de perte », resume d'une session ARCHIVÉE → 201.
import { spawn } from 'node:child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import { DatabaseSync } from 'node:sqlite';
const require = createRequire(import.meta.url);
const WebSocket = require('ws');
const PORT = 7551;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const OLD = '2020-01-01T00:00:00.000Z';
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-p10-'));
const claudeHome = join(tmp, 'claude');
const workDir = join(tmp, 'work');
const fakeBin = join(tmp, 'bin');
const dbPath = join(tmp, 'a.db');
mkdirSync(join(claudeHome, 'projects'), { recursive: true });
mkdirSync(join(claudeHome, 'sessions'), { recursive: true });
mkdirSync(workDir, { recursive: true });
mkdirSync(fakeBin, { recursive: true });
writeFileSync(join(fakeBin, 'claude'), '#!/usr/bin/env bash\necho "FAKE-CLAUDE args=[$*] cwd=$(pwd)"\nsleep 30\n');
chmodSync(join(fakeBin, 'claude'), 0o755);
// Insère une session managée « claude » terminée directement en DB (2e connexion WAL).
function insertManagedDeadSession(id, claudeSid, endedAt) {
const db = new DatabaseSync(dbPath);
db.prepare(
'INSERT INTO sessions (id, cwd, command, created_at, ended_at, claude_session_id) VALUES (?, ?, ?, ?, ?, ?)',
).run(id, workDir, 'claude', OLD, endedAt, claudeSid);
db.close();
}
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', dbPath, '--claude-home', claudeHome, '--no-discover'],
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, 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 = 6000) => {
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) } : {}),
});
const listSessions = async (cookie, q = '') => (await (await j(`/api/v1/sessions${q}`, 'GET', cookie)).json()).sessions ?? [];
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: ['sessions'] });
// ---- A. Auto-archivage (sweep via archive-now) ----
insertManagedDeadSession('arch-old', 'sid-old', OLD);
const before = await listSessions(cookie);
check('session terminée ancienne visible par défaut (avant archivage)', before.some((s) => s.id === 'arch-old' && !s.archived));
c.state.msgs.length = 0;
const now = await (await j('/api/v1/sessions/archive-now', 'POST', cookie)).json();
check('POST /sessions/archive-now → ≥ 1 archivée', now.archived >= 1, `archived=${now.archived}`);
const evt = await c.waitMsg((m) => m.type === 'session_archived' && m.sessionId === 'arch-old');
check('event WS session_archived reçu', !!evt);
const def = await listSessions(cookie);
check('GET /sessions exclut l’archivée par défaut', !def.some((s) => s.id === 'arch-old'));
const inc = await listSessions(cookie, '?includeArchived=true');
check('GET /sessions?includeArchived=true inclut l’archivée (archived=true)', inc.some((s) => s.id === 'arch-old' && s.archived === true));
// ---- B. Preuve « pas de perte » : resume d'une session ARCHIVÉE → 201 ----
const resume = await j('/api/v1/sessions/arch-old/resume', 'POST', cookie);
const resumed = await resume.json();
check('resume d’une session archivée → 201 (PTY managé claude)', resume.status === 201 && resumed.session?.command === 'claude');
// ---- C. Archive / unarchive manuels ----
insertManagedDeadSession('manual1', 'sid-man', new Date().toISOString()); // récente → le sweep ne la touche pas
c.state.msgs.length = 0;
const arch = await j('/api/v1/sessions/manual1/archive', 'POST', cookie);
check('POST /sessions/:id/archive → 200', arch.status === 200);
check('archive manuel → event session_archived', !!(await c.waitMsg((m) => m.type === 'session_archived' && m.sessionId === 'manual1')));
check('archive manuel → exclue par défaut', !(await listSessions(cookie)).some((s) => s.id === 'manual1'));
const unarch = await j('/api/v1/sessions/manual1/archive', 'DELETE', cookie);
check('DELETE /sessions/:id/archive → 200', unarch.status === 200);
check('unarchive → ré-affichée par défaut (archived=false)', (await listSessions(cookie)).some((s) => s.id === 'manual1' && !s.archived));
const missing = await j('/api/v1/sessions/does-not-exist/archive', 'POST', cookie);
check('archive d’un id inconnu → 404', missing.status === 404);
// ---- D. Rétention = 0 → archivage désactivé (no-op) ----
const patch = await j('/api/v1/settings', 'PATCH', cookie, { retentionDays: 0 });
check('PATCH retentionDays=0 → 200', patch.status === 200);
insertManagedDeadSession('arch-old2', 'sid-old2', OLD);
const now0 = await (await j('/api/v1/sessions/archive-now', 'POST', cookie)).json();
check('rétention=0 → sweep n’archive rien', now0.archived === 0);
check('session ancienne reste visible (archivage désactivé)', (await listSessions(cookie)).some((s) => s.id === 'arch-old2' && !s.archived));
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 P10: ALL GREEN' : `\nACCEPTANCE P10: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env node
// Acceptation P11 (sans navigateur) : temps réel complet. Vrai daemon + vrai repo git tmp + client WS.
// Couvre : (1) `git checkout` en CLI sur le CHECKOUT PRINCIPAL → worktree_update (nouvelle branche)
// poussé en temps réel (< 500 ms) sans qu'aucun client n'ait `watch`é ce worktree ; (2) PATCH /settings
// → settings_update reçu par un client abonné au topic 'settings'.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } 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-p11-'));
const repo = join(tmp, 'repo');
execFileSync('mkdir', ['-p', repo]);
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');
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 = 6000) => {
const t0 = Date.now();
while (Date.now() - t0 < timeout) {
const m = state.msgs.find(pred);
if (m) return m;
await sleep(40);
}
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', 'settings'] });
// ---- (1) checkout du PRINCIPAL en CLI → worktree_update sans watch client ----
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
check('POST /repos → 201', addRepo.status === 201);
await sleep(1000); // laisse chokidar finir le scan initial du watcher permanent du principal
c.state.msgs.length = 0;
const t0 = Date.now();
git('checkout', '-b', 'feature'); // changement de branche du checkout principal, hors Arboretum
const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 5000);
const dt = branchMsg ? Date.now() - t0 : -1;
check('checkout principal en CLI → worktree_update (sans watch client)', !!branchMsg, branchMsg ? `${dt}ms` : 'timeout');
check('latence temps réel < 500 ms', branchMsg !== null && dt >= 0 && dt < 500, `${dt}ms`);
// ---- (2) PATCH /settings → settings_update reçu par l'abonné 'settings' ----
c.state.msgs.length = 0;
const patch = await j('/api/v1/settings', 'PATCH', cookie, { retentionDays: 7 });
check('PATCH /settings → 200', patch.status === 200);
const settingsMsg = await c.waitMsg((m) => m.type === 'settings_update' && m.settings?.retentionDays === 7, 3000);
check('settings_update reçu avec le nouvel état', !!settingsMsg);
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 P11: ALL GREEN' : `\nACCEPTANCE P11: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+149
View File
@@ -0,0 +1,149 @@
#!/usr/bin/env node
// Acceptation P12a (sans navigateur, sans réseau/quota) : services git distants + clone. Vrai daemon
// + credential factice + clone d'un dépôt bare LOCAL (chemin de fichier, pas de réseau). Couvre :
// création de credential (secret chiffré), POST /repos/clone (202) → progression WS clone_update →
// done → repo auto-enregistré, ET surtout : le secret en clair est ABSENT de l'API, de la DB et du
// .git/config du dépôt cloné (garde-fou « jamais de fuite de secret »).
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } 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 = 7555;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const SECRET = 'arb-secret-token-9876XYZ'; // token factice : ne doit JAMAIS fuiter en clair
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-p12-'));
const work = join(tmp, 'work'); // racine de scan + destination des clones
const src = join(tmp, 'src'); // dépôt source (working)
const bare = join(tmp, 'source.git'); // remote bare local (file path)
const dbPath = join(tmp, 'a.db');
mkdirSync(work, { recursive: true });
mkdirSync(src, { recursive: true });
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' });
g(src, 'init', '-b', 'main');
g(src, 'config', 'user.email', 'test@arboretum.dev');
g(src, 'config', 'user.name', 'Test');
writeFileSync(join(src, 'README.md'), '# cloned demo\n');
g(src, 'add', '-A');
g(src, 'commit', '-m', 'init');
execFileSync('git', ['clone', '--bare', src, bare], { stdio: 'pipe' });
const srv = spawn(
'node',
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', dbPath, '--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 = 15000) => {
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);
// racine de scan = work (confine la destination du clone).
const patch = await j('/api/v1/settings', 'PATCH', cookie, { scanRoots: [work] });
check('PATCH scanRoots → 200', patch.status === 200);
// credential factice (secret chiffré côté serveur).
const createCred = await j('/api/v1/git-connections', 'POST', cookie, {
label: 'fake', service: 'gitea', authType: 'pat', baseUrl: 'http://localhost:9999', secret: SECRET,
});
const credBody = await createCred.json();
const credId = credBody.credential?.id;
check('POST /git-connections → 201', createCred.status === 201 && !!credId);
check('réponse de création SANS secret en clair', !JSON.stringify(credBody).includes(SECRET));
check('réponse expose secretLast4 (et hasSecret)', credBody.credential?.hasSecret === true && credBody.credential?.secretLast4 === SECRET.slice(-4));
// GET liste : pas de secret.
const listed = await (await j('/api/v1/git-connections', 'GET', cookie)).json();
check('GET /git-connections SANS secret en clair', !JSON.stringify(listed).includes(SECRET));
// WS abonné aux clones.
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: ['clones', 'worktrees'] });
// clone du bare local → dest sous la racine de scan.
const dest = join(work, 'cloned');
const clone = await j('/api/v1/repos/clone', 'POST', cookie, { credentialId: credId, remoteUrl: bare, dest });
const cloneBody = await clone.json();
check('POST /repos/clone → 202 + operationId', clone.status === 202 && !!cloneBody.operationId);
const doneMsg = await c.waitMsg((m) => m.type === 'clone_update' && m.operation?.id === cloneBody.operationId && m.operation?.state === 'done');
check('clone_update state=done reçu via WS', !!doneMsg, doneMsg ? `repoId=${doneMsg.operation.repoId}` : 'timeout');
check('le clone a produit un repoId (auto-enregistré)', !!doneMsg?.operation?.repoId);
// repo enregistré + visible.
const repos = await (await j('/api/v1/repos', 'GET', cookie)).json();
const cloned = (repos.repos ?? []).find((r) => r.path === dest);
check('repo cloné enregistré et listé', !!cloned);
check('le dépôt cloné existe sur disque (README.md)', existsSync(join(dest, 'README.md')));
// ---- garde-fou « pas de fuite de secret » ----
const gitConfig = existsSync(join(dest, '.git', 'config')) ? readFileSync(join(dest, '.git', 'config'), 'utf8') : '';
check('secret ABSENT du .git/config du clone', !gitConfig.includes(SECRET));
const dbBytes = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]
.filter((p) => existsSync(p))
.map((p) => readFileSync(p).toString('latin1'))
.join('');
check('secret ABSENT de la base (chiffré au repos)', !dbBytes.includes(SECRET));
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 P12: ALL GREEN' : `\nACCEPTANCE P12: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env node
// Acceptation P13 (sans navigateur, sans quota Claude) : « Démarrer le projet » (lancement
// multi-terminaux). Vrai daemon + vrai repo git tmp + vrai client WS. Couvre : exposition/persistance
// de launch_commands (+ broadcast repo_update), auto-détection (package.json/Procfile/compose),
// lancement d'un terminal par commande activée (même launchRunId, command bash, titre = label),
// auto-type réellement exécuté (marqueur dans le ring) dans un shell INTERACTIF (survit à la commande),
// bornage anti-traversal du cwd + sous-dossier valide, sélection par commandIds, filtrage des désactivées,
// et « tout arrêter ».
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } 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 = 7553;
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-p13-'));
const repo = join(tmp, 'demo-repo');
mkdirSync(repo, { recursive: true });
mkdirSync(join(repo, 'sub'), { 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');
// Fichiers pour l'auto-détection.
writeFileSync(join(repo, 'package.json'), JSON.stringify({ scripts: { dev: 'echo dev', build: 'echo build', test: 'echo test' } }));
writeFileSync(join(repo, 'Procfile'), 'web: echo procweb\n');
writeFileSync(join(repo, 'docker-compose.yml'), 'services: {}\n');
writeFileSync(join(repo, 'README.md'), '# demo\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));
// Client WS multiplexé (contrôle JSON + sortie binaire → ring décodé en latin1).
function wsClient(cookie) {
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
ws.binaryType = 'arraybuffer';
const state = { msgs: [], outputs: new Map() };
ws.on('message', (data, isBinary) => {
if (!isBinary) {
state.msgs.push(JSON.parse(String(data)));
return;
}
const buf = Buffer.from(data);
const type = buf.readUInt8(0);
const channel = buf.readUInt32LE(1);
const payload = buf.subarray(5);
if (type === 0x02) state.outputs.set(channel, payload.toString('latin1'));
else state.outputs.set(channel, ((state.outputs.get(channel) ?? '') + payload.toString('latin1')).slice(-200000));
});
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 && cookie.startsWith('arb_session='));
// Enregistre le repo.
const reg = await j('/api/v1/repos', 'POST', cookie, { path: repo });
const repoId = (await reg.json()).repo?.id;
check('register repo', reg.status === 201 && !!repoId);
// launchCommands vide par défaut.
const list0 = await (await j('/api/v1/repos', 'GET', cookie)).json();
const r0 = list0.repos.find((r) => r.id === repoId);
check('launchCommands défaut = []', Array.isArray(r0?.launchCommands) && r0.launchCommands.length === 0);
// Auto-détection.
const det = await (await j(`/api/v1/repos/${repoId}/launch/detect`, 'GET', cookie)).json();
const runs = (det.suggestions ?? []).map((s) => s.run);
check(
'detect : package.json + Procfile + docker-compose',
runs.includes('npm run dev') && runs.includes('npm run build') && runs.some((r) => r.startsWith('echo procweb')) && runs.includes('docker compose up'),
`${runs.length} suggestions`,
);
check('detect : dev activé, build désactivé (heuristique)', (det.suggestions.find((s) => s.run === 'npm run dev')?.enabled === true) && (det.suggestions.find((s) => s.run === 'npm run build')?.enabled === false));
// Abonnement worktrees pour vérifier le broadcast repo_update.
const c1 = wsClient(cookie);
await new Promise((res, rej) => (c1.ws.on('open', res), c1.ws.on('error', rej)));
c1.send({ type: 'hello', protocol: 1 });
await c1.waitMsg((m) => m.type === 'hello_ok');
c1.send({ type: 'sub', topics: ['worktrees', 'sessions'] });
await sleep(200);
const nonce = String(token).slice(-6);
const commands = [
{ id: 'c-web', label: 'web', run: `echo ARB_LAUNCH_OK_${nonce}; echo ARB_FLAGS_$-; sleep 30`, enabled: true },
{ id: 'c-api', label: 'api', run: 'sleep 30', enabled: true },
{ id: 'c-build', label: 'build', run: 'echo SHOULD_NOT_RUN', enabled: false },
{ id: 'c-sub', label: 'sub', run: 'pwd; sleep 30', cwd: 'sub', enabled: false },
{ id: 'c-esc', label: 'esc', run: 'pwd', cwd: '../../etc', enabled: false },
];
const patch = await j(`/api/v1/repos/${repoId}`, 'PATCH', cookie, { launchCommands: commands });
const patched = (await patch.json()).repo;
check('PATCH launchCommands persiste', patch.status === 200 && patched.launchCommands.length === 5);
const evt = await c1.waitMsg((m) => m.type === 'repo_update' && m.repo?.id === repoId && (m.repo.launchCommands?.length ?? 0) === 5);
check('broadcast repo_update porte launchCommands', !!evt);
// Lancement par défaut (commandes activées : web, api).
const launch = await j(`/api/v1/repos/${repoId}/launch`, 'POST', cookie, {});
const lr = await launch.json();
check('POST /launch → N sessions (activées only)', launch.status === 201 && lr.sessions?.length === 2, `${lr.sessions?.length} sessions`);
const runIds = new Set(lr.sessions.map((s) => s.launchRunId));
check('même launchRunId sur tous les terminaux', runIds.size === 1 && [...runIds][0], [...runIds][0]);
check('command = bash + titre = label', lr.sessions.every((s) => s.command === 'bash') && lr.sessions.map((s) => s.title).sort().join(',') === 'api,web');
const launchRunId = [...runIds][0];
// Attache au terminal « web » → l'auto-type a été exécuté (marqueur) dans un shell INTERACTIF.
const webSid = lr.sessions.find((s) => s.title === 'web').id;
c1.send({ type: 'attach', sessionId: webSid, mode: 'interactive', cols: 120, rows: 32 });
const att = await c1.waitMsg((m) => m.type === 'attached' && m.sessionId === webSid);
await sleep(1200);
const out = c1.state.outputs.get(att.channel) ?? '';
check('auto-type exécuté (marqueur dans le ring)', out.includes(`ARB_LAUNCH_OK_${nonce}`), `${out.length} o`);
check('shell interactif (flags $- contiennent i)', /ARB_FLAGS_[a-zA-Z]*i/.test(out));
// Le shell survit à la commande (sleep encore vivant).
const sess1 = await (await j('/api/v1/sessions', 'GET', cookie)).json();
const apiSid = lr.sessions.find((s) => s.title === 'api').id;
check('shell survivant (session live)', sess1.sessions.find((s) => s.id === apiSid)?.live === true);
// Sélection par commandIds (web seul).
const one = await (await j(`/api/v1/repos/${repoId}/launch`, 'POST', cookie, { commandIds: ['c-web'] })).json();
check('commandIds : sous-ensemble', one.sessions?.length === 1 && one.sessions[0].title === 'web');
// Sous-dossier valide : pwd sous le worktree.
const subRes = await (await j(`/api/v1/repos/${repoId}/launch`, 'POST', cookie, { commandIds: ['c-sub'] })).json();
const subSid = subRes.sessions?.[0]?.id;
c1.send({ type: 'attach', sessionId: subSid, mode: 'interactive', cols: 120, rows: 32 });
const attSub = await c1.waitMsg((m) => m.type === 'attached' && m.sessionId === subSid);
await sleep(800);
check('cwd sous-dossier borné (pwd dans /sub)', (c1.state.outputs.get(attSub.channel) ?? '').includes('/sub'));
// Traversal rejeté : cwd ../../etc.
const esc = await j(`/api/v1/repos/${repoId}/launch`, 'POST', cookie, { commandIds: ['c-esc'] });
check('cwd traversal rejeté (4xx)', esc.status >= 400 && esc.status < 500, `status ${esc.status}`);
// « Tout arrêter » : kill de tous les terminaux du launchRunId initial.
const before = (await (await j('/api/v1/sessions', 'GET', cookie)).json()).sessions.filter((s) => s.launchRunId === launchRunId);
for (const s of before) await j(`/api/v1/sessions/${s.id}`, 'DELETE', cookie);
// Un shell interactif ignore SIGTERM (standard) → mort garantie au SIGKILL après le délai de grâce (~5 s).
await sleep(6500);
const after = (await (await j('/api/v1/sessions', 'GET', cookie)).json()).sessions.filter((s) => s.launchRunId === launchRunId);
check('tout arrêter → terminaux non vivants', before.length === 2 && after.length === 2 && after.every((s) => !s.live));
c1.ws.close();
} catch (err) {
check('exception', false, String(err && err.stack ? err.stack : err));
} finally {
srv.kill('SIGTERM');
await sleep(1500);
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
console.log(failed.length === 0 ? '\nACCEPTANCE P13: ALL GREEN' : `\nACCEPTANCE P13: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+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);
}
+227
View File
@@ -0,0 +1,227 @@
#!/usr/bin/env node
// Acceptation P17 : « le terminal reste tout noir alors que la session tourne ».
//
// Cause racine reproduite ici : le replay d'attache est une frame BINAIRE, et le client n'apprend le
// numéro de canal qu'avec le message `attached`. Émis AVANT, le replay tombait sur un canal inconnu et
// était jeté en silence : rien à l'écran jusqu'au prochain octet spontané du PTY, c'est-à-dire jamais
// pour un TUI au repos. Ce script vérifie l'ordre réel des trames sur un VRAI WebSocket, et couvre au
// passage les attaches sans écran et l'épilogue de sortie.
//
// Aucun quota Claude consommé : commande `bash`.
import { spawn } from 'node:child_process';
import { mkdtempSync, rmSync } 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 = 7549;
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-p17-'));
// Daemon lancé avec un environnement POLLUÉ, exactement comme lorsqu'il est démarré depuis une
// session Claude Code (cas vécu : l'app de bureau lancée par un agent). Ces marqueurs ne doivent
// JAMAIS atteindre les sessions qu'il lance, sinon le CLI se croit sous-session et coupe la
// sauvegarde de son transcript (plus d'historique, plus de --resume).
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--no-discover'], {
env: {
...process.env,
ARBORETUM_LOG: 'warn',
CLAUDECODE: '1',
CLAUDE_CODE_CHILD_SESSION: '1',
CLAUDE_CODE_SESSION_ID: 'parent-session-id',
CLAUDE_PID: '424242',
ARB_MARQUEUR_LEGITIME: 'conserve-moi',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
let srvOut = '';
srv.stdout.on('data', (d) => (srvOut += d));
srv.stderr.on('data', (d) => (srvOut += d));
/**
* Client WS qui conserve la CHRONOLOGIE des trames (`frames`), texte et binaire mêlés : c'est le seul
* moyen de tester un ordre. Les frames binaires sont décodées en {type, channel, payload}.
*/
function wsClient(cookie) {
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
ws.binaryType = 'arraybuffer';
const frames = [];
const msgs = [];
ws.on('message', (data, isBinary) => {
if (!isBinary) {
const msg = JSON.parse(String(data));
msgs.push(msg);
frames.push({ kind: 'text', msg });
return;
}
const buf = Buffer.from(data);
frames.push({ kind: 'binary', type: buf.readUInt8(0), channel: buf.readUInt32LE(1), payload: buf.subarray(5) });
});
const waitMsg = async (pred, timeout = 8000) => {
const t0 = Date.now();
while (Date.now() - t0 < timeout) {
const m = msgs.find(pred);
if (m) return m;
await sleep(50);
}
return null;
};
/**
* Sortie telle que le VRAI client la peindrait : il n'enregistre un canal qu'en recevant `attached`
* et jette toute frame binaire arrivée avant. On imite ce comportement, sinon ce script verrait un
* écran que le navigateur, lui, n'affiche pas.
*/
const outputOf = (channel) => {
const known = frames.findIndex((f) => f.kind === 'text' && f.msg.type === 'attached' && f.msg.channel === channel);
if (known < 0) return '';
return frames
.slice(known)
.filter((f) => f.kind === 'binary' && f.channel === channel)
.map((f) => f.payload.toString('latin1'))
.join('');
};
return { ws, frames, msgs, waitMsg, outputOf, send: (m) => ws.send(JSON.stringify(m)) };
}
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 && cookie.startsWith('arb_session='));
const api = (path, init = {}) =>
fetch(`${ORIGIN}${path}`, { ...init, headers: { 'Content-Type': 'application/json', Origin: ORIGIN, Cookie: cookie, ...(init.headers ?? {}) } });
const created = await api('/api/v1/sessions', { method: 'POST', body: JSON.stringify({ cwd: tmp, command: 'bash' }) });
const sid = (await created.json()).session.id;
check('spawn bash', created.status === 201 && !!sid);
// --- 1. Première attache : de la sortie existe déjà dans le ring ---
const c1 = wsClient(cookie);
await new Promise((res, rej) => (c1.ws.on('open', res), c1.ws.on('error', rej)));
c1.send({ type: 'hello', protocol: 1 });
await c1.waitMsg((m) => m.type === 'hello_ok');
c1.send({ type: 'attach', sessionId: sid, mode: 'interactive', cols: 120, rows: 32 });
const att1 = await c1.waitMsg((m) => m.type === 'attached');
check('attach interactif + controlling', att1?.controlling === true);
await sleep(300);
c1.send({ type: 'stdin', channel: att1.channel, data: 'echo MARQUEUR-ECRAN-1\r' });
await sleep(800);
check('stdin → output', c1.outputOf(att1.channel).includes('MARQUEUR-ECRAN-1'));
// --- 2. Ré-attache (nouvelle connexion, PTY silencieux) : l'écran DOIT revenir ---
// C'est le scénario vécu : l'app est rechargée, Claude est à son prompt et n'émet plus rien.
const c2 = wsClient(cookie);
await new Promise((res, rej) => (c2.ws.on('open', res), c2.ws.on('error', rej)));
c2.send({ type: 'hello', protocol: 1 });
await c2.waitMsg((m) => m.type === 'hello_ok');
c2.send({ type: 'attach', sessionId: sid, mode: 'interactive', cols: 120, rows: 32 });
const att2 = await c2.waitMsg((m) => m.type === 'attached');
await sleep(400);
const idxAttached = c2.frames.findIndex((f) => f.kind === 'text' && f.msg.type === 'attached');
const idxResync = c2.frames.findIndex((f) => f.kind === 'binary' && f.type === 0x02);
check('ORDRE : `attached` précède le replay binaire', idxAttached >= 0 && idxResync > idxAttached, `attached@${idxAttached}, resync@${idxResync}`);
check('le replay porte le canal annoncé', c2.frames[idxResync]?.channel === att2.channel);
const replay = c2.outputOf(att2.channel);
check('l’écran se reconstitue à la ré-attache (fin de l’écran noir)', replay.includes('MARQUEUR-ECRAN-1'), `${replay.length} octets rejoués`);
// --- 3. Un observateur peint aussi : il doit recevoir son replay ---
const c3 = wsClient(cookie);
await new Promise((res, rej) => (c3.ws.on('open', res), c3.ws.on('error', rej)));
c3.send({ type: 'hello', protocol: 1 });
await c3.waitMsg((m) => m.type === 'hello_ok');
c3.send({ type: 'attach', sessionId: sid, mode: 'observer', cols: 100, rows: 30 });
const att3 = await c3.waitMsg((m) => m.type === 'attached');
await sleep(400);
check('un observateur reçoit son replay (non-controlling)', att3?.controlling === false && c3.outputOf(att3.channel).includes('MARQUEUR-ECRAN-1'));
// --- 4. Attache SANS écran : ne vole pas le contrôle, ne reçoit rien ---
// Régression : le DialogPrompt attachait en interactif avec des dimensions bidon, prenait le
// `controlling` et figeait la géométrie du TUI pour le terminal ouvert ensuite.
const c4 = wsClient(cookie);
await new Promise((res, rej) => (c4.ws.on('open', res), c4.ws.on('error', rej)));
c4.send({ type: 'hello', protocol: 1 });
await c4.waitMsg((m) => m.type === 'hello_ok');
c4.send({ type: 'attach', sessionId: sid, mode: 'interactive', cols: 80, rows: 24, screen: false });
const att4 = await c4.waitMsg((m) => m.type === 'attached');
await sleep(300);
check('attache sans écran : jamais controlling', att4?.controlling === false);
check('attache sans écran : aucune frame binaire', !c4.frames.some((f) => f.kind === 'binary'));
c2.send({ type: 'stdin', channel: att2.channel, data: 'echo APRES-AVEUGLE\r' });
await sleep(800);
check('attache sans écran : ne reçoit pas la sortie du PTY', !c4.frames.some((f) => f.kind === 'binary'));
check('le terminal à écran garde le contrôle et fonctionne', c2.outputOf(att2.channel).includes('APRES-AVEUGLE'));
// elle garde en revanche le droit d'écrire (c'est sa seule raison d'être)
c4.send({ type: 'stdin', channel: att4.channel, data: 'echo ECRIT-PAR-AVEUGLE\r' });
await sleep(800);
check('attache sans écran : peut écrire', c2.outputOf(att2.channel).includes('ECRIT-PAR-AVEUGLE'));
// --- 5. Épilogue de sortie : la raison de la mort est visible DANS le terminal ---
const dying = await api('/api/v1/sessions', { method: 'POST', body: JSON.stringify({ cwd: tmp, command: 'bash' }) });
const dsid = (await dying.json()).session.id;
const c5 = wsClient(cookie);
await new Promise((res, rej) => (c5.ws.on('open', res), c5.ws.on('error', rej)));
c5.send({ type: 'hello', protocol: 1 });
await c5.waitMsg((m) => m.type === 'hello_ok');
c5.send({ type: 'attach', sessionId: dsid, mode: 'interactive', cols: 80, rows: 24 });
const att5 = await c5.waitMsg((m) => m.type === 'attached');
await sleep(300);
c5.send({ type: 'stdin', channel: att5.channel, data: 'exit 3\r' });
const detached5 = await c5.waitMsg((m) => m.type === 'detached' && m.channel === att5.channel, 8000);
const epilogue = c5.outputOf(att5.channel);
check('épilogue : le code de sortie est écrit dans le terminal', epilogue.includes('[arboretum]') && epilogue.includes('exited with code 3'), epilogue.slice(-60).replace(/[\r\n]+/g, ' '));
check('épilogue reçu AVANT le detached', !!detached5);
// --- 6. L'environnement du PTY est assaini des marqueurs de la session parente ---
// Le nom du marqueur est CONCATÉNÉ dans la commande ('EN' + 'V:') pour que l'écho local du terminal
// ne ressemble pas au résultat : sinon on relit sa propre frappe et le test passe toujours.
c2.send({ type: 'stdin', channel: att2.channel, data: 'echo "EN""V:[$CLAUDECODE][$CLAUDE_CODE_CHILD_SESSION][$CLAUDE_CODE_SESSION_ID][$CLAUDE_PID]"\r' });
await sleep(900);
const envLine = /ENV:\[[^\]]*\]\[[^\]]*\]\[[^\]]*\]\[[^\]]*\]/.exec(c2.outputOf(att2.channel).replace(/\r?\n/g, ''))?.[0] ?? '';
check('les marqueurs de session parente ne sont pas transmis au PTY', envLine === 'ENV:[][][][]', envLine || 'non observé');
c2.send({ type: 'stdin', channel: att2.channel, data: 'echo "GARDE:[$ARB_MARQUEUR_LEGITIME]"\r' });
await sleep(900);
check(
'le reste de l’environnement est bien transmis',
c2.outputOf(att2.channel).includes('GARDE:[conserve-moi]'),
);
// --- 7. Le PTY n'a pas été redimensionné par les attaches sans écran ---
const listed = await (await api('/api/v1/sessions')).json();
check('session toujours vivante après tout ça', listed.sessions.some((s) => s.id === sid && s.live));
for (const c of [c1, c2, c3, c4, c5]) 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.exitCode === null);
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
if (failed.length > 0) console.log(`\n--- sortie du daemon ---\n${srvOut.slice(-2000)}`);
console.log(failed.length === 0 ? '\nACCEPTANCE P17: ALL GREEN' : `\nACCEPTANCE P17: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+1 -1
View File
@@ -22,7 +22,7 @@ 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}` : ''}`);
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p2-'));
+1 -1
View File
@@ -19,7 +19,7 @@ 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}` : ''}`);
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p3-'));
+2 -2
View File
@@ -2,7 +2,7 @@
// Acceptation P4 (sans navigateur, sans quota Claude) : Web Push + commande WS `answer`.
// Vrai daemon. Couvre : garde auth + Origin sur les routes push, clé VAPID exposée, subscribe
// idempotent / malformé / unsubscribe, et la commande `answer` (rejets INVALID_ANSWER /
// NOT_CONTROLLING — la validation fine `select` vit dans les tests vitest sur fixtures).
// NOT_CONTROLLING : la validation fine `select` vit dans les tests vitest sur fixtures).
import { spawn } from 'node:child_process';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
@@ -20,7 +20,7 @@ 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}` : ''}`);
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p4-'));
+1 -1
View File
@@ -20,7 +20,7 @@ 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}` : ''}`);
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
};
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p5-'));
+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env node
// Acceptation P7 (sans navigateur, sans quota Claude) : moteur git « IDE » + API fichiers + watcher
// FS temps réel. Vrai daemon + vrai repo git tmp + vrai client WS. Couvre : GET /changes & /diff,
// staging sélectif + commit(staged), API fichiers content GET/PUT (Monaco) + refus de traversal,
// abonnement ciblé watch → worktree_changes à l'édition, checkout externe → worktree_update, unwatch.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync, 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 = 7547;
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-p7-'));
const repo = join(tmp, 'demo-repo');
execFileSync('mkdir', ['-p', repo]);
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');
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'] });
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 /changes : un fichier modifié + un untracked ----
appendFileSync(join(repo, 'README.md'), 'edited line\n');
writeFileSync(join(repo, 'untracked.txt'), 'new\n');
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
const byPath = Object.fromEntries((ch.changes ?? []).map((c2) => [c2.path, c2]));
check('GET /changes : README.md modifié non indexé', byPath['README.md']?.unstaged === true && byPath['README.md']?.staged === false);
check('GET /changes : untracked.txt détecté', byPath['untracked.txt']?.untracked === true);
// ---- GET /diff ----
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+edited line'));
// ---- staging sélectif + commit(staged) ----
const stage = await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['README.md'] });
const staged = await stage.json();
check('POST /stage → README.md staged', staged.worktree?.git?.stagedCount >= 1);
const commit = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'commit staged only', mode: 'staged' });
check('POST /commit (mode=staged) → 200', commit.status === 200);
const ch2 = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
const paths2 = (ch2.changes ?? []).map((c2) => c2.path);
check('après commit staged : README committé, untracked restant', !paths2.includes('README.md') && paths2.includes('untracked.txt'));
// ---- API fichiers (Monaco) : GET content + PUT + refus traversal ----
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=untracked.txt`, 'GET', cookie)).json();
check('GET /files/content : contenu lu + langage', get1.content === 'new\n');
const put = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
check('PUT /files/content (création) → 200', put.status === 200);
const get2 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
check('GET après PUT : contenu écrit + langage typescript', get2.content === 'export const x = 1\n' && get2.language === 'typescript');
const trav = await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=${encodeURIComponent('../escape.txt')}`, 'GET', cookie);
check('GET /files/content : traversal ../ refusé', trav.status === 400 || trav.status === 403);
// ---- temps réel : watch → worktree_changes à l'édition ----
c.send({ type: 'watch', repoId, path: repo });
await sleep(900); // laisse chokidar finir son scan initial
const t0 = Date.now();
writeFileSync(join(repo, 'live.txt'), 'live edit\n');
const changesMsg = await c.waitMsg((m) => m.type === 'worktree_changes' && m.path === repo, 6000);
check('watch → worktree_changes ciblé reçu', !!changesMsg, changesMsg ? `${Date.now() - t0}ms` : 'timeout');
const updMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === repo, 3000);
check('édition → worktree_update diffusé', !!updMsg);
// ---- checkout externe (CLI) → worktree_update avec nouvelle branche ----
c.state.msgs.length = 0; // reset pour ne capter que les nouveaux events
git('branch', 'feature');
git('checkout', 'feature');
const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 6000);
check('checkout externe → branche principale mise à jour en temps réel', !!branchMsg);
// ---- unwatch : plus de worktree_changes ----
c.send({ type: 'unwatch', repoId, path: repo });
await sleep(300);
c.state.msgs.length = 0;
writeFileSync(join(repo, 'after-unwatch.txt'), 'x\n');
const afterUnwatch = await c.waitMsg((m) => m.type === 'worktree_changes', 1500);
check('unwatch → plus de worktree_changes', !afterUnwatch);
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 P7: ALL GREEN' : `\nACCEPTANCE P7: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env node
// Acceptation P8 (sans navigateur) : API fichiers de l'éditeur Monaco + garde-fou conflit (mtime).
// Vrai daemon + vrai repo git tmp. Couvre : GET content (+mtime), PUT avec baseMtime correct → 200,
// PUT avec baseMtime périmé → 409 STALE_FILE, PUT sans baseMtime (overwrite) → 200, diff après
// édition cohérent, fs/list?includeFiles=1 (isFile), refus de traversal.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const PORT = 7552;
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-p8-'));
const repo = join(tmp, 'demo-repo');
execFileSync('mkdir', ['-p', repo]);
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');
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 content : contenu + mtime ----
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=README.md`, 'GET', cookie)).json();
check('GET /files/content : contenu + mtime', get1.content === '# demo\n' && typeof get1.mtime === 'number');
const mtime0 = get1.mtime;
// ---- PUT avec baseMtime correct → 200 + nouveau mtime ----
const put1 = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
wt: repo, path: 'README.md', content: '# demo\nedited via editor\n', baseMtime: mtime0,
});
const put1Body = await put1.json();
check('PUT (baseMtime correct) → 200 + mtime', put1.status === 200 && typeof put1Body.mtime === 'number');
// ---- PUT avec baseMtime périmé (l'ancien) → 409 STALE_FILE ----
const putStale = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
wt: repo, path: 'README.md', content: 'concurrent overwrite\n', baseMtime: mtime0,
});
const staleBody = await putStale.json();
check('PUT (baseMtime périmé) → 409 STALE_FILE', putStale.status === 409 && staleBody.error?.code === 'STALE_FILE');
// ---- PUT sans baseMtime (overwrite forcé) → 200 ----
const putForce = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
wt: repo, path: 'README.md', content: '# demo\nforced\n',
});
check('PUT (sans baseMtime, overwrite) → 200', putForce.status === 200);
// ---- diff après édition ----
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
check('GET /changes : README.md modifié', (ch.changes ?? []).some((c) => c.path === 'README.md' && c.unstaged));
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+forced'));
// ---- création d'un nouveau fichier + lecture du langage ----
const putNew = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
check('PUT (création src/app.ts) → 200', putNew.status === 200);
const getNew = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
check('GET nouveau fichier : langage typescript', getNew.language === 'typescript');
// ---- fs/list?includeFiles=1 : remonte les fichiers (arbre IDE) ----
const fs = await (await j(`/api/v1/fs/list?path=${enc}&includeFiles=1`, 'GET', cookie)).json();
const readme = (fs.entries ?? []).find((e) => e.name === 'README.md');
check('fs/list?includeFiles=1 : README.md (isFile)', readme?.isFile === true);
// ---- refus de traversal ----
const trav = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: '../escape.txt', content: 'x' });
check('PUT traversal ../ refusé', trav.status === 400 || trav.status === 403);
} 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 P8: ALL GREEN' : `\nACCEPTANCE P8: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env node
// Acceptation P9 (sans navigateur) : cycle git propre depuis l'UI (primitives P7). Vrai daemon +
// vrai repo git tmp + remote bare local (file://). Couvre : staging sélectif → commit ne prend QUE
// le sélectionné ; amend d'un commit NON poussé → OK (HEAD change) ; amend d'un commit POUSSÉ → 409
// ALREADY_PUSHED ; pull --ff-only fast-forward → OK ; pull en divergence → refusé proprement.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const PORT = 7553;
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-p9-'));
const repo = join(tmp, 'repo');
const bare = join(tmp, 'bare.git');
const clone2 = join(tmp, 'clone2');
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
const cfg = (cwd) => {
g(cwd, 'config', 'user.email', 'test@arboretum.dev');
g(cwd, 'config', 'user.name', 'Test');
};
execFileSync('mkdir', ['-p', repo]);
g(repo, 'init', '-b', 'main');
cfg(repo);
writeFileSync(join(repo, 'a.txt'), 'a\n');
g(repo, 'add', '-A');
g(repo, 'commit', '-m', 'init');
execFileSync('git', ['init', '--bare', bare], { stdio: 'pipe' });
g(bare, 'symbolic-ref', 'HEAD', 'refs/heads/main'); // pour que les clones se placent sur main
g(repo, 'remote', 'add', 'origin', bare);
g(repo, 'push', '-u', 'origin', 'main');
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);
const changes = async () => (await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json()).changes ?? [];
// ---- staging sélectif : modifier 2 fichiers, n'indexer que a.txt, committer staged ----
writeFileSync(join(repo, 'a.txt'), 'a modified\n');
writeFileSync(join(repo, 'b.txt'), 'b new\n');
await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['a.txt'] });
const commit1 = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a', mode: 'staged' });
check('commit (staged) → 200', commit1.status === 200);
const afterCommit = (await changes()).map((c) => c.path);
check('commit ne prend QUE le fichier indexé (b.txt reste, a.txt committé)', !afterCommit.includes('a.txt') && afterCommit.includes('b.txt'));
check('a.txt présent dans le dernier commit', g(repo, 'show', '--name-only', '--format=', 'HEAD').includes('a.txt'));
// ---- amend d'un commit NON poussé → OK, le sujet de HEAD change ----
const amendOk = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a (amended)', amend: true });
check('amend (commit non poussé) → 200', amendOk.status === 200);
check('amend modifie le sujet de HEAD', g(repo, 'log', '-1', '--format=%s').trim() === 'only a (amended)');
// ---- push, puis amend d'un commit POUSSÉ → 409 ALREADY_PUSHED ----
const push = await j(`/api/v1/repos/${repoId}/worktrees/push`, 'POST', cookie, { path: repo });
check('push → 200', push.status === 200);
const amendPushed = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'too late', amend: true });
const amendBody = await amendPushed.json();
check('amend (commit poussé) → 409 ALREADY_PUSHED', amendPushed.status === 409 && amendBody.error?.code === 'ALREADY_PUSHED');
// ---- pull --ff-only : un commit distant en avance → fast-forward OK ----
execFileSync('git', ['clone', bare, clone2], { stdio: 'pipe' });
cfg(clone2);
writeFileSync(join(clone2, 'c.txt'), 'c\n');
g(clone2, 'add', '-A');
g(clone2, 'commit', '-m', 'remote commit');
g(clone2, 'push', 'origin', 'main');
await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
const pullFf = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
check('pull --ff-only (fast-forward) → 200', pullFf.status === 200);
check('le commit distant est intégré (remote commit dans l’historique)', g(repo, 'log', '--format=%s').includes('remote commit'));
// ---- divergence : commit local non poussé + commit distant → pull --ff-only refusé ----
writeFileSync(join(repo, 'a.txt'), 'a local divergent\n');
await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'local divergent', mode: 'all' });
writeFileSync(join(clone2, 'd.txt'), 'd\n');
g(clone2, 'add', '-A');
g(clone2, 'commit', '-m', 'remote divergent');
g(clone2, 'push', 'origin', 'main');
await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
const pullDiv = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
check('pull --ff-only en divergence → refusé (non-200)', pullDiv.status !== 200, `status=${pullDiv.status}`);
} 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 P9: ALL GREEN' : `\nACCEPTANCE P9: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+3 -3
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// Embarque la SPA buildée (packages/web/dist) dans public/ du package server,
// pour que le tarball npm soit autonome. Branché sur le hook "prepack".
// ARBORETUM_PACK_NO_WEB=1 : mode tolérant (CI/smoke) — placeholder à la place du front.
// ARBORETUM_PACK_NO_WEB=1 : mode tolérant (CI/smoke), placeholder à la place du front.
import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -19,10 +19,10 @@ if (!existsSync(webDist)) {
'<!doctype html>\n<html lang="en">\n<head><meta charset="utf-8"><title>Arboretum</title></head>\n' +
'<body><p>Arboretum server is running, but this package was built without the web UI.</p></body>\n</html>\n',
);
console.log('copy-web: ARBORETUM_PACK_NO_WEB=1 — wrote placeholder public/index.html');
console.log('copy-web: ARBORETUM_PACK_NO_WEB=1: wrote placeholder public/index.html');
process.exit(0);
}
console.error(`copy-web: ${webDist} not found — run npm run build -w @arboretum/web first`);
console.error(`copy-web: ${webDist} not found: run npm run build -w @arboretum/web first`);
process.exit(1);
}
+4 -4
View File
@@ -4,7 +4,7 @@
//
// Pourquoi PAS bundleDependencies : embarquer une dépendance qui est aussi un *workspace* via
// bundleDependencies est instable selon l'environnement npm (mode -w, exécution en root sur un
// runner CI, version d'arborist) — npm voit le nœud comme un lien workspace et n'embarque parfois
// runner CI, version d'arborist) : npm voit le nœud comme un lien workspace et n'embarque parfois
// AUCUN fichier ("bundled files: 0"), produisant un paquet cassé chez le consommateur. On élimine
// donc toute magie de bundling : on copie le JS compilé de shared dans dist/_shared et on réécrit
// l'import bare '@arboretum/shared' du serveur vers ce chemin relatif. Zéro node_modules embarqué,
@@ -20,7 +20,7 @@ const inlineDir = join(serverDist, '_shared');
for (const [label, p] of [['dist serveur', serverDist], ['dist shared', sharedDist]]) {
if (!existsSync(p)) {
console.error(`inline-shared: ${label} introuvable (${p}) — lance "npm run build" avant le pack.`);
console.error(`inline-shared: ${label} introuvable (${p}) : lance "npm run build" avant le pack.`);
process.exit(1);
}
}
@@ -38,7 +38,7 @@ for (const name of readdirSync(sharedDist)) {
}
}
if (copied === 0) {
console.error(`inline-shared: aucun .js dans ${sharedDist} — shared n'est pas compilé.`);
console.error(`inline-shared: aucun .js dans ${sharedDist} : shared n'est pas compilé.`);
process.exit(1);
}
@@ -64,7 +64,7 @@ for (const file of walk(serverDist)) {
}
}
if (rewritten === 0) {
console.error(`inline-shared: aucun import '@arboretum/shared' réécrit dans ${serverDist} — build manquant ?`);
console.error(`inline-shared: aucun import '@arboretum/shared' réécrit dans ${serverDist} : build manquant ?`);
process.exit(1);
}
@@ -0,0 +1,235 @@
#!/usr/bin/env node
// Vérification E2E du copier / coller dans le terminal web (régression : la sélection d'xterm n'est
// pas une sélection DOM, le « Copier » natif ne voyait donc rien). Daemon temporaire isolé + session
// `bash` (pas `claude` : pas de quota consommé) + Chromium piloté en CDP : on tape un marqueur, on le
// sélectionne à la souris, Ctrl+Shift+C, et on relit le presse-papier réel du navigateur. Puis
// l'inverse : on remplit le presse-papier, Ctrl+Shift+V, et on vérifie que le PTY l'a reçu.
import { spawn } from 'node:child_process';
import { mkdtempSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { WebSocket } from 'ws';
const PORT = 7411;
const CDP_PORT = 9334;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let failures = 0;
function check(label, ok, detail = '') {
console.log(`${ok ? '✅' : '❌'} ${label}${detail ? ` : ${detail}` : ''}`);
if (!ok) failures++;
}
function findChromium() {
for (const bin of ['/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/google-chrome']) {
if (existsSync(bin)) return bin;
}
return null;
}
/** Client CDP minimal : un socket, corrélation par id. */
function cdp(url) {
const ws = new WebSocket(url, { perMessageDeflate: false });
const pending = new Map();
let seq = 0;
const ready = new Promise((resolve, reject) => {
ws.once('open', resolve);
ws.once('error', reject);
});
ws.on('message', (raw) => {
const msg = JSON.parse(raw.toString());
const entry = pending.get(msg.id);
if (!entry) return;
pending.delete(msg.id);
msg.error ? entry.reject(new Error(msg.error.message)) : entry.resolve(msg.result);
});
return {
ready,
close: () => ws.close(),
send(method, params = {}, sessionId) {
const id = ++seq;
return new Promise((resolve, reject) => {
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);
});
},
};
}
let srv, browser, tmp;
try {
tmp = mkdtempSync(join(tmpdir(), 'arb-clip-'));
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);
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.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).find((c) => c.startsWith('arb_session='));
const cookieValue = cookie?.slice('arb_session='.length) ?? '';
check('login → cookie de session', !!cookie);
const sess = await (
await fetch(`${ORIGIN}/api/v1/sessions`, {
method: 'POST',
headers: { Origin: ORIGIN, Cookie: cookie, 'Content-Type': 'application/json' },
body: JSON.stringify({ cwd: tmp, command: 'bash' }),
})
).json();
const sessionId = sess.session?.id;
check('session bash lancée', !!sessionId);
const chromeBin = findChromium();
check('Chromium disponible', !!chromeBin, chromeBin ?? 'introuvable');
if (!chromeBin || !sessionId) throw new Error('prérequis manquants');
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;
// Presse-papier lisible/écrivable sans geste utilisateur (sinon readText() rejette en headless).
await client.send('Browser.grantPermissions', {
origin: ORIGIN,
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
});
const { targetId } = await client.send('Target.createTarget', { url: 'about:blank' });
const { sessionId: sid } = await client.send('Target.attachToTarget', { targetId, flatten: true });
await client.send('Page.enable', {}, sid);
await client.send('Runtime.enable', {}, sid);
await client.send('Network.enable', {}, sid);
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sid);
await client.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, sid);
const evaluate = async (expression, awaitPromise = false) =>
(await client.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise }, sid)).result?.value;
await client.send('Page.navigate', { url: `${ORIGIN}/sessions/${sessionId}` }, sid);
// attend que xterm soit monté ET que bash ait rendu son invite
let screen = null;
for (let i = 0; i < 80 && !screen; i++) {
await sleep(250);
screen = await evaluate(`(() => { const el = document.querySelector('.xterm-screen'); if (!el) return null; const r = el.getBoundingClientRect(); return r.width > 50 ? JSON.stringify(r) : null; })()`);
}
check('terminal xterm monté', !!screen);
const rect = screen ? JSON.parse(screen) : null;
// Le renderer WebGL peint dans un canvas : `.xterm-rows` est vide, on ne peut RIEN vérifier via le
// DOM. Les preuves passent donc par le système de fichiers (le cwd de la session est `tmp`) et par
// le presse-papier réel du navigateur.
const focusTerm = () => client.send('Runtime.evaluate', { expression: `document.querySelector('.xterm-helper-textarea')?.focus()` }, sid);
const pressEnter = async () => {
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13, text: '\r' }, sid);
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 }, sid);
};
const waitForFile = async (name, tries = 40) => {
for (let i = 0; i < tries; i++) {
if (existsSync(join(tmp, name))) return true;
await sleep(200);
}
return false;
};
// --- Frappe dans le PTY (Input.insertText → textarea xterm → stdin) ---
await focusTerm();
await client.send('Input.insertText', { text: 'touch typed-ok' }, sid);
await pressEnter();
check('le PTY exécute une commande tapée au clavier', await waitForFile('typed-ok'));
// Marqueur affiché à l'écran, cible de la copie
const MARKER = 'COPIE_MOI_4242';
await client.send('Input.insertText', { text: `echo ${MARKER}` }, sid);
await pressEnter();
await sleep(600);
// --- Sélection à la souris sur la zone du terminal, puis Ctrl+Shift+C ---
if (rect) {
const y = rect.y + 8;
await client.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: rect.x + 2, y, button: 'left', clickCount: 1, buttons: 1 }, sid);
await client.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: rect.x + rect.width - 4, y: y + 40, button: 'left', buttons: 1 }, sid);
await client.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: rect.x + rect.width - 4, y: y + 40, button: 'left', clickCount: 1, buttons: 0 }, sid);
}
await sleep(300);
const selection = await evaluate(`(() => { const s = document.querySelector('.xterm')?.classList; return document.getSelection()?.toString() ?? ''; })()`);
// ctrl(2) + shift(8) = 10
const keyOpts = { modifiers: 10, windowsVirtualKeyCode: 67, nativeVirtualKeyCode: 67, key: 'C', code: 'KeyC' };
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', ...keyOpts }, sid);
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', ...keyOpts }, sid);
await sleep(500);
const copied = (await evaluate('navigator.clipboard.readText()', true)) ?? '';
check('Ctrl+Shift+C copie la sélection du terminal', copied.includes(MARKER), JSON.stringify(copied.slice(0, 60)));
// --- Collage : presse-papier → Ctrl+Shift+V → la commande collée doit atteindre le PTY ---
await evaluate(`navigator.clipboard.writeText('touch paste-ok')`, true);
await focusTerm();
const vOpts = { modifiers: 10, windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, key: 'V', code: 'KeyV' };
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', ...vOpts }, sid);
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', ...vOpts }, sid);
await sleep(400);
await pressEnter();
check('Ctrl+Shift+V colle le presse-papier dans le terminal', await waitForFile('paste-ok'));
// --- Ctrl+C ne doit PAS être détourné : il reste SIGINT ---
// `sleep 25` bloque le shell ; si le ^C passe, le shell reprend et exécute la commande suivante.
await focusTerm();
await client.send('Input.insertText', { text: 'sleep 25' }, sid);
await pressEnter();
await sleep(700);
const cOpts = { modifiers: 2, windowsVirtualKeyCode: 67, nativeVirtualKeyCode: 67, key: 'c', code: 'KeyC' };
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', ...cOpts }, sid);
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', ...cOpts }, sid);
await sleep(500);
await client.send('Input.insertText', { text: 'touch interrupt-ok' }, sid);
await pressEnter();
check('Ctrl+C reste transmis au PTY (SIGINT, pas une copie)', await waitForFile('interrupt-ok', 30));
client.close();
} catch (err) {
check('exécution du scénario', false, err?.message ?? String(err));
} finally {
browser?.kill('SIGKILL');
srv?.kill('SIGKILL');
await sleep(300);
if (tmp) rmSync(tmp, { recursive: true, force: true });
}
console.log(failures === 0 ? '\nVERIFY CLIPBOARD: ALL GREEN' : `\nVERIFY CLIPBOARD: ${failures} ÉCHEC(S)`);
process.exit(failures === 0 ? 0 : 1);
+403
View File
@@ -0,0 +1,403 @@
#!/usr/bin/env node
// Vérification E2E de la ZONE CENTRALE de l'IDE, par interaction réelle (pas des captures) : daemon
// temporaire isolé + Chromium headless piloté en CDP + cookie de session injecté. On clique dans
// l'arbre comme un utilisateur, puis on lit le DOM de Monaco.
//
// Ce que ce script prouve, et qu'aucune capture ne prouvait :
// (a) ouvrir un fichier alors qu'AUCUN onglet n'est persisté affiche réellement son contenu. C'est
// le cas nominal qui restait vide et muet : le conteneur de Monaco vivait sous un `v-if`, donc
// l'éditeur n'était jamais créé et aucun watcher ne retentait ;
// (b) fermer le dernier onglet puis réouvrir un fichier réaffiche le contenu (le conteneur ne doit
// pas être détruit, sinon l'éditeur pointe sur un noeud détaché) ;
// (c) sur mobile, toucher un fichier amène la zone centrale au premier plan (l'arbre et l'éditeur
// étant mutuellement exclusifs sous 768 px, un contenu visible EST la preuve de la bascule) ;
// (d) chunk de l'éditeur introuvable : un message et des actions de récupération, pas une zone vide ;
// (e) la bascule Fichiers / Changements liste bien les fichiers modifiés et permet de committer.
//
// Usage : node packages/server/scripts/verify-editor.mjs
// Prérequis : `npm run build` puis `node packages/server/scripts/copy-web.mjs`.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } 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 = 7412;
const CDP_PORT = 9335;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const MARKER = 'ARB_EDITOR_RENDERED_4242';
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
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-editor-'));
let srv = null;
let browser = null;
try {
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 fichier sonde EN PREMIÈRE LIGNE (Monaco virtualise le rendu) ---
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');
writeFileSync(join(repo, 'probe.ts'), `export const probe = '${MARKER}';\n`);
git('add', '-A');
git('commit', '-m', 'commit initial');
// du travail non commité, pour la vue Changements
writeFileSync(join(repo, 'dirty.txt'), 'travail en cours\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 sessionCookie = (login.headers.getSetCookie?.() ?? []).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 repoRes = await (await j('/api/v1/repos', 'POST', { path: repo })).json();
const repoId = repoRes.repo?.id;
const repoLabel = repoRes.repo?.label;
check('dépôt de démonstration enregistré', !!repoId, repoLabel ?? '');
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;
// localStorage est partagé par les cibles d'un même profil : on l'efface pour chaque scénario.
// AUCUN onglet persisté : c'est précisément le cas qui restait vide. `arboretum.locale` n'est pas
// un persistedRef (chaîne brute, pas de JSON).
const seed = (extra = '') =>
`localStorage.clear();localStorage.setItem('arb.theme', '"dark"');localStorage.setItem('arboretum.locale', 'en');${extra}`;
/** Ouvre une cible isolée, authentifiée, avec un état de vue amorcé. */
async function openTarget({ width = 1440, height = 900, extraSeed = '', blocked = [] } = {}) {
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('Page.enable', {}, sessionId);
await client.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 500 }, sessionId);
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
if (blocked.length > 0) await client.send('Network.setBlockedURLs', { urls: blocked }, sessionId);
await client.send('Page.addScriptToEvaluateOnNewDocument', { source: seed(extraSeed) }, sessionId);
const before = client.events.length;
await client.send('Page.navigate', { url: `${ORIGIN}/ide` }, sessionId);
return { targetId, sessionId, before };
}
const evaluate = async (expression, sessionId) =>
(await client.send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)).result?.value;
/** Attend qu'une condition devienne vraie (jamais de sleep fixe sur un rendu asynchrone). */
async function waitFor(fn, tries = 60, delay = 250) {
for (let i = 0; i < tries; i++) {
if (await fn()) return true;
await sleep(delay);
}
return false;
}
// Clic sur une ligne par son libellé exact : les libellés vivent dans un <span> à l'intérieur du
// <button> de la ligne (arbre de projets comme arbre de fichiers).
const clickRow = (label, sessionId) =>
evaluate(
`(() => {
const span = [...document.querySelectorAll('button span')].find((s) => s.textContent.trim() === ${JSON.stringify(label)});
const btn = span?.closest('button');
if (!btn) return false;
btn.click();
return true;
})()`,
sessionId,
);
// Monaco VIRTUALISE : seules les lignes visibles existent dans le DOM, et les espaces sortent en
// U+00A0. La sonde est donc en première ligne, et on normalise avant comparaison.
const editorText = async (sessionId) =>
(await evaluate(
`(() => {
const lines = document.querySelector('.monaco-editor .view-lines');
return lines ? lines.textContent.replace(/\\u00a0/g, ' ') : '';
})()`,
sessionId,
)) ?? '';
const editorBox = async (sessionId) =>
JSON.parse(
(await evaluate(
`JSON.stringify((() => {
const el = document.querySelector('.monaco-editor');
if (!el) return null;
const r = el.getBoundingClientRect();
return { w: Math.round(r.width), h: Math.round(r.height) };
})())`,
sessionId,
)) ?? 'null',
);
const describeError = (e) => {
const d = e.params?.exceptionDetails;
if (d) {
const ex = d.exception ?? {};
const where = d.url ? ` @${d.url}:${d.lineNumber ?? '?'}` : '';
return `${d.text ?? ''} ${ex.description ?? ex.value ?? ''}${where}`.trim();
}
return (e.params?.args ?? []).map((a) => a.description ?? a.value ?? a.type).join(' ');
};
const consoleErrors = (sessionId, before) =>
client.events
.slice(before)
.filter((e) => e.sessionId === sessionId)
.filter((e) => (e.method === 'Runtime.consoleAPICalled' && e.params?.type === 'error') || e.method === 'Runtime.exceptionThrown')
.map(describeError)
.filter((m) => m && !/favicon|manifest\.webmanifest/i.test(m));
/** Déroule l'arbre jusqu'au fichier sonde : dépôt, puis branche, puis fichier. */
async function openProbeFile(sessionId) {
if (!(await waitFor(() => clickRow(repoLabel, sessionId)))) return false;
if (!(await waitFor(() => clickRow('main', sessionId)))) return false;
return waitFor(() => clickRow('probe.ts', sessionId));
}
// --- (a) desktop, aucun onglet persisté : le cas nominal qui restait vide ---
{
const { targetId, sessionId, before } = await openTarget();
const treeReady = await waitFor(async () => !!(await clickRow(repoLabel, sessionId)));
check('a · arbre de projets rendu', treeReady);
// L'éditeur ne doit pas exister avant qu'un fichier soit demandé (chargement paresseux préservé).
check('a · Monaco non chargé avant ouverture d un fichier', (await editorBox(sessionId)) === null);
check('a · navigation jusqu au fichier', await waitFor(() => clickRow('main', sessionId)) && (await waitFor(() => clickRow('probe.ts', sessionId))));
const shown = await waitFor(async () => (await editorText(sessionId)).includes(MARKER));
check('a · le contenu du fichier est réellement rendu', shown, shown ? '' : await editorText(sessionId));
const box = await editorBox(sessionId);
check('a · l éditeur occupe une surface réelle', !!box && box.w > 200 && box.h > 100, JSON.stringify(box));
check('a · la gouttière de numéros est rendue', !!(await evaluate("!!document.querySelector('.margin-view-overlays .line-numbers')", sessionId)));
const errs = consoleErrors(sessionId, before);
check('a · aucune erreur console', errs.length === 0, errs.slice(0, 3).join(' | '));
await client.send('Target.closeTarget', { targetId });
}
// --- (b) fermer le dernier onglet, puis réouvrir : le conteneur ne doit pas avoir été détruit ---
{
const { targetId, sessionId, before } = await openTarget();
check('b · fichier ouvert une première fois', (await openProbeFile(sessionId)) && (await waitFor(async () => (await editorText(sessionId)).includes(MARKER))));
const closed = await evaluate(
`(() => {
const tab = [...document.querySelectorAll('[title="probe.ts"]')].find((e) => e.querySelector('button'));
const btn = tab?.querySelector('button');
if (!btn) return false;
btn.click();
return true;
})()`,
sessionId,
);
check('b · dernier onglet fermé', !!closed);
const tabsLeft = await evaluate("JSON.parse(localStorage.getItem('arb.ide.tabs') ?? '[]').length", sessionId);
check('b · plus aucun onglet', tabsLeft === 0, `restants: ${tabsLeft}`);
// Le point à prouver : le CONTENEUR survit (v-show, pas v-if). Sans modèle, Monaco détruit sa
// vue de lui-même (`.monaco-editor` disparaît) et la recrée au prochain setModel : c'est normal.
// Ce qui ne doit jamais disparaître, c'est le conteneur, sinon l'instance garde une référence sur
// un noeud détaché et la zone reste définitivement vide.
const hostAlive = await waitFor(
async () => (await evaluate("!!document.querySelector('[data-editor-host]')", sessionId)) === true,
12,
);
check('b · le conteneur de l éditeur survit à la fermeture', hostAlive);
check(
'b · état vide affiché',
await waitFor(async () => String(await evaluate('document.body.innerText', sessionId)).includes('No file open'), 12),
);
check('b · fichier réouvert', await waitFor(() => clickRow('probe.ts', sessionId)));
check('b · le contenu revient après réouverture', await waitFor(async () => (await editorText(sessionId)).includes(MARKER)));
const errs = consoleErrors(sessionId, before);
check('b · aucune erreur console', errs.length === 0, errs.slice(0, 3).join(' | '));
await client.send('Target.closeTarget', { targetId });
}
// --- (c) mobile : l'arbre et l'éditeur sont mutuellement exclusifs, donc un contenu visible
// prouve que l'ouverture d'un fichier a bien amené la zone centrale au premier plan ---
{
const { targetId, sessionId } = await openTarget({ width: 390, height: 844 });
check('c · fichier ouvert depuis l explorateur mobile', await openProbeFile(sessionId));
check('c · le contenu s affiche (le panneau a basculé)', await waitFor(async () => (await editorText(sessionId)).includes(MARKER)));
const treeGone = await evaluate(
`![...document.querySelectorAll('button span')].some((s) => s.textContent.trim() === 'probe.ts')`,
sessionId,
);
check('c · l explorateur a laissé la place à l éditeur', !!treeGone);
await client.send('Target.closeTarget', { targetId });
}
// --- (d) chunk de l'éditeur introuvable : message + actions, puis récupération au rechargement ---
// On bloque UNIQUEMENT le module d'import dynamique. Surtout pas *vendor-monaco* : le chunk
// d'entrée l'importe statiquement, le bloquer tuerait toute la SPA.
{
const { targetId, sessionId } = await openTarget({ blocked: ['*monaco-setup*'] });
check('d · fichier demandé malgré le chunk bloqué', await openProbeFile(sessionId));
const said = await waitFor(async () =>
String(await evaluate('document.body.innerText', sessionId)).includes('The code editor could not be loaded'),
);
check('d · l échec est annoncé au lieu d une zone vide', said);
const actions = await evaluate(
`(() => {
const labels = [...document.querySelectorAll('button')].map((b) => b.textContent.trim());
return labels.includes('Retry') && labels.includes('Reload page');
})()`,
sessionId,
);
check('d · des actions de récupération sont proposées', !!actions);
await client.send('Network.setBlockedURLs', { urls: [] }, sessionId);
await client.send('Page.reload', {}, sessionId);
check('d · après rechargement, le fichier s ouvre', (await openProbeFile(sessionId)) && (await waitFor(async () => (await editorText(sessionId)).includes(MARKER))));
await client.send('Target.closeTarget', { targetId });
}
// --- (e) bascule Fichiers / Changements : la liste des fichiers non commités et le commit ---
{
const { targetId, sessionId, before } = await openTarget({
extraSeed:
`localStorage.setItem('arb.ide.centerMode', '"changes"');` +
`localStorage.setItem('arb.ide.expandedRepos', ${JSON.stringify(JSON.stringify([repoId]))});` +
`localStorage.setItem('arb.ide.changesExpanded', ${JSON.stringify(JSON.stringify([`${repoId}\0${repo}`]))});`,
});
const listed = await waitFor(async () => String(await evaluate('document.body.innerText', sessionId)).includes('dirty.txt'));
check('e · la vue Changements liste le fichier non commité', listed);
const hasCommit = await evaluate(
`[...document.querySelectorAll('button')].some((b) => b.textContent.trim().startsWith('Commit'))`,
sessionId,
);
check('e · le panneau de commit est présent dans le bloc', !!hasCommit);
// La bascule de mode vit dans la barre d'onglets, donc elle est là même sans aucun onglet ouvert.
const switched = await evaluate(
`(() => {
const btn = [...document.querySelectorAll('button[title]')].find((b) => b.getAttribute('title') === 'Files');
if (!btn) return false;
btn.click();
return true;
})()`,
sessionId,
);
check('e · la bascule Fichiers est accessible sans onglet ouvert', !!switched);
check(
'e · retour au mode Fichiers',
await waitFor(async () => String(await evaluate('document.body.innerText', sessionId)).includes('No file open')),
);
const errs = consoleErrors(sessionId, before);
check('e · aucune erreur console', errs.length === 0, errs.slice(0, 3).join(' | '));
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 EDITOR: ALL GREEN' : `\nVERIFY EDITOR: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
@@ -0,0 +1,411 @@
#!/usr/bin/env node
// Vérification E2E du DOCK TERMINAUX par interaction réelle : daemon temporaire isolé + Chromium
// headless piloté en CDP + cookie de session injecté. On clique comme un utilisateur, puis on lit le
// DOM et l'écran d'xterm.
//
// Ce que ce script prouve, et qu'aucune capture ne prouvait :
// (a) un terminal attaché AFFICHE la sortie de son PTY (le bug « écran tout noir » venait du replay
// émis avant `attached`, donc jeté par le client : ici on lit le texte réellement peint) ;
// (b) deux terminaux tiennent côte à côte, chacun dans sa colonne, tous les deux visibles ;
// (c) la frappe va au terminal de la colonne ACTIVE, et suit le changement de colonne ;
// (d) fermer une colonne rend sa place à l'autre, et le terminal restant continue de fonctionner ;
// (e) la vue Changements suit le terminal focalisé (portée), et la bascule « tout voir » la libère.
//
// Sessions `bash` uniquement : aucun quota Claude consommé.
// Usage : node packages/server/scripts/verify-terminals.mjs
// Prérequis : `npm run build` puis `node packages/server/scripts/copy-web.mjs`.
import { spawn, execFileSync } from 'node:child_process';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } 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 = 7413;
const CDP_PORT = 9336;
const ORIGIN = `http://127.0.0.1:${PORT}`;
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
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;
}
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 };
}
/** Répertoire de captures optionnel : `node scripts/verify-terminals.mjs [out]`. */
const shotDir = process.argv[2] ?? null;
const tmp = mkdtempSync(join(tmpdir(), 'arb-verify-term-'));
let srv = null;
let browser = null;
try {
check('SPA copiée dans packages/server/public', existsSync(join(serverDir, 'public', 'index.html')));
// Deux dépôts : le second sert à prouver que la portée git suit bien le terminal focalisé.
const repos = [];
for (const name of ['alpha', 'beta']) {
const dir = join(tmp, name);
mkdirSync(dir, { recursive: true });
const git = (...args) => execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.email', 'test@arboretum.dev');
git('config', 'user.name', 'Test');
writeFileSync(join(dir, 'README.md'), `# ${name}\n`);
git('add', '-A');
git('commit', '-m', 'commit initial');
writeFileSync(join(dir, `wip-${name}.txt`), 'travail en cours\n');
repos.push({ name, dir });
}
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 sessionCookie = (login.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).find((c) => c.startsWith('arb_session='));
const cookieValue = sessionCookie?.slice('arb_session='.length) ?? '';
check('login → cookie de session', !!sessionCookie);
const j = (path, method, body) =>
fetch(`${ORIGIN}${path}`, {
method,
headers: { Origin: ORIGIN, Cookie: sessionCookie ?? '', ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
});
for (const r of repos) {
const res = await (await j('/api/v1/repos', 'POST', { path: r.dir })).json();
r.id = res.repo?.id;
}
check('deux dépôts enregistrés', repos.every((r) => !!r.id));
// Une session bash par dépôt : ce sont elles qui peupleront les deux colonnes.
for (const r of repos) {
const res = await (await j('/api/v1/sessions', 'POST', { cwd: r.dir, command: 'bash' })).json();
r.sessionId = res.session?.id;
}
check('deux sessions bash lancées', repos.every((r) => !!r.sessionId));
const chromeBin = findChromium();
check('Chromium disponible', !!chromeBin, chromeBin ?? 'introuvable');
if (!chromeBin) throw new Error('Chromium introuvable');
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',
// xterm peint sur un canvas WebGL quand il peut : le texte n'est alors PAS dans le DOM et
// aucun test ne peut le lire. On force le renderer DOM ; le chemin vérifié (transport → xterm)
// est le même, seule la peinture change.
'--disable-webgl',
'--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;
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('Page.enable', {}, sessionId);
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 950, deviceScaleFactor: 1, mobile: false }, sessionId);
await client.send('Network.enable', {}, sessionId);
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
// Aucun état de vue persisté : le dock part vide, comme au premier lancement.
// Amorçage AVANT navigation (sinon le store lit un localStorage encore vide) : panneau Sessions à
// gauche pour ouvrir les terminaux, et zone centrale en mode Changements pour observer la portée.
await client.send(
'Page.addScriptToEvaluateOnNewDocument',
{
source: [
"localStorage.clear();",
`localStorage.setItem('arb.theme', '"dark"');`,
"localStorage.setItem('arboretum.locale', 'en');",
`localStorage.setItem('arb.ide.activity', '"sessions"');`,
`localStorage.setItem('arb.ide.centerMode', '"changes"');`,
"localStorage.setItem('arb.ide.leftVisible', 'true');",
].join(''),
},
sessionId,
);
const consoleBefore = client.events.length;
await client.send('Page.navigate', { url: `${ORIGIN}/ide` }, sessionId);
const evaluate = async (expression) => (await client.send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)).result?.value;
async function waitFor(fn, tries = 60, delay = 250) {
for (let i = 0; i < tries; i++) {
if (await fn()) return true;
await sleep(delay);
}
return false;
}
/** Texte réellement PEINT par une instance xterm (index de colonne dans le dock). */
const screenText = (n) =>
evaluate(
`(() => {
const rows = [...document.querySelectorAll('.xterm-rows')];
const el = rows[${n}] ?? [...document.querySelectorAll('.xterm-screen')][${n}];
return el ? el.innerText.replace(/\\u00a0/g, ' ') : null;
})()`,
);
const columnCount = () => evaluate(`document.querySelectorAll('.xterm-screen').length`);
const clickRow = (label) =>
evaluate(
`(() => {
const span = [...document.querySelectorAll('button span')].find((s) => s.textContent.trim() === ${JSON.stringify(label)});
const btn = span?.closest('button');
if (!btn) return false;
btn.click();
return true;
})()`,
);
const clickTitled = (title, nth = 0) =>
evaluate(
`(() => {
const btns = [...document.querySelectorAll('[title=' + JSON.stringify(${JSON.stringify(title)}) + ']')];
const btn = btns[${nth}];
if (!btn) return false;
btn.click();
return true;
})()`,
);
/**
* Clic NATIF au centre d'une colonne : c'est le seul moyen de donner le focus au textarea caché
* d'xterm (un PointerEvent synthétique ne déplace pas le focus du navigateur).
*/
async function clickColumn(n) {
const box = await evaluate(
`(() => {
const el = [...document.querySelectorAll('.xterm-screen')][${n}];
if (!el) return null;
const r = el.getBoundingClientRect();
return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
})()`,
);
if (!box) return false;
for (const type of ['mousePressed', 'mouseReleased']) {
await client.send('Input.dispatchMouseEvent', { type, x: box.x, y: box.y, button: 'left', clickCount: 1 }, sessionId);
}
await sleep(200);
return true;
}
/** Frappe réelle : insertText va à l'élément focalisé (le textarea d'xterm). */
const type = (text) => client.send('Input.insertText', { text }, sessionId);
const pressEnter = async () => {
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13, text: '\r' }, sessionId);
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 }, sessionId);
};
check('SPA chargée sur /ide', await waitFor(async () => (await evaluate(`!!document.querySelector('[aria-label], nav, main')`)) === true));
// --- (a) un terminal affiche la sortie de son PTY ---
/** Clique la ligne de session du panneau Sessions correspondant à un dépôt. `alt` = ouvrir à côté. */
const clickSessionRow = (repoName, alt = false) =>
evaluate(
`(() => {
const rows = [...document.querySelectorAll('aside button, div button')].filter(
(b) => b.textContent.includes(${JSON.stringify(repoName)}) && b.querySelector('span'),
);
const row = rows[0];
if (!row) return false;
row.dispatchEvent(new MouseEvent('click', { bubbles: true, altKey: ${alt} }));
return true;
})()`,
);
const listed = await waitFor(async () => (await evaluate(`document.body.innerText.includes('alpha') && document.body.innerText.includes('beta')`)) === true, 40);
check('les deux sessions sont listées dans le panneau', listed);
const openedFirst = await waitFor(async () => {
await clickSessionRow('alpha');
return (await columnCount()) >= 1;
}, 30);
check('un terminal s’ouvre dans le dock', openedFirst, `colonnes: ${await columnCount()}`);
await clickColumn(0);
check('le terminal prend le focus clavier', (await evaluate(`document.activeElement?.tagName?.toLowerCase() ?? ''`)) === 'textarea');
// Deux preuves complémentaires : le PTY a bien reçu la frappe (fichier créé dans SON cwd), et sa
// sortie est réellement peinte à l'écran (c'était précisément ce qui manquait : un écran noir).
await type('touch recu-A && echo MARQUEUR-COLONNE-A');
await pressEnter();
const gotA = await waitFor(() => existsSync(join(repos[0].dir, 'recu-A')), 40);
check('(a) la frappe atteint le PTY du terminal', gotA);
const paintedA = await waitFor(async () => ((await screenText(0)) ?? '').includes('MARQUEUR-COLONNE-A'), 40);
check('(a) le terminal PEINT la sortie de son PTY (fin de l’écran noir)', paintedA, ((await screenText(0)) ?? '').replace(/\s+/g, ' ').slice(-70));
// --- (b) deux terminaux côte à côte ---
const splitDone = await waitFor(async () => {
await clickSessionRow('beta', true); // Alt+clic = ouvrir à côté
return (await columnCount()) === 2;
}, 30);
check('(b) deux colonnes de terminaux visibles simultanément', splitDone, `colonnes: ${await columnCount()}`);
const bothVisible = await evaluate(
`(() => {
const screens = [...document.querySelectorAll('.xterm-screen')];
if (screens.length !== 2) return false;
return screens.every((s) => { const r = s.getBoundingClientRect(); return r.width > 50 && r.height > 20; });
})()`,
);
check('(b) les deux colonnes ont une surface réelle', bothVisible === true);
const sideBySide = await evaluate(
`(() => {
const [a, b] = [...document.querySelectorAll('.xterm-screen')].map((s) => s.getBoundingClientRect());
return !!a && !!b && Math.abs(a.top - b.top) < 40 && Math.abs(a.left - b.left) > 100;
})()`,
);
check('(b) elles sont côte à côte (et non empilées)', sideBySide === true);
// Capture optionnelle (argument 1) : preuve visuelle des deux colonnes, utile en revue.
if (shotDir) {
mkdirSync(shotDir, { recursive: true });
const shot = await client.send('Page.captureScreenshot', { format: 'png' }, sessionId);
const file = join(shotDir, 'terminal-columns.png');
writeFileSync(file, Buffer.from(shot.data, 'base64'));
check('capture des deux colonnes écrite', existsSync(file), file);
}
// --- (c) la frappe va à la colonne active (la seconde vient d'être créée) ---
await type('touch recu-B && echo MARQUEUR-COLONNE-B');
await pressEnter();
const gotB = await waitFor(() => existsSync(join(repos[1].dir, 'recu-B')), 40);
check('(c) la frappe va au PTY de la colonne active (nouvelle colonne focalisée)', gotB);
check('(c) elle ne fuit pas dans l’autre PTY', !existsSync(join(repos[0].dir, 'recu-B')));
const paintedB = await waitFor(async () => ((await screenText(1)) ?? '').includes('MARQUEUR-COLONNE-B'), 40);
check('(c) la seconde colonne peint aussi sa sortie', paintedB);
// Retour sur la première colonne : un clic dedans doit lui rendre la frappe.
await clickColumn(0);
await type('touch retour-A');
await pressEnter();
const backToA = await waitFor(() => existsSync(join(repos[0].dir, 'retour-A')), 40);
check('(c) le focus suit le clic sur une colonne', backToA);
// --- (e) la portée git suit le terminal focalisé (zone centrale en mode Changements) ---
// La colonne active est celle d'alpha (on vient d'y revenir) : seul son fichier modifié doit être
// listé, celui de beta doit disparaître de la vue.
const centerText = () => evaluate(`document.querySelector('main')?.innerText ?? ''`);
const scopedToAlpha = await waitFor(async () => {
const txt = await centerText();
return txt.includes('wip-alpha.txt') && !txt.includes('wip-beta.txt');
}, 40);
check('(e) la vue Changements ne montre que le projet du terminal focalisé', scopedToAlpha, (await centerText()).replace(/\s+/g, ' ').slice(0, 90));
// Focaliser la colonne de beta doit faire suivre la vue.
await clickColumn(1);
const followsBeta = await waitFor(async () => {
const txt = await centerText();
return txt.includes('wip-beta.txt') && !txt.includes('wip-alpha.txt');
}, 40);
check('(e) changer de colonne fait suivre la vue Changements', followsBeta, (await centerText()).replace(/\s+/g, ' ').slice(0, 90));
// La bascule « tout voir » doit libérer la portée.
await evaluate(
`(() => {
const btn = [...document.querySelectorAll('button')].find((b) => /Show every project|Follow the focused terminal/.test(b.getAttribute('title') ?? ''));
btn?.click();
return !!btn;
})()`,
);
// Un bloc replié ne liste pas ses fichiers : la preuve d'élargissement, ce sont les deux dépôts.
const seesBoth = await waitFor(async () => {
const txt = await centerText();
return txt.includes('alpha') && txt.includes('beta');
}, 40);
check('(e) la bascule « tout voir » libère la portée', seesBoth);
// --- (d) fermer une colonne ---
const closed = await waitFor(async () => {
await clickTitled('Close', 0);
return (await columnCount()) <= 1;
}, 20);
check('(d) fermer un terminal libère sa colonne', closed, `colonnes: ${await columnCount()}`);
const consoleErrors = client.events
.slice(consoleBefore)
.filter((e) => e.method === 'Log.entryAdded' && e.params?.entry?.level === 'error')
.map((e) => e.params.entry.text)
// Les 404 de favicon et les avertissements de chunk ne concernent pas le dock.
.filter((t) => !/favicon|manifest/i.test(t));
check('aucune erreur console', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '));
} catch (err) {
check('exception', false, String(err));
} finally {
browser?.kill('SIGKILL');
srv?.kill('SIGTERM');
await sleep(1200);
srv?.kill('SIGKILL');
rmSync(tmp, { recursive: true, force: true });
const failed = results.filter((r) => !r.ok);
console.log(failed.length === 0 ? '\nVERIFY TERMINALS: ALL GREEN' : `\nVERIFY TERMINALS: ${failed.length} FAILURE(S)`);
process.exit(failed.length === 0 ? 0 : 1);
}
+271
View File
@@ -0,0 +1,271 @@
#!/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);
// Un fichier indexé et un non indexé dans le checkout principal : la vue Changements doit montrer
// ses DEUX sections (« Staged » et « Changes »), sinon la capture ne prouve que la moitié.
writeFileSync(join(repo, 'notes.md'), 'brouillon\n');
const staged = await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', { path: repo, files: ['src/app.ts'] });
check('un fichier indexé pour la démonstration', staged.ok);
// --- 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});`;
// Index Git de la sidebar : compteurs par projet, sans liste de fichiers (celle-ci vit au centre).
const seedGit = `${seedExplorer}localStorage.setItem('arb.ide.activity', '"git"');`;
// Vue Changements de la zone centrale : blocs dépliés du checkout principal ET du worktree de
// feature, plus l'historique du premier (sa clé de repli est désormais PAR worktree).
const changesKeys = JSON.stringify(
JSON.stringify([`${repoId}\0${repo}`, ...(wtRes.worktree?.path ? [`${repoId}\0${wtRes.worktree.path}`] : [])]),
);
const seedChanges =
`${seedExplorer}localStorage.setItem('arb.ide.centerMode', '"changes"');` +
`localStorage.setItem('arb.ide.changesExpanded', ${changesKeys});` +
`localStorage.setItem(${JSON.stringify(`arb.history.open:${repoId}\0${repo}`)}, 'true');`;
const seedChangesMobile = `${seedChanges}localStorage.setItem('arb.ide.mobilePanel', '"changes"');`;
// Zone d'édition : un onglet persisté, jamais capturé jusqu'ici.
const editorTabId = `${repoId}\0${repo}\0src/app.ts`;
const seedEditor =
`${seedExplorer}localStorage.setItem('arb.ide.tabs', ${JSON.stringify(
JSON.stringify([{ id: editorTabId, repoId, wtPath: repo, file: 'src/app.ts', view: 'editor' }]),
)});localStorage.setItem('arb.ide.activeTab', ${JSON.stringify(JSON.stringify(editorTabId))});`;
// Panneau Groupes avec le groupe ET le worktree dépliés : c'est la vue qui porte l'arborescence de
// fichiers des membres du groupe, sinon jamais capturée.
const seedGroups =
`${seedExplorer}localStorage.setItem('arb.ide.activity', '"groups"');` +
`localStorage.setItem('arb.ide.expandedGroups', ${JSON.stringify(JSON.stringify([groupRes.group?.id]))});` +
`localStorage.setItem('arb.ide.expandedWts', ${JSON.stringify(JSON.stringify([repo]))});`;
// `expect` : une capture non vide ne prouve pas que le bon composant s'est rendu. On exige donc un
// fragment de texte propre à la surface visée.
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, expect: 'feature/demo' },
{ name: 'git-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedGit, expect: 'feature/demo' },
{ name: 'changes-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedChanges, expect: 'wip.txt' },
{ name: 'changes-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedChanges, expect: 'wip.txt' },
{ name: 'changes-dark-mobile', theme: 'dark', width: 390, height: 844, seed: seedChangesMobile, expect: 'wip.txt' },
{ name: 'editor-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedEditor, expect: 'src/app.ts' },
{ name: 'groups-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedGroups },
{ 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);
// `localStorage.clear()` d'abord : les cibles d'un même profil Chromium le PARTAGENT, donc sans
// ça une capture héritait de l'état de vue de la précédente (une capture de la zone d'édition
// montrait la vue Changements laissée par celle d'avant).
await client.send(
'Page.addScriptToEvaluateOnNewDocument',
{ source: `localStorage.clear();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`);
if (shot.expect) check(`${shot.name} : contenu attendu`, rendered.includes(shot.expect), shot.expect);
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);
}
+78 -11
View File
@@ -10,6 +10,11 @@ import type { Db } from './db/index.js';
import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.js';
import { PtyManager } from './core/pty-manager.js';
import { DiscoveryService } from './core/discovery-service.js';
import { SessionArchiveService } from './core/session-archive.js';
import { SettingsBus } from './core/settings-bus.js';
import { GitCredentialsManager } from './core/git-credentials.js';
import { CloneManager } from './core/clone-manager.js';
import { registerGitConnectionRoutes } from './routes/git-connections.js';
import { WorktreeManager } from './core/worktree-manager.js';
import { RepoDiscoveryService } from './core/repo-discovery.js';
import { GroupManager } from './core/group-manager.js';
@@ -17,12 +22,16 @@ import { PushService } from './core/push-service.js';
import { loadSecretBox } from './core/secret-box.js';
import { registerAuthRoutes } from './routes/auth.js';
import { registerSessionRoutes } from './routes/sessions.js';
import { registerProjectRoutes } from './routes/projects.js';
import { registerRepoRoutes } from './routes/repos.js';
import { registerGroupRoutes } from './routes/groups.js';
import { registerWorktreeRoutes } from './routes/worktrees.js';
import { registerGitRoutes } from './routes/git.js';
import { registerFileRoutes } from './routes/files.js';
import { registerPushRoutes } from './routes/push.js';
import { registerSettingsRoutes } from './routes/settings.js';
import { registerFsRoutes } from './routes/fs.js';
import { FsWatcherService } from './core/fs-watcher.js';
import { registerAuditRoutes } from './routes/audit.js';
import { registerDataRoutes } from './routes/data.js';
import { registerWsGateway } from './ws/gateway.js';
@@ -55,6 +64,22 @@ const SECURITY_HEADERS: Record<string, string> = {
].join('; '),
};
// Politique de cache du statique. Piège à connaître : `npm pack` normalise le mtime de TOUS les
// fichiers du tarball à une date constante (1985-10-26). L'etag faible de @fastify/static étant
// dérivé de taille+mtime, deux versions différentes d'un même fichier non haché produisent le
// MÊME etag dès que leur taille coïncide : le client reçoit un 304 et garde indéfiniment
// l'ancienne copie. Vécu en production sur index.html à la mise à jour de l'app desktop : l'index
// obsolète référençait des `/assets/<hash>.js` disparus, le fallback SPA répondait du text/html
// pour ces modules, et la page restait noire.
// Conséquence : seuls les fichiers dont le NOM porte un hash de contenu (/assets/) sont
// cachables ; tout le reste (index.html, sw.js, theme-boot.js, manifest, icônes) part en
// no-store, la revalidation par etag n'étant pas fiable ici.
export function cacheControlFor(pathname: string): string {
return pathname.startsWith('/assets/')
? 'public, max-age=31536000, immutable'
: 'no-store';
}
declare module 'fastify' {
interface FastifyRequest {
authContext: AuthContext | null;
@@ -69,10 +94,15 @@ export interface AppBundle {
auth: AuthService;
manager: PtyManager;
discovery: DiscoveryService;
sessionArchive: SessionArchiveService;
repoDiscovery: RepoDiscoveryService;
worktrees: WorktreeManager;
groups: GroupManager;
push: PushService;
fsWatcher: FsWatcherService;
settingsBus: SettingsBus;
gitCredentials: GitCredentialsManager;
clones: CloneManager;
}
export function buildApp(config: Config, db: Db, serverVersion: string): AppBundle {
@@ -89,10 +119,20 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
projectsDir: config.claudeProjectsDir,
sessionsDir: config.claudeSessionsDir,
});
const worktrees = new WorktreeManager(db, manager, discovery);
// Archivage auto des sessions terminées (P10). Démarré dans runDaemon() : jamais ici (tests).
const sessionArchive = new SessionArchiveService({ db });
// Watcher FS temps réel (P7) : armé à la demande sur les worktrees regardés via les commandes
// WS watch/unwatch. closeAll() au drain (libération des descripteurs).
const fsWatcher = new FsWatcherService();
const worktrees = new WorktreeManager(db, manager, discovery, fsWatcher);
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
const groups = new GroupManager(db);
// P11 · bus de diffusion des réglages : PATCH /settings émet, la gateway relaie au topic 'settings'.
const settingsBus = new SettingsBus();
// P12 · services git distants : `box` (SecretBox) câblé ici pour chiffrer les secrets des credentials.
const gitCredentials = new GitCredentialsManager(db, box);
const clones = new CloneManager(db, worktrees, gitCredentials);
// En-têtes de sécurité sur toute réponse + no-store sur les réponses sensibles (API/WS).
// onSend DOIT retourner le payload (sinon Fastify vide la réponse).
@@ -152,14 +192,19 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
};
// Garde globale : auth sur tout /api/** et /ws ; check Origin strict quand l'en-tête est présent
// (anti cross-site WebSocket hijacking — le cookie SameSite=Strict ne suffit pas pour les upgrades).
// (anti cross-site WebSocket hijacking : le cookie SameSite=Strict ne suffit pas pour les upgrades).
app.addHook('preValidation', async (req, reply) => {
const isApi = req.url.startsWith('/api/');
const isWs = req.url.startsWith('/ws');
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;
@@ -169,25 +214,47 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
});
registerAuthRoutes(app, auth, limiter, serverVersion, db);
registerSessionRoutes(app, manager, discovery, db);
registerRepoRoutes(app, worktrees, db);
registerSessionRoutes(app, manager, discovery, sessionArchive, db);
registerProjectRoutes(app, manager, db);
registerRepoRoutes(app, worktrees, db, manager);
registerGroupRoutes(app, groups, db, worktrees, manager);
registerWorktreeRoutes(app, worktrees, db);
registerGitRoutes(app, worktrees, db);
registerFileRoutes(app, worktrees, db);
registerPushRoutes(app, push, db);
registerSettingsRoutes(app, db, config, serverVersion, push);
registerSettingsRoutes(app, db, config, serverVersion, push, settingsBus);
registerGitConnectionRoutes(app, gitCredentials, clones, db);
registerFsRoutes(app);
registerAuditRoutes(app, db);
registerDataRoutes(app, db, auth);
// La route websocket doit être déclarée APRÈS le chargement du plugin (contexte
// encapsulé) — sinon le handler reçoit la signature REST (request, reply).
// encapsulé) : sinon le handler reçoit la signature REST (request, reply).
void app.register(async (scoped) => {
registerWsGateway(scoped, manager, discovery, worktrees, groups, serverVersion);
registerWsGateway(scoped, manager, discovery, sessionArchive, worktrees, groups, settingsBus, clones, serverVersion);
});
// SPA buildée embarquée dans le paquet npm (public/) — absente en dev (vite dev sert le front)
// SPA buildée embarquée dans le paquet npm (public/) : absente en dev (vite dev sert le front)
const publicDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'public');
if (existsSync(publicDir)) {
void app.register(fastifyStatic, { root: publicDir, wildcard: false });
void app.register(fastifyStatic, {
root: publicDir,
wildcard: false,
// Validation conditionnelle désactivée : l'etag faible et le Last-Modified dérivent du mtime,
// que `npm pack` fige (cf. cacheControlFor). Les laisser actifs ferait répondre 304 aux
// clients qui détiennent encore un index.html périmé d'une version antérieure : ils y
// resteraient bloqués. Sans etag, ils reçoivent un 200 et se réparent d'eux-mêmes. Le coût
// est nul pour /assets (noms hachés, servis immutable) et négligeable ailleurs.
etag: false,
lastModified: false,
// Indispensable : sinon le plugin écrit son propre `cache-control: public, max-age=0`
// APRÈS setHeaders et écrase le no-store ci-dessous.
cacheControl: false,
// `setHeaders` s'applique aussi aux `reply.sendFile` du fallback SPA ci-dessous.
setHeaders(res, path) {
const rel = path.slice(publicDir.length).replace(/\\/g, '/');
res.setHeader('Cache-Control', cacheControlFor(rel));
},
});
app.setNotFoundHandler((req, reply) => {
if (req.url.startsWith('/api/') || req.url.startsWith('/ws')) {
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'Route not found' } });
@@ -196,5 +263,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
});
}
return { app, auth, manager, discovery, repoDiscovery, worktrees, groups, push };
return { app, auth, manager, discovery, sessionArchive, repoDiscovery, worktrees, groups, push, fsWatcher, settingsBus, gitCredentials, clones };
}
+78 -16
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,
@@ -122,11 +138,16 @@ function quoteIfNeeded(token: string): string {
return /\s/.test(token) ? `"${token}"` : token;
}
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[] }): string {
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[]; pathEnv?: string | undefined }): string {
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
// Un service systemd user démarre avec un PATH minimal (typiquement /usr/bin:/bin…) qui n'inclut
// PAS ~/.local/bin ni le bin npm/nvm où vit le CLI `claude` → resolveClaudeBin() (`which claude`)
// échouerait. On fige donc le PATH de l'environnement d'installation, où `claude` est résolvable.
// Doubles quotes systemd : tolèrent un chemin du PATH contenant des espaces.
const pathLine = input.pathEnv ? `\nEnvironment="PATH=${input.pathEnv}"` : '';
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
return `[Unit]
Description=Arboretum — git worktree & Claude Code dashboard
Description=Arboretum · git worktree & Claude Code dashboard
After=network-online.target
Wants=network-online.target
@@ -136,7 +157,7 @@ Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=10
Environment=NODE_ENV=production
Environment=NODE_ENV=production${pathLine}
[Install]
WantedBy=default.target
@@ -148,8 +169,14 @@ export function renderLaunchAgentPlist(input: {
programArguments: string[];
stdoutPath: string;
stderrPath: string;
pathEnv?: string | undefined;
}): string {
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
// launchd démarre un LaunchAgent avec un PATH minimal qui n'inclut pas ~/.local/bin ni le bin
// npm/nvm où vit le CLI `claude` → resolveClaudeBin() échouerait. On fige le PATH d'installation.
const pathEntry = input.pathEnv
? `\n <key>PATH</key>\n <string>${xmlEscape(input.pathEnv)}</string>`
: '';
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -175,7 +202,7 @@ ${args}
<key>EnvironmentVariables</key>
<dict>
<key>NODE_ENV</key>
<string>production</string>
<string>production</string>${pathEntry}
</dict>
</dict>
</plist>
@@ -184,19 +211,20 @@ ${args}
export function printTokenBanner(token: string, url: string): void {
console.log('\n┌──────────────────────────────────────────────────────────────────┐');
console.log('│ First start — your access token (shown once, store it safely): │');
console.log('│ First start : your access token (shown once, store it safely): │');
console.log('└──────────────────────────────────────────────────────────────────┘');
console.log(`\n ${token}\n`);
console.log(` Login at: ${url}/\n`);
}
export function printUsage(version: string): void {
console.log(`Arboretum v${version} — git worktree & Claude Code dashboard
console.log(`Arboretum v${version} · git worktree & Claude Code dashboard
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
@@ -207,7 +235,10 @@ Daemon flags:
--allow-origin <url> Additional allowed Origin (repeatable)
--db <path> SQLite database path
--vapid-contact <mailto|url> VAPID contact subject for Web Push
--i-know-this-exposes-a-terminal Acknowledge a non-loopback bind (avoid — prefer Tailscale Serve)
--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):
--bin-path <path> Use this binary in the service instead of node + script
@@ -246,7 +277,7 @@ function bootstrapToken(serviceArgs: string[]): void {
try {
const token = new AuthService(db).ensureBootstrapToken();
if (token) printTokenBanner(token, url);
else console.log('\nAn access token already exists in this database — manage tokens from Settings.\n');
else console.log('\nAn access token already exists in this database. Manage tokens from Settings.\n');
} finally {
db.close();
}
@@ -258,9 +289,12 @@ export async function runInstall(argv: string[]): Promise<void> {
const serviceArgs = buildServiceArgs(flags);
const { exec, args: binArgs } = resolveBin(flags);
const scriptArgs = [...binArgs, ...serviceArgs];
// PATH de l'environnement d'installation (shell interactif où `claude` est résolvable) : on le
// fige dans l'unit/plist car systemd/launchd démarrent le service avec un PATH minimal.
const pathEnv = process.env.PATH;
if (platform === 'linux') {
const unit = renderSystemdUnit({ exec, scriptArgs });
const unit = renderSystemdUnit({ exec, scriptArgs, pathEnv });
const unitPath = systemdUnitPath();
if (flags.dryRun) {
console.log(`# ${unitPath}\n${unit}\n# commands:`);
@@ -280,13 +314,30 @@ export async function runInstall(argv: string[]): Promise<void> {
run('systemctl', ['--user', 'enable', '--now', SERVICE_NAME], { check: true });
// enable-linger best-effort : absent en CI / sans session loginctl, non bloquant.
if (run('loginctl', ['enable-linger', process.env.USER ?? '']) !== 0) {
console.warn('Warning: could not enable linger — the service may not start at boot.');
console.warn('Warning: could not enable linger. The service may not start at boot.');
}
}
console.log(`\nArboretum service installed. Logs: journalctl --user -u ${SERVICE_NAME} -f`);
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];
@@ -295,6 +346,7 @@ export async function runInstall(argv: string[]): Promise<void> {
programArguments,
stdoutPath: logs.out,
stderrPath: logs.err,
pathEnv,
});
const plistPath = launchAgentPlistPath(flags.label);
const uid = process.getuid?.() ?? 0;
@@ -337,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
@@ -356,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}`);
+27 -5
View File
@@ -11,7 +11,11 @@ export interface Config {
/** origins supplémentaires autorisées (ex. https://machine.tailnet.ts.net) */
allowedOrigins: string[];
printToken: boolean;
/** ~/.claude/projects (transcripts JSONL) — surchargeable via --claude-home (tests). */
/** racine effective de l'install Claude (~/.claude par défaut, --claude-home, ou réglage claude_home). */
claudeHome: string;
/** true si --claude-home a été passé explicitement → a priorité sur le réglage claude_home. */
claudeHomeFromFlag: boolean;
/** ~/.claude/projects (transcripts JSONL) : surchargeable via --claude-home (tests). */
claudeProjectsDir: string;
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
claudeSessionsDir: string;
@@ -21,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,
@@ -31,11 +50,11 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
'allow-origin': { type: 'string', multiple: true },
'print-token': { type: 'boolean', default: false },
'i-know-this-exposes-a-terminal': { type: 'boolean', default: false },
// racine de l'install Claude (~/.claude par défaut) — surchargée par les tests d'acceptation.
// racine de l'install Claude (~/.claude par défaut) : surchargée par les tests d'acceptation.
'claude-home': { type: 'string' },
// sujet VAPID des notifications push (contact requis par la spec Web Push).
'vapid-contact': { type: 'string' },
// désactive la découverte auto des repos (boot + périodique) — utilisé par les tests d'acceptation.
// désactive la découverte auto des repos (boot + périodique) : utilisé par les tests d'acceptation.
'no-discover': { type: 'boolean', default: false },
},
strict: true,
@@ -51,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
@@ -61,7 +80,8 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
} catch {
/* FS sans permissions POSIX : ignoré, cf. avertissement dans db.openDb */
}
const claudeHome = values['claude-home'] ?? join(homedir(), '.claude');
const claudeHomeFlag = values['claude-home'];
const claudeHome = claudeHomeFlag ?? join(homedir(), '.claude');
return {
port: Number(values.port),
bind,
@@ -69,6 +89,8 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
dataDir,
allowedOrigins: values['allow-origin'] ?? [],
printToken: values['print-token'] ?? false,
claudeHome,
claudeHomeFromFlag: claudeHomeFlag !== undefined,
claudeProjectsDir: join(claudeHome, 'projects'),
claudeSessionsDir: join(claudeHome, 'sessions'),
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
+1 -1
View File
@@ -1,7 +1,7 @@
// Journal d'audit : trace persistante des opérations sensibles (création/révocation de tokens,
// changements de réglages, génération de secrets, abonnements push, CRUD groupes). Exigence de
// conformité entreprise (GDPR/SOX/ISO 27001). Règle ABSOLUE : ne JAMAIS journaliser un secret en
// clair — `details` ne contient que des métadonnées non sensibles (ids, labels, compteurs).
// clair : `details` ne contient que des métadonnées non sensibles (ids, labels, compteurs).
import { randomUUID } from 'node:crypto';
import type { AuditLogEntry } from '@arboretum/shared';
import type { Db } from '../db/index.js';
+161 -7
View File
@@ -1,4 +1,5 @@
import { execFileSync } from 'node:child_process';
import { accessSync, constants, existsSync } from 'node:fs';
export interface SpawnSpec {
file: string;
@@ -12,39 +13,192 @@ 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 le PATH. */
claudeBinPath?: string | null;
/**
* Lancement de projet (« Démarrer le projet ») : au lieu de `bash --norc`, lance le shell de
* login interactif de l'utilisateur (`$SHELL -l -i`) pour charger son environnement complet
* (PATH nvm/asdf/~/.local/bin). Indispensable quand le daemon tourne en service systemd/launchd
* (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). */
export interface ClaudeBinDiagnostic {
/** chemin résolu du binaire, ou null si introuvable. */
path: string | null;
/** 'configured' = réglage explicite ; 'path' = trouvé via PATH ; null = introuvable. */
source: 'configured' | 'path' | null;
/** true si le binaire est présent et exécutable. */
ok: boolean;
}
let cachedClaudeBin: string | null = null;
export function resolveClaudeBin(): string {
if (cachedClaudeBin) return cachedClaudeBin;
/**
* 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(platform: NodeJS.Platform = process.platform): string | null {
const { file, args } = whichCommand(platform);
try {
cachedClaudeBin = execFileSync('which', ['claude'], { encoding: 'utf8' }).trim();
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;
}
}
/**
* « 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;
} catch {
return false;
}
}
/**
* 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 :
* 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) {
if (!isExecutable(configuredPath)) {
throw new Error(`Configured Claude CLI path is not executable: ${configuredPath}`);
}
return configuredPath;
}
// Cache REVALIDÉ : le daemon vit des jours. Un changement de version nvm/asdf, une réinstallation
// du CLI ou un simple `npm i -g` remplace le chemin, et le cache pointait alors sur un fichier
// disparu : node-pty spawnait dans le vide, le PTY mourait sans un octet, et l'utilisateur n'avait
// qu'un terminal vide sans explication.
if (cachedClaudeBin) {
if (isExecutable(cachedClaudeBin)) return cachedClaudeBin;
cachedClaudeBin = null;
}
const found = findClaudeOnPath();
if (!found) {
throw new Error(
'Claude Code CLI not found in PATH. Install it first: https://code.claude.com/docs/en/quickstart',
);
}
cachedClaudeBin = found;
return cachedClaudeBin;
}
/** Diagnostic non-throwing pour l'UI (Réglages) : recalculé à chaque appel, jamais caché. */
export function diagnoseClaudeBin(configuredPath?: string | null): ClaudeBinDiagnostic {
if (configuredPath) {
return { path: configuredPath, source: 'configured', ok: isExecutable(configuredPath) };
}
const found = findClaudeOnPath();
return found ? { path: found, source: 'path', ok: true } : { path: null, source: null, ok: false };
}
/** Shells interactifs connus supportant `-l -i` (login + interactif). */
const KNOWN_LOGIN_SHELLS = new Set(['bash', 'zsh', 'fish']);
/**
* 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.
*/
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'] };
}
/**
* Marqueurs d'EXÉCUTION que le CLI claude pose dans l'environnement de ses processus enfants. Si le
* daemon a lui-même été lancé depuis une session Claude Code (ce qui arrive : `arboretum` démarré
* depuis un terminal Claude, ou l'app de bureau lancée par un agent), il les hérite et les
* retransmettait à CHAQUE session qu'il lance. Conséquences observées :
* - `CLAUDE_CODE_CHILD_SESSION=1` fait croire au CLI qu'il est une sous-session : il DÉSACTIVE la
* sauvegarde du transcript (« Transcript saving is off »), donc plus d'historique, plus de
* `--resume`, et `claudeSessionId` reste null (l'état fin busy/waiting/idle tombe avec lui) ;
* - `CLAUDE_CODE_SESSION_ID` / `CLAUDE_PID` désignent la session PARENTE, pas celle qu'on lance.
* On ne retire QUE ces marqueurs : la configuration légitime de l'utilisateur (`CLAUDE_CONFIG_DIR`,
* `ANTHROPIC_*`, proxies...) doit passer telle quelle, sinon on casserait son installation.
*/
export const INHERITED_CLAUDE_MARKERS = [
'CLAUDECODE',
'CLAUDE_CODE_CHILD_SESSION',
'CLAUDE_CODE_SESSION_ID',
'CLAUDE_CODE_ENTRYPOINT',
'CLAUDE_CODE_EXECPATH',
'CLAUDE_PID',
'CLAUDE_EFFORT',
] as const;
/**
* Environnement assaini pour un PTY : pur et testable. Appliqué aussi au shell (`bash`), car un
* `claude` lancé à la main dans ce terminal hériterait des mêmes marqueurs.
*/
export function sanitizeInheritedEnv(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...source };
for (const key of INHERITED_CLAUDE_MARKERS) delete env[key];
return env;
}
/** 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,
...sanitizeInheritedEnv(process.env),
TERM: 'xterm-256color',
COLORTERM: 'truecolor',
};
if (opts.command === 'bash') {
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) {
// `--resume` doit toujours s'exécuter dans le cwd d'origine (garanti par l'appelant — spike S1).
// `--resume` doit toujours s'exécuter dans le cwd d'origine (garanti par l'appelant, spike S1).
args.push('--resume', opts.resume.claudeSessionId);
if (opts.resume.fork) args.push('--fork-session');
}
// Session de groupe : relie plusieurs repos/worktrees dans une seule session (P6).
for (const dir of opts.addDirs ?? []) args.push('--add-dir', dir);
return { file: resolveClaudeBin(), args, env };
return { file: resolveClaudeBin(opts.claudeBinPath), args, env };
}
@@ -0,0 +1,63 @@
// Réglages liés au CLI Claude, persistés dans la table `settings` (clé/valeur), modifiables via
// l'onglet Réglages. Frontière de sécurité identique à scan-settings : clés NON sensibles, écrites
// uniquement via l'allow-list du PATCH /api/v1/settings et les validateurs ci-dessous.
//
// Motivation : un service systemd/launchd démarre avec un PATH minimal qui n'inclut pas ~/.local/bin
// (où vit le binaire `claude`) → `which claude` échoue. Plutôt que de bricoler le PATH du service,
// l'utilisateur peut pointer explicitement le binaire ici (effet : prochaine session, sans redémarrage).
import { accessSync, constants, statSync } from 'node:fs';
import { getSetting } from '../db/index.js';
import type { Db } from '../db/index.js';
import { isSafeAbsolutePath } from './git.js';
/** Chemin explicite du binaire `claude` (override de la résolution via PATH). */
export const CLAUDE_BIN_PATH_KEY = 'claude_bin_path';
/** Override de la racine ~/.claude (transcripts + registre des sessions). */
export const CLAUDE_HOME_KEY = 'claude_home';
/** Chemin configuré du binaire `claude`, ou null si non défini (⇒ auto-détection via PATH). */
export function readClaudeBinPath(db: Db): string | null {
const raw = getSetting(db, CLAUDE_BIN_PATH_KEY)?.trim();
return raw ? raw : null;
}
/** Racine ~/.claude configurée, ou null si non défini (⇒ défaut/flag). */
export function readClaudeHome(db: Db): string | null {
const raw = getSetting(db, CLAUDE_HOME_KEY)?.trim();
return raw ? raw : null;
}
/**
* Valide un chemin de binaire `claude`. Retourne `''` pour réinitialiser (auto-détection), le chemin
* normalisé s'il est absolu ET pointe vers un fichier exécutable, ou `null` si invalide (⇒ 400).
*/
export function normalizeClaudeBinPath(raw: unknown): string | null {
if (typeof raw !== 'string') return null;
const p = raw.trim();
if (p === '') return '';
if (!isSafeAbsolutePath(p)) return null;
try {
if (!statSync(p).isFile()) return null;
accessSync(p, constants.X_OK);
} catch {
return null;
}
return p;
}
/**
* Valide une racine ~/.claude. Retourne `''` pour réinitialiser (défaut), le chemin normalisé s'il
* est absolu ET pointe vers un répertoire existant, ou `null` si invalide (⇒ 400).
*/
export function normalizeClaudeHome(raw: unknown): string | null {
if (typeof raw !== 'string') return null;
const p = raw.trim();
if (p === '') return '';
if (!isSafeAbsolutePath(p)) return null;
try {
if (!statSync(p).isDirectory()) return null;
} catch {
return null;
}
return p;
}
+118
View File
@@ -0,0 +1,118 @@
// Orchestration des clones (P12). Asynchrone : POST /repos/clone répond 202 avec un operationId,
// la progression est poussée en WS (topic 'clones') et lisible en REST (survit au refresh). À la fin,
// le repo cloné est auto-enregistré via WorktreeManager.addRepo (réutilise unicité/validation/event).
// `dest` est strictement confiné SOUS une racine de scan + non existant (mkdir implicite par git).
import { EventEmitter } from 'node:events';
import { randomUUID } from 'node:crypto';
import { rm, stat } from 'node:fs/promises';
import { resolve, sep } from 'node:path';
import type { CloneOperation, GitService } from '@arboretum/shared';
import type { Db } from '../db/index.js';
import { isSafeAbsolutePath, cloneRepo } from './git.js';
import { readScanRoots } from './scan-settings.js';
import { withGitAuth } from './git-auth.js';
import type { GitAuth } from './git-clients/index.js';
import type { GitCredentialsManager } from './git-credentials.js';
import type { WorktreeManager } from './worktree-manager.js';
import { recordAudit } from './audit-log.js';
export interface CloneManagerEvents {
clone_update: [CloneOperation];
}
function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
return Object.assign(new Error(message), { statusCode, code });
}
export class CloneManager extends EventEmitter<CloneManagerEvents> {
private readonly ops = new Map<string, CloneOperation>();
constructor(
private readonly db: Db,
private readonly worktrees: WorktreeManager,
private readonly credentials: GitCredentialsManager,
) {
super();
}
get(id: string): CloneOperation | null {
return this.ops.get(id) ?? null;
}
/**
* Démarre un clone (validation synchrone du dest → throw 4xx ; clone asynchrone ensuite).
* Retourne l'operationId à suivre via WS/REST. `actor` pour l'audit.
*/
async start(opts: { credentialId: string; remoteUrl: string; dest: string }, actor: string): Promise<string> {
const dest = resolve(opts.dest);
if (!isSafeAbsolutePath(dest)) throw httpError(400, 'BAD_REQUEST', 'dest must be an absolute, normalized path');
if (typeof opts.remoteUrl !== 'string' || opts.remoteUrl.trim() === '') throw httpError(400, 'BAD_REQUEST', 'remoteUrl is required');
const ctx = this.credentials.authContext(opts.credentialId);
if (!ctx) throw httpError(404, 'NOT_FOUND', 'No usable credential with this id');
// Confinement : dest DOIT être sous une racine de scan configurée (jamais d'écriture arbitraire).
const roots = readScanRoots(this.db);
if (roots.length === 0) throw httpError(400, 'NO_SCAN_ROOT', 'Configure a scan folder first (Settings → Discovery)');
const underRoot = roots.some((r) => {
const root = resolve(r);
return dest === root || dest.startsWith(root + sep);
});
if (!underRoot) throw httpError(400, 'OUTSIDE_SCAN_ROOT', 'dest must be inside a configured scan folder');
// Le parent doit exister ; le dest ne doit pas exister (git clone le crée).
const parent = dest.slice(0, dest.lastIndexOf(sep)) || sep;
try {
const st = await stat(parent);
if (!st.isDirectory()) throw httpError(400, 'BAD_DEST', 'Parent of dest is not a directory');
} catch (err) {
if ((err as { statusCode?: number }).statusCode) throw err;
throw httpError(404, 'NOT_FOUND', `Parent directory does not exist: ${parent}`);
}
if (await stat(dest).then(() => true).catch(() => false)) throw httpError(409, 'DEST_EXISTS', `Destination already exists: ${dest}`);
const id = randomUUID();
const op: CloneOperation = { id, state: 'pending', progress: null, phase: null, error: null, repoId: null, dest };
this.ops.set(id, op);
recordAudit(this.db, { actor, action: 'repo.clone', resourceId: id, details: { service: ctx.service, dest } });
// Lancement asynchrone (ne bloque pas la réponse 202).
void this.run(op, opts.remoteUrl, opts.credentialId, ctx);
return id;
}
private update(op: CloneOperation, patch: Partial<CloneOperation>): void {
Object.assign(op, patch);
this.emit('clone_update', { ...op });
}
private async run(
op: CloneOperation,
remoteUrl: string,
credentialId: string,
ctx: { service: GitService; baseUrl: string | null; auth: GitAuth },
): Promise<void> {
this.update(op, { state: 'running' });
let lastPct = -10;
const onProgress = (p: { phase: string; percent: number | null }): void => {
// throttle : on ne pousse que sur changement de phase ou +3% pour éviter le flood WS.
if (p.percent == null || p.percent - lastPct >= 3 || p.phase !== op.phase) {
lastPct = p.percent ?? lastPct;
this.update(op, { phase: p.phase, progress: p.percent });
}
};
try {
await withGitAuth(ctx.service, ctx.auth, (env) =>
cloneRepo({ url: remoteUrl, dest: op.dest, env, onProgress }),
);
// auto-enregistrement du repo cloné + métadonnées de provenance.
const repo = await this.worktrees.addRepo({ path: op.dest });
this.db
.prepare('UPDATE repos SET remote_url = ?, git_service = ?, credential_id = ? WHERE id = ?')
.run(remoteUrl, ctx.service, credentialId, repo.id);
this.update(op, { state: 'done', progress: 100, repoId: repo.id });
} catch (err) {
// nettoyage du clone partiel (best-effort).
await rm(op.dest, { recursive: true, force: true }).catch(() => {});
this.update(op, { state: 'error', error: err instanceof Error ? err.message : String(err) });
}
}
}
@@ -1,4 +1,4 @@
// Typage de dialogue à partir de l'écran reconstruit (ScreenReader) — fonctions PURES.
// Typage de dialogue à partir de l'écran reconstruit (ScreenReader) : fonctions PURES.
// L'écran sert à TYPER le dialogue et extraire ses options ; l'état (waiting vrai/faux) vient du
// registre (source primaire). Tolérant aux variations de rendu inter-versions (texte aplati + regex).
import type { DialogKind, DialogOption } from '@arboretum/shared';
@@ -23,7 +23,7 @@ export function parseOptions(lines: string[]): DialogOption[] {
/**
* Retourne le dialogue typé visible à l'écran, ou null si aucun. `trust` et `question` priment sur
* `permission` (un écran AskUserQuestion contient aussi « Esc to cancel »). Un écran numéroté non
* typé est traité en `permission` générique (best-effort — le fallback reste le terminal web).
* typé est traité en `permission` générique (best-effort, le fallback reste le terminal web).
*/
export function classifyDialog(lines: string[]): ClassifiedDialog | null {
const text = lines.join('\n');
@@ -64,13 +64,13 @@ export class DiscoveryService extends EventEmitter<DiscoveryServiceEvents> {
return this.cache;
}
/** Session découverte (avec son cwd d'origine lu sur disque) — pour resume/fork. null si absente. */
/** Session découverte (avec son cwd d'origine lu sur disque) : pour resume/fork. null si absente. */
getDiscovered(claudeSessionId: string): DiscoveredJsonl | null {
return this.byId.get(claudeSessionId) ?? null;
}
/**
* Vivacité FRAÎCHE d'une session (relit le registre, ne se fie pas au cache) — garde-fou
* Vivacité FRAÎCHE d'une session (relit le registre, ne se fie pas au cache) : garde-fou
* anti-corruption : la route /resume doit refuser une session devenue vivante depuis le dernier scan.
*/
isClaudeSessionLive(claudeSessionId: string): boolean {
+226
View File
@@ -0,0 +1,226 @@
// Watcher FS des worktrees ACTIFS (regardés par un client OU portant une session vivante).
// Émet un signal débouncé `worktree_fs_change` que le WorktreeManager traduit en recalcul du
// statut git + broadcast WS. Pool LRU borné + refcount pour ne jamais épuiser les descripteurs :
// un worktree n'est watché que tant qu'il est observé/épinglé, et la taille totale est plafonnée.
import { EventEmitter } from 'node:events';
import { resolve, sep, join } from 'node:path';
import chokidar, { type FSWatcher } from 'chokidar';
import { resolveGitDir } from './git.js';
// 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 }];
}
interface WatchEntry {
repoId: string;
path: string;
watcher: FSWatcher;
/** nombre de clients qui « regardent » ce worktree. */
refCount: number;
/** nombre de sessions vivantes épinglant ce worktree. */
sessionPins: number;
/** épingle « permanente » (checkout principal d'un repo enregistré) : jamais évincée (P11). */
repoPins: number;
lastUsed: number;
debounce: NodeJS.Timeout | null;
/** résolue quand chokidar a fini son scan initial (les events deviennent fiables). */
ready: Promise<void>;
}
/**
* Ignore tout sous `.git/` SAUF `HEAD` et `index` (⇒ on détecte le `git checkout` externe et le
* 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 {
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`));
}
return false;
}
export interface FsWatcherOptions {
maxWatchers?: number;
debounceMs?: number;
}
export class FsWatcherService extends EventEmitter<FsWatcherEvents> {
private readonly entries = new Map<string, WatchEntry>();
private readonly maxWatchers: number;
private readonly debounceMs: number;
constructor(opts: FsWatcherOptions = {}) {
super();
this.maxWatchers = opts.maxWatchers ?? DEFAULT_MAX_WATCHERS;
this.debounceMs = opts.debounceMs ?? DEBOUNCE_MS;
}
private key(repoId: string, path: string): string {
return `${repoId}\0${resolve(path)}`;
}
/** Un client commence à observer un worktree (vue IDE ouverte). */
watch(repoId: string, path: string): void {
const e = this.ensure(repoId, path);
e.refCount++;
e.lastUsed = Date.now();
}
/** Un client cesse d'observer ; le watcher reste (idle) jusqu'à éviction LRU. */
unwatch(repoId: string, path: string): void {
const e = this.entries.get(this.key(repoId, path));
if (!e) return;
e.refCount = Math.max(0, e.refCount - 1);
e.lastUsed = Date.now();
}
/** Épingle un worktree tant qu'une session y est vivante (jamais évincé). */
pinSession(repoId: string, path: string): void {
const e = this.ensure(repoId, path);
e.sessionPins++;
e.lastUsed = Date.now();
}
unpinSession(repoId: string, path: string): void {
const e = this.entries.get(this.key(repoId, path));
if (!e) return;
e.sessionPins = Math.max(0, e.sessionPins - 1);
e.lastUsed = Date.now();
}
/**
* Épingle en PERMANENCE le checkout principal d'un repo enregistré (P11) : ainsi un `git checkout`
* en CLI sur le principal est détecté et rediffusé sans qu'aucun client n'ait « regardé » ce
* worktree. Idempotent (un seul pin par repo+path conservé). Jamais évincé par la LRU.
*/
pinRepo(repoId: string, path: string): void {
const e = this.ensure(repoId, path);
e.repoPins = 1; // idempotent : on ne cumule pas (un seul checkout principal par repo)
e.lastUsed = Date.now();
}
unpinRepo(repoId: string, path: string): void {
const e = this.entries.get(this.key(repoId, path));
if (!e) return;
e.repoPins = 0;
e.lastUsed = Date.now();
}
/** Nombre de watchers actifs (test/diagnostic). */
size(): number {
return this.entries.size;
}
isWatching(repoId: string, path: string): boolean {
return this.entries.has(this.key(repoId, path));
}
/** Résout quand le watcher de ce worktree a fini son scan initial (utile aux tests). */
whenReady(repoId: string, path: string): Promise<void> {
return this.entries.get(this.key(repoId, path))?.ready ?? Promise.resolve();
}
private ensure(repoId: string, path: string): WatchEntry {
const key = this.key(repoId, path);
const existing = this.entries.get(key);
if (existing) return existing;
const abs = resolve(path);
const watcher = chokidar.watch(abs, {
ignored: (p: string) => isIgnoredPath(p),
ignoreInitial: true,
// coalesce les écritures rapides (build, génération) avant d'émettre.
awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 40 },
});
let resolveReady: () => void = () => {};
const ready = new Promise<void>((r) => (resolveReady = r));
watcher.once('ready', () => resolveReady());
const entry: WatchEntry = { repoId, path: abs, watcher, refCount: 0, sessionPins: 0, repoPins: 0, lastUsed: Date.now(), debounce: null, ready };
const onChange = (): void => this.schedule(entry);
watcher.on('add', onChange).on('change', onChange).on('unlink', onChange).on('addDir', onChange).on('unlinkDir', onChange);
this.entries.set(key, entry);
// Worktree LIÉ : HEAD/index vivent hors du worktree (dans .git/worktrees/<n>). On les ajoute
// explicitement pour capter un changement de branche externe (git checkout en CLI).
void resolveGitDir(abs).then((gitDir) => {
if (!gitDir || !this.entries.has(key)) return;
if (gitDir === join(abs, '.git') || gitDir.startsWith(abs + sep)) return; // déjà couvert
watcher.add([join(gitDir, 'HEAD'), join(gitDir, 'index')]);
}).catch(() => {});
this.evictIfNeeded();
return entry;
}
private schedule(entry: WatchEntry): void {
if (entry.debounce) clearTimeout(entry.debounce);
entry.debounce = setTimeout(() => {
entry.debounce = null;
entry.lastUsed = Date.now();
this.emit('worktree_fs_change', { repoId: entry.repoId, path: entry.path });
}, this.debounceMs);
entry.debounce.unref();
}
/** Ferme les watchers idle (refCount===0 && sessionPins===0) les moins récents au-delà du plafond. */
private evictIfNeeded(): void {
if (this.entries.size <= this.maxWatchers) return;
const idle = [...this.entries.entries()]
.filter(([, e]) => e.refCount === 0 && e.sessionPins === 0 && e.repoPins === 0)
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
for (const [key, e] of idle) {
if (this.entries.size <= this.maxWatchers) break;
this.close(key, e);
}
// Si tout est actif (reffé/épinglé), on dépasse le plafond volontairement : un worktree
// explicitement observé ne doit jamais perdre son temps réel.
}
private close(key: string, e: WatchEntry): void {
if (e.debounce) clearTimeout(e.debounce);
void e.watcher.close().catch(() => {});
this.entries.delete(key);
}
/** Libère tous les descripteurs (drain SIGTERM/SIGINT). */
async closeAll(): Promise<void> {
const all = [...this.entries.entries()];
this.entries.clear();
await Promise.all(all.map(([, e]) => {
if (e.debounce) clearTimeout(e.debounce);
return e.watcher.close().catch(() => {});
}));
}
}
+60
View File
@@ -0,0 +1,60 @@
// Préparation d'un environnement d'authentification git ÉPHÉMÈRE (P12). HTTPS (pat/app_password) :
// 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';
import type { GitService } from '@arboretum/shared';
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 script = askpassScript();
const askpass = join(dir, script.name);
const user = auth.username || SERVICE_DEFAULT_USER[service];
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,
GIT_TERMINAL_PROMPT: '0',
ARB_GIT_USER: user,
ARB_GIT_PASS: auth.secret,
};
try {
return await fn(env);
} finally {
await rm(dir, { recursive: true, force: true }).catch(() => {});
}
}
@@ -0,0 +1,156 @@
// Clients des services git distants (Gitea / GitLab / GitHub) : P12. Uniquement `fetch` global
// (Node ≥ 22), AUCUNE dépendance (pas d'octokit/gitbeaker). Chaque client expose verify() (test de
// connectivité/auth) et listRepos() (paginé). Erreurs typées : AUTH_FAILED / RATE_LIMITED / UNREACHABLE.
import type { GitAuthType, GitService, RemoteRepoSummary } from '@arboretum/shared';
const REQUEST_TIMEOUT_MS = 12_000;
const PER_PAGE = 30;
export interface GitAuth {
authType: GitAuthType;
username: string | null;
secret: string;
}
export class GitServiceError extends Error {
constructor(
public readonly errorCode: string,
message?: string,
) {
super(message ?? errorCode);
this.name = 'GitServiceError';
}
}
export interface GitClient {
verify(auth: GitAuth): Promise<{ login: string }>;
listRepos(auth: GitAuth, page: number, search?: string): Promise<{ repos: RemoteRepoSummary[]; nextPage: number | null }>;
}
/** En-têtes d'auth selon le type. app_password → Basic (username:secret) ; pat → en-tête propre au service. */
function authHeaders(service: GitService, auth: GitAuth): Record<string, string> {
if (auth.authType === 'app_password') {
const basic = Buffer.from(`${auth.username ?? ''}:${auth.secret}`).toString('base64');
return { Authorization: `Basic ${basic}` };
}
// pat
if (service === 'gitlab') return { 'PRIVATE-TOKEN': auth.secret };
if (service === 'gitea') return { Authorization: `token ${auth.secret}` };
return { Authorization: `Bearer ${auth.secret}` }; // github
}
/** Refuse une base self-hosted non http(s) (anti-SSRF schéma) ; renvoie l'origine normalisée sans `/` final. */
function normalizeBase(baseUrl: string): string {
let u: URL;
try {
u = new URL(baseUrl);
} catch {
throw new GitServiceError('BAD_BASE_URL', 'base_url must be a valid http(s) URL');
}
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new GitServiceError('BAD_BASE_URL', 'base_url must be http(s)');
return `${u.origin}${u.pathname}`.replace(/\/+$/, '');
}
async function fetchJson(url: string, headers: Record<string, string>): Promise<{ json: unknown; headers: Headers }> {
let res: Response;
try {
res = await fetch(url, { headers: { Accept: 'application/json', ...headers }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
} catch {
throw new GitServiceError('UNREACHABLE', 'Could not reach the git service');
}
if (res.status === 429) throw new GitServiceError('RATE_LIMITED', 'Rate limited by the git service');
if (res.status === 401 || res.status === 403) {
// 403 + quota épuisé = rate limit (GitHub) ; sinon échec d'auth.
if (res.headers.get('x-ratelimit-remaining') === '0') throw new GitServiceError('RATE_LIMITED', 'Rate limited by the git service');
throw new GitServiceError('AUTH_FAILED', 'Authentication failed');
}
if (!res.ok) throw new GitServiceError(`HTTP_${res.status}`, `Unexpected response ${res.status}`);
return { json: await res.json().catch(() => null), headers: res.headers };
}
function githubBase(baseUrl: string | null): string {
return baseUrl ? normalizeBase(baseUrl) : 'https://api.github.com';
}
function gitlabBase(baseUrl: string | null): string {
return `${baseUrl ? normalizeBase(baseUrl) : 'https://gitlab.com'}/api/v4`;
}
function giteaBase(baseUrl: string | null): string {
if (!baseUrl) throw new GitServiceError('BAD_BASE_URL', 'Gitea requires a base_url (self-hosted instance)');
return `${normalizeBase(baseUrl)}/api/v1`;
}
const githubClient = (baseUrl: string | null): GitClient => {
const base = githubBase(baseUrl);
return {
async verify(auth) {
const { json } = await fetchJson(`${base}/user`, authHeaders('github', auth));
return { login: String((json as { login?: string })?.login ?? '') };
},
async listRepos(auth, page) {
const { json } = await fetchJson(`${base}/user/repos?per_page=${PER_PAGE}&page=${page}&sort=updated`, authHeaders('github', auth));
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
const repos = arr.map((r): RemoteRepoSummary => ({
fullName: String(r.full_name ?? ''),
cloneUrl: String(r.clone_url ?? ''),
private: Boolean(r.private),
description: (r.description as string | null) ?? null,
defaultBranch: (r.default_branch as string | null) ?? null,
}));
return { repos, nextPage: arr.length === PER_PAGE ? page + 1 : null };
},
};
};
const gitlabClient = (baseUrl: string | null): GitClient => {
const base = gitlabBase(baseUrl);
return {
async verify(auth) {
const { json } = await fetchJson(`${base}/user`, authHeaders('gitlab', auth));
return { login: String((json as { username?: string })?.username ?? '') };
},
async listRepos(auth, page) {
const { json, headers } = await fetchJson(
`${base}/projects?membership=true&per_page=${PER_PAGE}&page=${page}&order_by=last_activity_at`,
authHeaders('gitlab', auth),
);
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
const repos = arr.map((r): RemoteRepoSummary => ({
fullName: String(r.path_with_namespace ?? ''),
cloneUrl: String(r.http_url_to_repo ?? ''),
private: r.visibility !== 'public',
description: (r.description as string | null) ?? null,
defaultBranch: (r.default_branch as string | null) ?? null,
}));
const next = headers.get('x-next-page');
return { repos, nextPage: next ? Number(next) : null };
},
};
};
const giteaClient = (baseUrl: string | null): GitClient => {
const base = giteaBase(baseUrl);
return {
async verify(auth) {
const { json } = await fetchJson(`${base}/user`, authHeaders('gitea', auth));
return { login: String((json as { login?: string })?.login ?? '') };
},
async listRepos(auth, page) {
const { json } = await fetchJson(`${base}/user/repos?page=${page}&limit=${PER_PAGE}`, authHeaders('gitea', auth));
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
const repos = arr.map((r): RemoteRepoSummary => ({
fullName: String(r.full_name ?? ''),
cloneUrl: String(r.clone_url ?? ''),
private: Boolean(r.private),
description: (r.description as string | null) ?? null,
defaultBranch: (r.default_branch as string | null) ?? null,
}));
return { repos, nextPage: arr.length === PER_PAGE ? page + 1 : null };
},
};
};
export function getGitClient(service: GitService, baseUrl: string | null): GitClient {
if (service === 'github') return githubClient(baseUrl);
if (service === 'gitlab') return gitlabClient(baseUrl);
return giteaClient(baseUrl);
}
+180
View File
@@ -0,0 +1,180 @@
// Gestion des credentials des services git distants (P12). Les secrets (PAT/app password) sont
// chiffrés par SecretBox AVANT insertion et ne ressortent JAMAIS via l'API (résumés sans secret).
// getSecret()/authFor() sont INTERNES (clone, listRepos, test) : jamais routés.
import { randomUUID } from 'node:crypto';
import type {
CreateGitCredentialRequest,
GitCredentialSummary,
GitService,
TestCredentialResponse,
UpdateGitCredentialRequest,
} from '@arboretum/shared';
import type { Db } from '../db/index.js';
import type { SecretBox } from './secret-box.js';
import { getGitClient, GitServiceError, type GitAuth } from './git-clients/index.js';
import { recordAudit } from './audit-log.js';
interface GitCredentialRow {
id: string;
label: string;
service: GitService;
base_url: string | null;
auth_type: GitCredentialSummary['authType'];
username: string | null;
secret_encrypted: string | null;
ssh_key_path: string | null;
oauth_access_encrypted: string | null;
oauth_refresh_encrypted: string | null;
oauth_expires_at: string | null;
created_at: string;
last_tested_at: string | null;
test_result: string | null;
}
function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
return Object.assign(new Error(message), { statusCode, code });
}
export class GitCredentialsManager {
constructor(
private readonly db: Db,
private readonly box: SecretBox,
) {}
private getRow(id: string): GitCredentialRow | null {
return (this.db.prepare('SELECT * FROM git_credentials WHERE id = ?').get(id) as unknown as GitCredentialRow | undefined) ?? null;
}
private toSummary(row: GitCredentialRow): GitCredentialSummary {
let secretLast4: string | null = null;
if (row.secret_encrypted) {
try {
const s = this.box.decrypt(row.secret_encrypted);
secretLast4 = s.length >= 4 ? s.slice(-4) : '••••';
} catch {
secretLast4 = null;
}
}
return {
id: row.id,
label: row.label,
service: row.service,
baseUrl: row.base_url,
authType: row.auth_type,
username: row.username,
hasSecret: row.secret_encrypted != null,
secretLast4,
createdAt: row.created_at,
lastTestedAt: row.last_tested_at,
testResult: row.test_result,
};
}
list(): GitCredentialSummary[] {
const rows = this.db.prepare('SELECT * FROM git_credentials ORDER BY created_at ASC').all() as unknown as GitCredentialRow[];
return rows.map((r) => this.toSummary(r));
}
get(id: string): GitCredentialSummary | null {
const row = this.getRow(id);
return row ? this.toSummary(row) : null;
}
create(opts: CreateGitCredentialRequest): GitCredentialSummary {
// P12a : seules les méthodes HTTPS (pat / app_password) sont supportées pour l'instant.
if (opts.authType !== 'pat' && opts.authType !== 'app_password') {
throw httpError(400, 'UNSUPPORTED_AUTH', 'Only pat and app_password are supported for now (SSH/OAuth: later phases)');
}
if (!opts.label?.trim()) throw httpError(400, 'BAD_REQUEST', 'label is required');
if (opts.service !== 'gitea' && opts.service !== 'gitlab' && opts.service !== 'github') {
throw httpError(400, 'BAD_REQUEST', 'service must be gitea, gitlab or github');
}
if (opts.service === 'gitea' && !opts.baseUrl) throw httpError(400, 'BAD_REQUEST', 'Gitea requires a base_url');
if (!opts.secret) throw httpError(400, 'BAD_REQUEST', 'secret (token) is required');
const row: GitCredentialRow = {
id: randomUUID(),
label: opts.label.trim(),
service: opts.service,
base_url: opts.baseUrl?.trim() || null,
auth_type: opts.authType,
username: opts.username?.trim() || null,
secret_encrypted: this.box.encrypt(opts.secret),
ssh_key_path: null,
oauth_access_encrypted: null,
oauth_refresh_encrypted: null,
oauth_expires_at: null,
created_at: new Date().toISOString(),
last_tested_at: null,
test_result: null,
};
this.db
.prepare(
`INSERT INTO git_credentials (id, label, service, base_url, auth_type, username, secret_encrypted, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(row.id, row.label, row.service, row.base_url, row.auth_type, row.username, row.secret_encrypted, row.created_at);
return this.toSummary(row);
}
update(id: string, patch: UpdateGitCredentialRequest): GitCredentialSummary {
const row = this.getRow(id);
if (!row) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
if (patch.baseUrl !== undefined) row.base_url = patch.baseUrl.trim() || null;
if (patch.username !== undefined) row.username = patch.username.trim() || null;
if (patch.secret) row.secret_encrypted = this.box.encrypt(patch.secret);
this.db
.prepare('UPDATE git_credentials SET label = ?, base_url = ?, username = ?, secret_encrypted = ? WHERE id = ?')
.run(row.label, row.base_url, row.username, row.secret_encrypted, id);
return this.toSummary(row);
}
/** Supprime un credential et NULLifie repos.credential_id (pas de FK). */
remove(id: string): boolean {
const res = this.db.prepare('DELETE FROM git_credentials WHERE id = ?').run(id);
if (res.changes === 0) return false;
this.db.prepare('UPDATE repos SET credential_id = NULL WHERE credential_id = ?').run(id);
return true;
}
/** Secret déchiffré : INTERNE (clone/listRepos/test). Jamais exposé par une route. */
getSecret(id: string): string | null {
const row = this.getRow(id);
if (!row?.secret_encrypted) return null;
try {
return this.box.decrypt(row.secret_encrypted);
} catch {
return null;
}
}
/** Contexte d'auth (service, base, secret déchiffré) pour le client API / le clone. */
authContext(id: string): { service: GitService; baseUrl: string | null; auth: GitAuth } | null {
const row = this.getRow(id);
if (!row) return null;
const secret = this.getSecret(id);
if (secret == null) return null;
return { service: row.service, baseUrl: row.base_url, auth: { authType: row.auth_type, username: row.username, secret } };
}
/** Teste la connectivité/auth (GET /user) et mémorise le diagnostic. */
async test(id: string): Promise<TestCredentialResponse> {
const ctx = this.authContext(id);
if (!ctx) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
const now = new Date().toISOString();
try {
const { login } = await getGitClient(ctx.service, ctx.baseUrl).verify(ctx.auth);
this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, 'ok', id);
return { ok: true, user: login };
} catch (err) {
const code = err instanceof GitServiceError ? err.errorCode : 'UNREACHABLE';
this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, code, id);
return { ok: false, error: code };
}
}
}
/** Helper d'audit partagé (jamais de secret dans details). */
export function auditCredential(db: Db, actor: string, action: string, id: string | null): void {
recordAudit(db, { actor, action, resourceId: id });
}
+424 -8
View File
@@ -1,8 +1,8 @@
// Couche git sûre : tout passe par execFile (JAMAIS de shell), arguments en tableau, `--` avant
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
import { execFile } from 'node:child_process';
import { execFile, spawn } from 'node:child_process';
import { resolve, sep } from 'node:path';
import type { WorktreeGitStatus, WorktreeBranchAction, WorktreeBranchMode } 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.
@@ -39,6 +39,24 @@ function git(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): P
});
}
/**
* Variante tolérante : résout `{ stdout, code }` au lieu de rejeter sur code de sortie non nul.
* Utile pour `git diff --no-index` (code 1 = « les fichiers diffèrent », pas une erreur).
*/
function gitRaw(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): Promise<{ stdout: string; code: number }> {
return new Promise((resolveP) => {
execFile(
'git',
args,
{ cwd, timeout: timeoutMs, maxBuffer: GIT_MAX_BUFFER, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' } },
(err, stdout) => {
const code = err ? ((err as GitError).code as number) ?? 1 : 0;
resolveP({ stdout: stdout.toString(), code: typeof code === 'number' ? code : 1 });
},
);
});
}
export interface ParsedWorktree {
path: string;
head: string | null;
@@ -122,6 +140,21 @@ export function isSafeAbsolutePath(p: string): boolean {
return p.startsWith('/') && resolve(p) === p && !p.split(sep).includes('..');
}
/**
* Pathspec relatif sûr passé à git (`git add/restore/diff -- <p>`) : non vide, non absolu, sans
* segment `..`, ne commençant pas par `-` (anti-flag). Le `--` avant le pathspec reste obligatoire.
*/
export function isSafeRelativePath(p: string): boolean {
if (p.length === 0 || p.startsWith('/') || p.startsWith('-')) return false;
const parts = p.split(/[\\/]/);
return !parts.includes('..') && !parts.includes('.git');
}
/** Initialise un dépôt git dans `dir` (déjà créé et validé par l'appelant). `git init` est idempotent. */
export async function gitInit(dir: string): Promise<void> {
await git(dir, ['init']);
}
/** true si `path` est la racine d'un dépôt git (main worktree) accessible. */
export async function isRepo(path: string): Promise<boolean> {
try {
@@ -166,7 +199,7 @@ export async function branchExists(repoPath: string, branch: string): Promise<{
return { local, remote };
}
/** Branches locales + suivies de `origin` (noms courts) + branche par défaut — pour un sélecteur de base. */
/** Branches locales + suivies de `origin` (noms courts) + branche par défaut : pour un sélecteur de base. */
export async function listBranches(repoPath: string): Promise<{ local: string[]; remote: string[]; default: string | null }> {
const local: string[] = [];
const remote: string[] = [];
@@ -214,13 +247,349 @@ export async function worktreeStatus(worktreePath: string): Promise<WorktreeGitS
}
}
let dirtyCount = 0;
let stagedCount = 0;
let unstagedCount = 0;
let conflictCount = 0;
try {
const status = await git(worktreePath, ['status', '--porcelain=v1', '--untracked-files=all']);
dirtyCount = status.split('\n').filter((l) => l.trim() !== '').length;
// Un SEUL passage porcelain v2 -z : dirtyCount + compteurs fins (staged/unstaged/conflit).
const out = await git(worktreePath, ['status', '--porcelain=v2', '-z', '--untracked-files=all']);
const entries = parsePorcelainV2(out);
dirtyCount = entries.length;
for (const e of entries) {
if (e.conflicted) conflictCount++;
if (e.staged) stagedCount++;
if (e.unstaged) unstagedCount++;
}
} catch {
/* ignore */
}
return { ahead, behind, dirtyCount, upstream };
let lastCommitHash: string | null = null;
let lastCommitSubject: string | null = null;
try {
const lc = await lastCommit(worktreePath);
if (lc) {
lastCommitHash = lc.hash;
lastCommitSubject = lc.subject;
}
} catch {
/* repo sans commit : on laisse null */
}
return { ahead, behind, dirtyCount, upstream, stagedCount, unstagedCount, conflictCount, lastCommitHash, lastCommitSubject };
}
// ---- P7 : statut détaillé / diff / staging / commit sélectif / fetch-pull (IDE worktree) ----
/** Entrée brute de `git status --porcelain=v2` (avant enrichissement numstat). */
export interface PorcelainV2Entry {
path: string;
indexStatus: string;
worktreeStatus: string;
staged: boolean;
unstaged: boolean;
untracked: boolean;
conflicted: boolean;
renamedFrom?: string;
}
/**
* Parse `git status --porcelain=v2 -z --untracked-files=all` (testable sans repo réel). Format -z :
* champs séparés par NUL ; une entrée de renommage (type `2`) consomme un champ supplémentaire
* (l'ancien chemin). Les chemins ne sont jamais entre guillemets en mode -z (pas d'échappement).
*/
export function parsePorcelainV2(stdout: string): PorcelainV2Entry[] {
const fields = stdout.split('\0');
if (fields.length && fields[fields.length - 1] === '') fields.pop();
const out: PorcelainV2Entry[] = [];
for (let i = 0; i < fields.length; i++) {
const f = fields[i];
if (!f) continue;
const kind = f[0];
if (kind === '1') {
const t = f.split(' ');
const xy = t[1] ?? '..';
out.push(entryFromXy(t.slice(8).join(' '), xy, { conflicted: false }));
} else if (kind === '2') {
const t = f.split(' ');
const xy = t[1] ?? '..';
const path = t.slice(9).join(' ');
const renamedFrom = fields[++i]; // l'ancien chemin suit dans le champ NUL suivant
out.push(entryFromXy(path, xy, { conflicted: false, ...(renamedFrom ? { renamedFrom } : {}) }));
} else if (kind === 'u') {
const t = f.split(' ');
const xy = t[1] ?? '..';
out.push(entryFromXy(t.slice(10).join(' '), xy, { conflicted: true }));
} else if (kind === '?') {
out.push({ path: f.slice(2), indexStatus: '?', worktreeStatus: '?', staged: false, unstaged: true, untracked: true, conflicted: false });
}
// '!' (ignored) : exclu de la liste des changements.
}
return out;
}
function entryFromXy(path: string, xy: string, opts: { conflicted: boolean; renamedFrom?: string }): PorcelainV2Entry {
const indexStatus = xy[0] ?? '.';
const worktreeStatus = xy[1] ?? '.';
return {
path,
indexStatus,
worktreeStatus,
staged: !opts.conflicted && indexStatus !== '.',
unstaged: opts.conflicted || worktreeStatus !== '.',
untracked: false,
conflicted: opts.conflicted,
...(opts.renamedFrom ? { renamedFrom: opts.renamedFrom } : {}),
};
}
/**
* Parse `git diff --numstat -z` → map chemin → {insertions, deletions, binary}. Les fichiers
* binaires sont marqués `'-'` par git. Les renommages ont un champ chemin vide suivi de
* deux champs NUL (ancien, nouveau) ; on indexe par le nouveau chemin.
*/
export function parseNumstatZ(stdout: string): Map<string, { insertions: number | null; deletions: number | null; binary: boolean }> {
const fields = stdout.split('\0');
if (fields.length && fields[fields.length - 1] === '') fields.pop();
const map = new Map<string, { insertions: number | null; deletions: number | null; binary: boolean }>();
for (let i = 0; i < fields.length; i++) {
const f = fields[i];
if (!f) continue;
const parts = f.split('\t');
if (parts.length < 3) continue;
const addRaw = parts[0] ?? '';
const delRaw = parts[1] ?? '';
let path = parts[2] ?? '';
if (path === '') {
// renommage : ancien chemin = champ suivant, nouveau chemin = champ d'après.
i++; // saute l'ancien chemin
path = fields[++i] ?? '';
if (path === '') continue;
}
const binary = addRaw === '-' || delRaw === '-';
map.set(path, {
insertions: binary ? null : Number(addRaw) || 0,
deletions: binary ? null : Number(delRaw) || 0,
binary,
});
}
return map;
}
const MAX_CHANGES = 5000;
/** Liste les fichiers modifiés d'un worktree (statut porcelain v2 enrichi des stats numstat). */
export async function listChanges(worktreePath: string): Promise<{ changes: FileChange[]; truncated: boolean }> {
const [statusOut, unstagedOut, stagedOut] = await Promise.all([
git(worktreePath, ['status', '--porcelain=v2', '-z', '--untracked-files=all']),
git(worktreePath, ['diff', '--numstat', '-z']),
git(worktreePath, ['diff', '--numstat', '-z', '--cached']),
]);
const entries = parsePorcelainV2(statusOut);
const unstaged = parseNumstatZ(unstagedOut);
const staged = parseNumstatZ(stagedOut);
const truncated = entries.length > MAX_CHANGES;
const slice = truncated ? entries.slice(0, MAX_CHANGES) : entries;
const changes: FileChange[] = slice.map((e) => {
const ns = unstaged.get(e.path) ?? staged.get(e.path);
const binary = ns?.binary ?? false;
// insertions/deletions = somme staged+unstaged quand disponible ; null pour binaire/untracked.
const u = unstaged.get(e.path);
const s = staged.get(e.path);
const sum = (a: number | null | undefined, b: number | null | undefined): number | null => {
if (a == null && b == null) return null;
return (a ?? 0) + (b ?? 0);
};
return {
path: e.path,
indexStatus: e.indexStatus,
worktreeStatus: e.worktreeStatus,
staged: e.staged,
unstaged: e.unstaged,
untracked: e.untracked,
conflicted: e.conflicted,
insertions: binary ? null : sum(u?.insertions, s?.insertions),
deletions: binary ? null : sum(u?.deletions, s?.deletions),
binary,
...(e.renamedFrom ? { renamedFrom: e.renamedFrom } : {}),
};
});
return { changes, truncated };
}
const MAX_DIFF_BYTES = 512 * 1024;
/** Diff unifié d'un fichier. `staged` → diff de l'index ; `untracked` → diff vs /dev/null. */
export async function fileDiff(
worktreePath: string,
file: string,
opts: { staged?: boolean; untracked?: boolean } = {},
): Promise<{ diff: string; binary: boolean; tooLarge: boolean }> {
let raw: string;
if (opts.untracked) {
// --no-index sort en code 1 quand les fichiers diffèrent : on tolère via gitRaw.
const r = await gitRaw(worktreePath, ['diff', '--no-index', '--no-color', '--', '/dev/null', file]);
raw = r.stdout;
} else {
raw = await git(worktreePath, ['diff', '--no-color', ...(opts.staged ? ['--cached'] : []), '--', file]);
}
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 };
}
/** Indexe des fichiers (`git add -- <files>`). Chaque chemin validé par l'appelant (isSafeRelativePath). */
export async function stageFiles(worktreePath: string, files: string[]): Promise<void> {
if (files.length === 0) return;
await git(worktreePath, ['add', '--', ...files]);
}
/** Désindexe des fichiers (`git restore --staged -- <files>`). */
export async function unstageFiles(worktreePath: string, files: string[]): Promise<void> {
if (files.length === 0) return;
await git(worktreePath, ['restore', '--staged', '--', ...files]);
}
/** Annule les modifications de l'arbre de travail de fichiers SUIVIS (`git restore -- <files>`). */
export async function restoreFiles(worktreePath: string, files: string[]): Promise<void> {
if (files.length === 0) return;
await git(worktreePath, ['restore', '--', ...files]);
}
/** Supprime des fichiers NON SUIVIS (`git clean -f -- <files>`). Destructif : opt-in côté appelant. */
export async function cleanFiles(worktreePath: string, files: string[]): Promise<void> {
if (files.length === 0) return;
await git(worktreePath, ['clean', '-f', '--', ...files]);
}
/** Commit de l'index uniquement (contraste avec `commitAll` = `git add -A` + commit). */
export async function commitStaged(worktreePath: string, message: string): Promise<void> {
await git(worktreePath, ['commit', '-m', message]);
}
/** Réécrit le dernier commit. L'appelant garantit qu'il n'est pas déjà poussé. */
export async function amendCommit(worktreePath: string, message?: string): Promise<void> {
await git(worktreePath, message ? ['commit', '--amend', '-m', message] : ['commit', '--amend', '--no-edit']);
}
/** `git fetch --all --prune` (réseau → timeout élargi). */
export async function fetchRemote(worktreePath: string): Promise<void> {
await git(worktreePath, ['fetch', '--all', '--prune'], GIT_PUSH_TIMEOUT_MS);
}
/** `git pull` : `ff-only` par défaut (jamais de merge surprise) ; `rebase` optionnel. */
export async function pull(worktreePath: string, mode: 'ff-only' | 'rebase' = 'ff-only'): Promise<void> {
const args = mode === 'rebase' ? ['-c', 'rebase.autoStash=false', 'pull', '--rebase'] : ['pull', '--ff-only'];
await git(worktreePath, args, GIT_PUSH_TIMEOUT_MS);
}
/**
* Répertoire git absolu d'un worktree (`git rev-parse --absolute-git-dir`). Pour le checkout
* principal : `<path>/.git` ; pour un worktree LIÉ : `<repo>/.git/worktrees/<n>` (le `.git` du
* worktree est un fichier pointeur). Sert au watcher FS pour surveiller le bon `HEAD`/`index`.
*/
export async function resolveGitDir(worktreePath: string): Promise<string | null> {
const r = await gitRaw(worktreePath, ['rev-parse', '--absolute-git-dir']);
if (r.code !== 0) return null;
return r.stdout.trim() || null;
}
/** Dernier commit (HEAD) : hash court + sujet. null si le dépôt n'a aucun commit. */
export async function lastCommit(worktreePath: string): Promise<{ hash: string; subject: string } | null> {
const r = await gitRaw(worktreePath, ['log', '-1', '--format=%h%x00%s']);
if (r.code !== 0) return null;
const idx = r.stdout.indexOf('\0');
if (idx === -1) return null;
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 {
await git(worktreePath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
} catch {
return true; // pas d'upstream → rien n'est « partagé »
}
try {
const out = (await git(worktreePath, ['rev-list', '--count', '@{u}..HEAD'])).trim();
return (Number(out) || 0) > 0;
} catch {
return true;
}
}
/** Point de départ d'une branche créée : `baseRef` explicite, sinon la branche par défaut du dépôt
@@ -238,7 +607,7 @@ async function resolveStartPoint(repoPath: string, baseRef?: string): Promise<st
/**
* Crée un worktree en résolvant la branche selon `mode` (voir `WorktreeBranchMode`). Renvoie l'action
* effective. En mode `auto`, on choisit checkout / suivi-remote / création selon l'existence réelle de
* la branche — indispensable pour les groupes hétérogènes (branche présente dans certains dépôts seulement).
* la branche : indispensable pour les groupes hétérogènes (branche présente dans certains dépôts seulement).
*/
export async function addWorktree(
repoPath: string,
@@ -289,7 +658,7 @@ export async function push(repoPath: string): Promise<void> {
}
/**
* Crée/bascule une branche dans le checkout (worktree) en `repoPath` — utilisé pour démarrer une
* Crée/bascule une branche dans le checkout (worktree) en `repoPath` : utilisé pour démarrer une
* session sur la branche principale sans worktree dédié. `create` → `git switch -c <branch>` (échoue
* si la branche existe) ; sinon `git switch <branch>` (branche existante). Pas de `--` : l'argument
* est une réf (pas un pathspec) et le nom est déjà filtré en amont par `isValidBranchName` (anti-flag).
@@ -311,3 +680,50 @@ export function isDirtyWorktreeError(err: unknown): boolean {
const msg = `${(err as GitError)?.stderr ?? ''} ${(err as Error)?.message ?? ''}`;
return /contains modified or untracked files|is dirty|use --force/i.test(msg);
}
const GIT_CLONE_TIMEOUT_MS = 10 * 60_000; // 10 min : un clone réseau peut être long.
export interface CloneProgress {
phase: string;
/** pourcentage 0-100 si git le rapporte, sinon null. */
percent: number | null;
}
/**
* Clone un dépôt via `git clone --progress` (P12). `spawn` (et non execFile) pour streamer la
* progression depuis stderr. `env` éphémère (cf. withGitAuth) porte l'auth : JAMAIS dans l'URL.
* `--` sépare l'URL/dest des options. L'appelant valide `dest` (sous scanRoots, non existant).
*/
export function cloneRepo(opts: {
url: string;
dest: string;
env?: NodeJS.ProcessEnv;
branch?: string;
onProgress?: (p: CloneProgress) => void;
signal?: AbortSignal;
}): Promise<void> {
return new Promise((resolveP, reject) => {
const args = ['clone', '--progress'];
if (opts.branch) args.push('--branch', opts.branch);
args.push('--', opts.url, opts.dest);
const child = spawn('git', args, {
env: { ...(opts.env ?? process.env), GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
stdio: ['ignore', 'ignore', 'pipe'],
timeout: GIT_CLONE_TIMEOUT_MS,
...(opts.signal ? { signal: opts.signal } : {}),
});
let stderr = '';
child.stderr.on('data', (d: Buffer) => {
const s = d.toString();
stderr += s;
if (stderr.length > 64 * 1024) stderr = stderr.slice(-64 * 1024); // borne mémoire
const m = /([A-Za-z][A-Za-z ]+):\s+(\d+)%/.exec(s);
if (m && m[1] && m[2] && opts.onProgress) opts.onProgress({ phase: m[1].trim(), percent: Number(m[2]) });
});
child.on('error', (err) => reject(err));
child.on('close', (code) => {
if (code === 0) resolveP();
else reject(new Error(stderr.trim().split('\n').pop() || `git clone exited with code ${code}`));
});
});
}
+1 -1
View File
@@ -1,5 +1,5 @@
// Gestion des groupes de travail (P5) : un groupe = collection nommée de repos (many-to-many).
// Membership légère et persistée ; les worktrees/sessions du groupe ne sont PAS stockés ici —
// Membership légère et persistée ; les worktrees/sessions du groupe ne sont PAS stockés ici :
// ils restent servis par WorktreeManager/PtyManager et filtrés côté client par repoId.
// Tout est synchrone : aucune I/O git/fs, node:sqlite est synchrone.
import { EventEmitter } from 'node:events';
+1 -1
View File
@@ -2,7 +2,7 @@ import { parse, resolve, sep } from 'node:path';
/**
* Plus long ancêtre commun d'un ensemble de chemins absolus (par segments, jamais par préfixe
* de chaîne — `/a/bc` n'est PAS un ancêtre de `/a/bcd`). Pour un seul chemin, renvoie ce chemin.
* de chaîne : `/a/bc` n'est PAS un ancêtre de `/a/bcd`). Pour un seul chemin, renvoie ce chemin.
*/
export function commonAncestorDir(paths: string[]): string {
const first = paths[0];
+2 -2
View File
@@ -10,7 +10,7 @@ const HEAD_BYTES = 256 * 1024;
const TAIL_BYTES = 64 * 1024;
const TITLE_MAX = 120;
/** Reproduit le nom de dossier ~/.claude/projects à partir d'un cwd (validé 100 % — spike S4). */
/** Reproduit le nom de dossier ~/.claude/projects à partir d'un cwd (validé 100 %, spike S4). */
export function munge(cwd: string): string {
return cwd.replace(/[^A-Za-z0-9]/g, '-');
}
@@ -82,7 +82,7 @@ function extractMeta(objs: Array<Record<string, unknown>>, meta: Meta): void {
setOnce('cwd', o.cwd);
setOnce('gitBranch', o.gitBranch);
setOnce('version', o.version);
// Titre : on retient la dernière valeur vue (la plus récente) — head puis tail → la queue gagne.
// Titre : on retient la dernière valeur vue (la plus récente) : head puis tail → la queue gagne.
const ai = asString(o.aiTitle);
if (ai) meta.aiTitle = ai;
const sum = asString(o.summary);
+83
View File
@@ -0,0 +1,83 @@
// Auto-détection des commandes de démarrage d'un projet (« Démarrer le projet »).
// Fonctions PURES et sans effet de bord notable : lecture bornée de quelques fichiers connus dans
// UN répertoire (jamais de récursion, jamais d'exécution). Tolérant : tout fichier absent/illisible
// est simplement ignoré. Les suggestions sont proposées à l'utilisateur, qui coche/ajuste.
import { existsSync, readFileSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import type { LaunchCommand } from '@arboretum/shared';
/** Taille max lue par fichier (garde-fou anti-fichier géant). */
const MAX_FILE_BYTES = 256 * 1024;
/** Noms de scripts npm activés par défaut (serveurs de dev longue durée) ; les autres sont proposés décochés. */
const DEFAULT_ENABLED_SCRIPT = /(^|:)(dev|start|serve|watch)(:|$)/i;
function readTextSafe(file: string): string | null {
try {
if (!existsSync(file)) return null;
// Lecture bornée : on tronque au-delà de MAX_FILE_BYTES (suffisant pour scripts / Procfile).
return readFileSync(file, 'utf8').slice(0, MAX_FILE_BYTES);
} catch {
return null;
}
}
/** Détecte le gestionnaire de paquets d'après le lockfile présent (défaut : npm). */
function detectRunner(dir: string): { cmd: string } {
if (existsSync(join(dir, 'pnpm-lock.yaml'))) return { cmd: 'pnpm run' };
if (existsSync(join(dir, 'yarn.lock'))) return { cmd: 'yarn' };
if (existsSync(join(dir, 'bun.lockb'))) return { cmd: 'bun run' };
return { cmd: 'npm run' };
}
function mk(label: string, run: string, enabled: boolean): LaunchCommand {
return { id: randomUUID(), label, run, enabled };
}
/** Scripts npm depuis package.json → `<runner> <script>`. */
function fromPackageJson(dir: string): LaunchCommand[] {
const raw = readTextSafe(join(dir, 'package.json'));
if (!raw) return [];
let scripts: Record<string, unknown> | undefined;
try {
const pkg = JSON.parse(raw) as { scripts?: Record<string, unknown> };
scripts = pkg.scripts;
} catch {
return [];
}
if (!scripts || typeof scripts !== 'object') return [];
const runner = detectRunner(dir);
return Object.keys(scripts)
.filter((name) => typeof scripts![name] === 'string')
.map((name) => mk(name, `${runner.cmd} ${name}`, DEFAULT_ENABLED_SCRIPT.test(name)));
}
/** Procfile (heroku/foreman) : lignes `name: command`. Toutes activées (ce sont des cibles d'exécution). */
function fromProcfile(dir: string): LaunchCommand[] {
const raw = readTextSafe(join(dir, 'Procfile'));
if (!raw) return [];
const out: LaunchCommand[] = [];
for (const line of raw.split(/\r?\n/)) {
const m = /^([A-Za-z0-9_-]+):\s*(.+)$/.exec(line.trim());
const name = m?.[1];
const cmd = m?.[2]?.trim();
if (name && cmd) out.push(mk(name, cmd, true));
}
return out;
}
/** docker-compose présent → suggestion `docker compose up` (énumération des services : évolution future). */
function fromDockerCompose(dir: string): LaunchCommand[] {
const names = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'];
const present = names.some((n) => existsSync(join(dir, n)));
return present ? [mk('docker', 'docker compose up', true)] : [];
}
/**
* Détecte des commandes de démarrage candidates dans `dir` (package.json, Procfile, docker-compose).
* Ne récurse pas et n'exécute rien. Renvoie [] si rien n'est détecté ou si `dir` est inaccessible.
*/
export function detectLaunchCommands(dir: string): LaunchCommand[] {
return [...fromPackageJson(dir), ...fromProcfile(dir), ...fromDockerCompose(dir)];
}
+33
View File
@@ -0,0 +1,33 @@
// Création d'un nouveau projet : un dossier `<root>/<name>` créé sous une racine existante, dans
// lequel on lance ensuite une session. Couche PURE (testable sans fs) : la création réelle du
// dossier, le `git init` et le spawn vivent dans `routes/projects.ts`.
import { join } from 'node:path';
import { isSafeAbsolutePath } from './git.js';
/**
* Valide un nom de projet : UN SEUL segment de dossier. Anti-traversal de base : refuse les noms
* vides, trop longs, `.`/`..`, et tout caractère de séparation (`/`, `\`) ou NUL. La résolution du
* chemin complet (et sa re-validation) est faite par {@link resolveProjectDir}.
*/
export function isSafeProjectName(name: string): boolean {
const n = name.trim();
if (n.length === 0 || n.length > 255) return false;
if (n === '.' || n === '..') return false;
return !/[/\\\0]/.test(n);
}
/**
* Résout le dossier de projet `<root>/<name>`. Suppose `root` déjà validé absolu et existant par
* l'appelant ; re-valide le chemin final via {@link isSafeAbsolutePath} (défense en profondeur).
* Lève si `name` est invalide ou si le chemin résultant échappe l'arborescence.
*/
export function resolveProjectDir(root: string, name: string): string {
if (!isSafeProjectName(name)) {
throw Object.assign(new Error(`Invalid project name: ${name}`), { statusCode: 400 });
}
const dir = join(root, name.trim());
if (!isSafeAbsolutePath(dir)) {
throw Object.assign(new Error(`Unsafe project path: ${dir}`), { statusCode: 400 });
}
return dir;
}

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