Compare commits
32 Commits
v2.0.0
...
desktop-v0
| Author | SHA1 | Date | |
|---|---|---|---|
| a7e04278fd | |||
| 7327407193 | |||
| 7a802e8920 | |||
| adc53b413e | |||
| 063f5e928b | |||
| 008e976e01 | |||
| 662c537ac4 | |||
| c694f9f2dd | |||
| e48798ebff | |||
| 1a74576955 | |||
| bd76e53570 | |||
| b0a75df204 | |||
| c7af406cbf | |||
| 8042376f9c | |||
| ef21b03d9c | |||
| 0532331795 | |||
| 1299b1b349 | |||
| ccbc1b9e4e | |||
| c9811fc0ca | |||
| 82682b0a37 | |||
| ae7ede6684 | |||
| de066abb54 | |||
| 4798732856 | |||
| d287c3c1d1 | |||
| 6741b2d47c | |||
| 5302bf29ae | |||
| f62404234b | |||
| c96d929c7a | |||
| 6acd4a16fd | |||
| cf60fa3a56 | |||
| 9a496abd00 | |||
| 65ef616867 |
@@ -43,7 +43,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 +56,12 @@ 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; }
|
||||
|| { 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: import bare '@arboretum/shared' encore présent dans le JS publié"
|
||||
grep -rn '@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 +82,20 @@ 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.
|
||||
# Exclusions : logo binaire + captures brutes du terminal (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 -nP '[\x{2014}\x{2013}]' -- . \
|
||||
':(exclude)brand/arboretum-logo-source.png' \
|
||||
':(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
|
||||
|
||||
87
.gitea/workflows/desktop-release.yml
Normal file
87
.gitea/workflows/desktop-release.yml
Normal file
@@ -0,0 +1,87 @@
|
||||
# Packaging de l'app de bureau Electron, déclenché UNIQUEMENT 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) est
|
||||
# automatisé ici ; Windows et macOS se buildent sur ces OS (voir packages/desktop/README.md) et
|
||||
# leurs artefacts sont attachés manuellement à la release.
|
||||
name: Desktop Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['desktop-v*']
|
||||
|
||||
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
|
||||
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
|
||||
# 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/latest-linux.yml
|
||||
# Best-effort : attache les installeurs (+ latest-linux.yml pour l'auto-update) à la release
|
||||
# Gitea du tag (crée la release si absente). Réutilise NPM_TOKEN (même token Gitea) : ce token
|
||||
# doit porter la portée write:repository en plus de write:package, sinon l'API release renvoie
|
||||
# un 403 (l'attache est ignorée, les installeurs restent disponibles en artefact du run).
|
||||
- name: Attach installers to Gitea release
|
||||
continue-on-error: true
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "::notice::NPM_TOKEN absent : installeurs disponibles 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/desktop/package.json').version")
|
||||
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 Desktop ${version}\"}" \
|
||||
"${api}/releases" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''")
|
||||
fi
|
||||
for f in packages/desktop/release/*.AppImage packages/desktop/release/*.deb packages/desktop/release/latest-linux.yml; do
|
||||
[ -f "$f" ] || continue
|
||||
name=$(basename "$f")
|
||||
# Re-run idempotent : supprimer un asset existant du même nom avant de ré-uploader, pour
|
||||
# que le dernier build gagne (l'API Gitea refuse sinon un asset déjà présent).
|
||||
existing=$(curl -fsSL -H "$auth" "${api}/releases/${rid}/assets" | node -e "const a=JSON.parse(require('fs').readFileSync(0,'utf8'));const m=Array.isArray(a)?a.find(x=>x.name===process.argv[1]):null;process.stdout.write(m?String(m.id):'')" "$name" || true)
|
||||
if [ -n "$existing" ]; then
|
||||
echo "replacing existing $name (asset $existing)"
|
||||
curl -fsSL -X DELETE -H "$auth" "${api}/releases/${rid}/assets/${existing}" || true
|
||||
fi
|
||||
echo "attaching $name"
|
||||
curl -fsSL -X POST -H "$auth" -F "attachment=@${f}" "${api}/releases/${rid}/assets?name=${name}"
|
||||
done
|
||||
echo "Installeurs Linux attachés à la release ${GITHUB_REF_NAME}."
|
||||
@@ -5,7 +5,7 @@ name: Release
|
||||
on:
|
||||
push:
|
||||
# `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.
|
||||
# : il stripperait alors `v` (→ `scode-v0.1.0`) et échouerait contre la version du daemon.
|
||||
tags: ['v[0-9]*']
|
||||
|
||||
permissions:
|
||||
@@ -39,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"
|
||||
@@ -53,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"
|
||||
|
||||
@@ -46,16 +46,17 @@ jobs:
|
||||
name: vsix
|
||||
path: packages/vscode/*.vsix
|
||||
# Best-effort : attache le VSIX à la release Gitea du tag (crée la release si absente).
|
||||
# Réutilise le secret NPM_TOKEN (même token Gitea que la publication du daemon — droits
|
||||
# repository suffisants pour l'API release). Sans lui, l'étape est ignorée sans faire échouer
|
||||
# le job (continue-on-error) ; le VSIX reste disponible en artefact.
|
||||
# Réutilise le secret NPM_TOKEN (même token Gitea que la publication du daemon) : ce token doit
|
||||
# porter write:repository en plus de write:package, sinon l'API release renvoie un 403. Sans
|
||||
# token, l'étape est ignorée sans faire échouer le job (continue-on-error) ; le VSIX reste
|
||||
# disponible en artefact.
|
||||
- name: Attach VSIX to Gitea release
|
||||
continue-on-error: true
|
||||
env:
|
||||
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
if [ -z "$RELEASE_TOKEN" ]; then
|
||||
echo "::notice::NPM_TOKEN absent — VSIX disponible en artefact uniquement."
|
||||
echo "::notice::NPM_TOKEN absent : VSIX disponible en artefact uniquement."
|
||||
exit 0
|
||||
fi
|
||||
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -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/
|
||||
|
||||
136
README.fr.md
136
README.fr.md
@@ -3,16 +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 worktree** : un espace de travail dans le navigateur (arbre de fichiers, éditeur Monaco, diffs inline, terminal intégré), un statut git détaillé adossé à un watcher de système de fichiers en temps réel, le staging sélectif / discard / amend / fetch / pull, l'archivage automatique des sessions, la synchronisation des réglages en temps réel entre navigateurs, et des services git distants chiffrés (GitHub / GitLab / Gitea) avec clone HTTPS.
|
||||
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>
|
||||
|
||||
---
|
||||
|
||||
@@ -26,43 +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.
|
||||
- **IDE worktree** — ouvrez n'importe quel worktree dans un espace de travail complet, dans le navigateur : un arbre de fichiers, un éditeur Monaco, un visualiseur de diff par fichier et le terminal de la session du worktree, côte à côte. Éditez les fichiers, indexez les changements sélectivement, committez (ou amendez), fetch/pull et push — sans quitter le dashboard. Un watcher de système de fichiers en temps réel garde la vue à jour au fil des éditions de l'agent.
|
||||
- **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).
|
||||
- **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
|
||||
@@ -72,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>
|
||||
@@ -80,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
|
||||
@@ -91,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
|
||||
@@ -102,48 +119,59 @@ 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.
|
||||
|
||||
## 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.
|
||||
|
||||
## Espace de travail & opérations git
|
||||
## L'IDE, espace de travail & opérations git
|
||||
|
||||
Au-delà de la supervision, Arboretum vous laisse vraiment *travailler* sur un worktree depuis le navigateur. Ouvrez l'**espace de travail** d'un worktree (`/workspace`) pour une vue façon IDE, en trois panneaux :
|
||||
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 fichiers & éditeur.** Parcourez le worktree, ouvrez un fichier dans un **éditeur Monaco** (coloration syntaxique, détection du langage), éditez-le et enregistrez-le. Les fichiers binaires et trop volumineux sont gérés proprement.
|
||||
- **Diffs par fichier.** Un visualiseur de diff unifié montre exactement ce qui a changé, ligne par ligne, pour l'arbre de travail ou l'index — ajouts et suppressions colorés, avec un refus de rendre les diffs binaires ou énormes.
|
||||
- **Staging sélectif & commit.** Indexez ou désindexez des fichiers individuels, jetez les changements non voulus, écrivez un message et **committez** — soit tout (`git add -A`), soit uniquement ce qui est indexé. **Amendez** le dernier commit (refusé une fois poussé), puis **fetch**, **pull** (fast-forward ou rebase) et **push**.
|
||||
- **Statut git détaillé.** Chaque worktree rapporte ses compteurs indexés / non indexés / conflits et son dernier commit, tenus à jour par un **watcher de système de fichiers en temps réel** : le diff et les compteurs s'actualisent dès qu'une session Claude touche un fichier.
|
||||
- **Terminal intégré.** Le terminal de la session Claude corrélée au worktree est juste à côté de l'éditeur, pour lire le diff et parler à l'agent au même endroit.
|
||||
- **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.
|
||||
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, **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.
|
||||
- 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.2.0.vsix
|
||||
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.3.0.vsix
|
||||
```
|
||||
|
||||
Puis installez-la via **Extensions : Installer à partir d'un VSIX…** (ou `code --install-extension git-arboretum-0.2.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-0.3.0.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
|
||||
@@ -162,7 +190,7 @@ Ouvrez `https://<machine>.<tailnet>.ts.net` depuis n'importe quel appareil de vo
|
||||
|
||||
## 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
|
||||
@@ -185,7 +213,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
|
||||
|
||||
@@ -210,7 +238,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
|
||||
|
||||
@@ -222,11 +250,11 @@ 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. |
|
||||
| `--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 :
|
||||
|
||||
@@ -239,14 +267,14 @@ Les options du daemon sont des flags CLI :
|
||||
|
||||
L'état (la base SQLite) vit dans `$XDG_DATA_HOME/arboretum` (par défaut `~/.local/share/arboretum`).
|
||||
|
||||
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.
|
||||
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 ».
|
||||
- **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é
|
||||
@@ -254,12 +282,12 @@ Arboretum peut se connecter à vos fournisseurs d'hébergement git pour parcouri
|
||||
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é.
|
||||
|
||||
@@ -270,7 +298,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 | ❌ |
|
||||
|
||||
@@ -278,11 +306,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)
|
||||
@@ -318,4 +346,4 @@ Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner
|
||||
|
||||
## Licence
|
||||
|
||||
MIT — voir [LICENSE](LICENSE).
|
||||
MIT, voir [LICENSE](LICENSE).
|
||||
|
||||
136
README.md
136
README.md
@@ -3,16 +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 **worktree IDE**: an in-browser workspace (file tree, Monaco editor, inline diffs, integrated terminal), detailed git status backed by a real-time file-system watcher, selective staging / discard / amend / fetch / pull, automatic session archival, real-time settings sync across browsers, and encrypted remote git services (GitHub / GitLab / Gitea) with HTTPS clone.
|
||||
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>
|
||||
|
||||
---
|
||||
|
||||
@@ -26,43 +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.
|
||||
- **Worktree IDE** — open any worktree in a full in-browser workspace: a file tree, a Monaco editor, an inline per-file diff viewer and the worktree's session terminal, side by side. Edit files, stage changes selectively, commit (or amend), fetch/pull and push — all without leaving the dashboard. A real-time file-system watcher keeps the view live as the agent edits.
|
||||
- **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).
|
||||
- **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
|
||||
@@ -72,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>
|
||||
@@ -80,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
|
||||
@@ -91,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
|
||||
@@ -102,48 +119,59 @@ 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.
|
||||
|
||||
## 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.
|
||||
|
||||
## Workspace & git operations
|
||||
## The IDE, workspace & git operations
|
||||
|
||||
Beyond supervising, Arboretum lets you actually *work* on a worktree from the browser. Open any worktree's **workspace** (`/workspace`) for an IDE-like, three-pane view:
|
||||
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:
|
||||
|
||||
- **File tree & editor.** Browse the worktree, open a file in a **Monaco editor** (syntax highlighting, language detection), edit and save it. Binary and oversized files are handled gracefully.
|
||||
- **Per-file diffs.** A unified diff viewer shows exactly what changed, line by line, for the working tree or the index — additions and deletions colour-coded, with a refusal to render binary or huge diffs.
|
||||
- **Selective staging & commit.** Stage or unstage individual files, discard changes you don't want, write a message and **commit** — either everything (`git add -A`) or just what's staged. **Amend** the last commit (refused once it's been pushed), then **fetch**, **pull** (fast-forward or rebase) and **push**.
|
||||
- **Detailed git status.** Every worktree reports staged / unstaged / conflict counts and its last commit, kept current by a **real-time file-system watcher** so the diff and counts update the moment a Claude session touches a file.
|
||||
- **Integrated terminal.** The worktree's correlated Claude session terminal sits right next to the editor, so you can read the diff and talk to the agent in one place.
|
||||
- **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.
|
||||
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, **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.
|
||||
- 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.2.0.vsix
|
||||
cd packages/vscode && npx @vscode/vsce package --no-dependencies # → git-arboretum-0.3.0.vsix
|
||||
```
|
||||
|
||||
Then install it via **Extensions: Install from VSIX…** (or `code --install-extension git-arboretum-0.2.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-0.3.0.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
|
||||
@@ -162,7 +190,7 @@ Open `https://<machine>.<tailnet>.ts.net` from any device on your tailnet. **Web
|
||||
|
||||
## 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
|
||||
@@ -185,7 +213,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
|
||||
|
||||
@@ -210,7 +238,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
|
||||
|
||||
@@ -222,11 +250,11 @@ 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. |
|
||||
| `--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:
|
||||
|
||||
@@ -239,14 +267,14 @@ Daemon options are CLI flags:
|
||||
|
||||
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum` (default `~/.local/share/arboretum`).
|
||||
|
||||
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.
|
||||
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.
|
||||
- **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
|
||||
@@ -254,12 +282,12 @@ Arboretum can connect to your git hosting providers so you can browse and clone
|
||||
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.
|
||||
|
||||
@@ -270,7 +298,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 | ❌ |
|
||||
|
||||
@@ -278,11 +306,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)
|
||||
@@ -318,4 +346,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).
|
||||
|
||||
10
SECURITY.md
10
SECURITY.md
@@ -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,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
|
||||
|
||||
|
||||
@@ -5,11 +5,11 @@ 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)
|
||||
@@ -24,7 +24,7 @@ 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 >_
|
||||
|
||||
BIN
brand/screenshot-ide-dark.png
Normal file
BIN
brand/screenshot-ide-dark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 113 KiB |
BIN
brand/screenshot-ide-light.png
Normal file
BIN
brand/screenshot-ide-light.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 113 KiB |
@@ -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.
|
||||
|
||||
36
package-lock.json
generated
36
package-lock.json
generated
@@ -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"
|
||||
@@ -7920,7 +7933,7 @@
|
||||
},
|
||||
"packages/server": {
|
||||
"name": "@johanleroy/git-arboretum",
|
||||
"version": "2.0.0",
|
||||
"version": "3.3.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.0.0",
|
||||
@@ -7954,13 +7967,14 @@
|
||||
},
|
||||
"packages/site": {
|
||||
"name": "@arboretum/site",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.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",
|
||||
@@ -8049,7 +8063,7 @@
|
||||
},
|
||||
"packages/vscode": {
|
||||
"name": "git-arboretum",
|
||||
"version": "0.2.0",
|
||||
"version": "0.4.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@arboretum/shared": "0.1.0",
|
||||
@@ -8500,6 +8514,8 @@
|
||||
"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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
4
packages/desktop/.gitignore
vendored
Normal file
4
packages/desktop/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
build/
|
||||
release/
|
||||
79
packages/desktop/README.md
Normal file
79
packages/desktop/README.md
Normal file
@@ -0,0 +1,79 @@
|
||||
# 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 gets `SIGTERM` (then `SIGKILL` after a grace delay).
|
||||
|
||||
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
|
||||
|
||||
Build on a Windows host (recommended): the `node-pty` win32 native binary and the installer
|
||||
(`makensis`) are most reliable there. Cross-building from Linux via Wine is a best-effort fallback.
|
||||
The app uses ConPTY (Windows 10 1809+). The installer is not code-signed yet, so SmartScreen shows
|
||||
"unknown publisher": choose "More info" then "Run anyway".
|
||||
|
||||
### macOS (best-effort)
|
||||
|
||||
Build on a Mac (`dmg`/`zip` cannot be produced elsewhere). The app is **not** signed or notarized,
|
||||
so Gatekeeper blocks the first launch: right-click the app then "Open", or run
|
||||
`xattr -dr com.apple.quarantine /Applications/Arboretum.app`.
|
||||
|
||||
## Auto-update
|
||||
|
||||
electron-builder emits `latest*.yml` next to the artifacts; `electron-updater` (wired in a later
|
||||
change) points at the Gitea release assets. Auto-update works for Windows (NSIS) and Linux
|
||||
(AppImage); macOS updates are manual while the app is unsigned.
|
||||
|
||||
## Icon
|
||||
|
||||
`resources/icon.png` (square, >= 512px) is the single source; electron-builder derives every
|
||||
platform icon from it.
|
||||
70
packages/desktop/electron-builder.yml
Normal file
70
packages/desktop/electron-builder.yml
Normal file
@@ -0,0 +1,70 @@
|
||||
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
|
||||
|
||||
# Icône : electron-builder dérive toutes les tailles/formats par OS depuis resources/icon.png
|
||||
# (buildResources), pas besoin de .ico/.icns séparés.
|
||||
linux:
|
||||
target: [AppImage, deb]
|
||||
category: Development
|
||||
artifactName: ${productName}-${version}-${arch}.${ext}
|
||||
# Entrée .desktop (forme plate, mergée telle quelle par electron-builder 25). StartupWMClass DOIT
|
||||
# correspondre à l'app_id runtime (posé par app.setName('Arboretum') dans src/main/main.ts) pour
|
||||
# que GNOME/Wayland associe la fenêtre au lanceur et affiche le logo. Redondant avec le défaut
|
||||
# (productName) mais explicite et robuste à un futur changement de productName.
|
||||
desktop:
|
||||
StartupWMClass: Arboretum
|
||||
# Note : le .deb installe l'icône et rafraîchit le cache (postinst electron-builder). L'AppImage,
|
||||
# lui, n'installe aucun .desktop sans intégration (appimaged) : sur Debian, préférer le .deb.
|
||||
|
||||
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>
|
||||
|
||||
win:
|
||||
target:
|
||||
- target: nsis
|
||||
arch: [x64]
|
||||
- target: portable
|
||||
arch: [x64]
|
||||
artifactName: ${productName}-${version}-${arch}.${ext}
|
||||
|
||||
nsis:
|
||||
oneClick: false
|
||||
perMachine: false
|
||||
allowToChangeInstallationDirectory: true
|
||||
|
||||
mac:
|
||||
target: [dmg, zip]
|
||||
category: public.app-category.developer-tools
|
||||
# macOS best-effort : non signe (documente : clic droit -> Ouvrir, ou xattr -dr com.apple.quarantine)
|
||||
identity: null
|
||||
hardenedRuntime: false
|
||||
|
||||
# Auto-update (electron-updater, cable en C5) : provider generic pointant sur les assets de release
|
||||
# Gitea. Genere latest*.yml a cote des artefacts.
|
||||
publish:
|
||||
provider: generic
|
||||
url: https://git.lidge.fr/johanleroy/arboretum/releases/download/desktop-latest
|
||||
24
packages/desktop/esbuild.mjs
Normal file
24
packages/desktop/esbuild.mjs
Normal 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
packages/desktop/package-lock.json
generated
Normal file
5836
packages/desktop/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
32
packages/desktop/package.json
Normal file
32
packages/desktop/package.json
Normal file
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@arboretum/desktop",
|
||||
"private": true,
|
||||
"version": "0.1.3",
|
||||
"description": "Arboretum desktop app: Electron shell that runs the daemon and shows its web UI",
|
||||
"homepage": "https://git-arboretum.com",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
BIN
packages/desktop/resources/icon.png
Normal file
BIN
packages/desktop/resources/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 184 KiB |
49
packages/desktop/scripts/fetch-node.mjs
Normal file
49
packages/desktop/scripts/fetch-node.mjs
Normal file
@@ -0,0 +1,49 @@
|
||||
// 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 { mkdirSync, rmSync, 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);
|
||||
if (ext === 'zip') execFileSync('unzip', ['-q', archive, '-d', BUILD], { stdio: 'inherit' });
|
||||
else execFileSync('tar', ['-xJf', archive, '-C', BUILD], { stdio: 'inherit' });
|
||||
// aplatir node-vX-os-arch/ -> build/node/
|
||||
execFileSync('bash', ['-c', `cp -R "${join(BUILD, name)}/." "${NODE_DIR}/" && rm -rf "${join(BUILD, name)}" "${archive}"`], { stdio: 'inherit' });
|
||||
|
||||
console.log(`fetch-node: Node ${NODE_VERSION} (${OS}-${arch}) -> build/node`);
|
||||
56
packages/desktop/scripts/prepare-server.mjs
Normal file
56
packages/desktop/scripts/prepare-server.mjs
Normal file
@@ -0,0 +1,56 @@
|
||||
// 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');
|
||||
|
||||
const run = (cmd, cmdArgs, cwd, env) =>
|
||||
execFileSync(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'})` : ''}`);
|
||||
16
packages/desktop/src/main/auth.ts
Normal file
16
packages/desktop/src/main/auth.ts
Normal 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
packages/desktop/src/main/autostart.ts
Normal file
44
packages/desktop/src/main/autostart.ts
Normal 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 });
|
||||
}
|
||||
90
packages/desktop/src/main/daemon.ts
Normal file
90
packages/desktop/src/main/daemon.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { resolveNodeBin, resolveServerEntry } from './paths';
|
||||
import { buildChildEnv } from './env';
|
||||
|
||||
export interface DaemonHandle {
|
||||
url: string;
|
||||
token: string;
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
interface Handshake {
|
||||
token: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export function startDaemon(opts: {
|
||||
dataDir: string;
|
||||
port: number;
|
||||
onLog?: (line: string) => void;
|
||||
onExit?: (code: number | null) => void;
|
||||
}): Promise<DaemonHandle> {
|
||||
const node = resolveNodeBin();
|
||||
const entry = resolveServerEntry();
|
||||
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'],
|
||||
});
|
||||
|
||||
child.stdout?.on('data', (d: Buffer) => opts.onLog?.(d.toString()));
|
||||
child.stderr?.on('data', (d: Buffer) => opts.onLog?.(d.toString()));
|
||||
|
||||
let stopped = false;
|
||||
const stop = (): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
if (stopped || child.exitCode !== null) return resolve();
|
||||
stopped = true;
|
||||
const killTimer = setTimeout(() => child.kill('SIGKILL'), 3000);
|
||||
child.once('exit', () => {
|
||||
clearTimeout(killTimer);
|
||||
resolve();
|
||||
});
|
||||
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 Error('daemon handshake timeout'));
|
||||
}, 30000);
|
||||
|
||||
child.once('exit', (code) => {
|
||||
opts.onExit?.(code);
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
reject(new Error(`daemon exited before handshake (code ${code ?? 'null'})`));
|
||||
}
|
||||
});
|
||||
|
||||
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, stop });
|
||||
} catch (err) {
|
||||
void stop();
|
||||
reject(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
15
packages/desktop/src/main/env.ts
Normal file
15
packages/desktop/src/main/env.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
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 };
|
||||
if (process.platform !== 'win32') {
|
||||
const extras = ['/usr/local/bin', '/opt/homebrew/bin', join(homedir(), '.local', 'bin'), '/usr/bin', '/bin'];
|
||||
const current = env.PATH ? env.PATH.split(delimiter) : [];
|
||||
env.PATH = [...new Set([...extras, ...current])].join(delimiter);
|
||||
}
|
||||
return env;
|
||||
}
|
||||
137
packages/desktop/src/main/main.ts
Normal file
137
packages/desktop/src/main/main.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { app, BrowserWindow, session, shell, type BrowserWindowConstructorOptions, type Tray } from 'electron';
|
||||
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 { initUpdater } from './updater';
|
||||
import { resolveIconPath } from './paths';
|
||||
|
||||
// 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 PORT = 7317;
|
||||
|
||||
let daemon: DaemonHandle | null = null;
|
||||
let win: BrowserWindow | null = null;
|
||||
let tray: Tray | null = null;
|
||||
let isQuitting = false;
|
||||
let shuttingDown = false;
|
||||
|
||||
// Instance unique : deux instances = deux daemons/ports en conflit.
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
} else {
|
||||
app.on('second-instance', showWindow);
|
||||
app.whenReady().then(bootstrap).catch((err: unknown) => {
|
||||
console.error('[arboretum-desktop] bootstrap failed:', err);
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const dataDir = join(app.getPath('userData'), 'daemon');
|
||||
daemon = await startDaemon({ dataDir, port: PORT, onLog: (l) => process.stdout.write(l) });
|
||||
await seedSessionCookie(PARTITION, daemon.url, daemon.token);
|
||||
createWindow(daemon.url);
|
||||
tray = createTray({ show: showWindow, quit: quitApp });
|
||||
initUpdater();
|
||||
}
|
||||
|
||||
function showWindow(): void {
|
||||
if (!win) return;
|
||||
if (win.isMinimized()) win.restore();
|
||||
win.show();
|
||||
win.focus();
|
||||
}
|
||||
|
||||
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;
|
||||
tray?.destroy();
|
||||
tray = null;
|
||||
app.quit();
|
||||
}
|
||||
}
|
||||
35
packages/desktop/src/main/paths.ts
Normal file
35
packages/desktop/src/main/paths.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { app } from 'electron';
|
||||
import { join } from 'node:path';
|
||||
|
||||
// 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');
|
||||
}
|
||||
|
||||
/** 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';
|
||||
}
|
||||
34
packages/desktop/src/main/tray.ts
Normal file
34
packages/desktop/src/main/tray.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { Menu, Tray, nativeImage } from 'electron';
|
||||
import { isAutoStartEnabled, setAutoStart } from './autostart';
|
||||
import { resolveIconPath } from './paths';
|
||||
|
||||
/** Icône de barre système : ouvrir la fenêtre, basculer le lancement au login, quitter. */
|
||||
export function createTray(opts: { show: () => void; quit: () => void }): Tray {
|
||||
const image = nativeImage.createFromPath(resolveIconPath());
|
||||
const tray = new Tray(image.isEmpty() ? nativeImage.createEmpty() : image.resize({ width: 18, height: 18 }));
|
||||
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
packages/desktop/src/main/updater.ts
Normal file
13
packages/desktop/src/main/updater.ts
Normal 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 */
|
||||
});
|
||||
}
|
||||
34
packages/desktop/src/main/window-state.ts
Normal file
34
packages/desktop/src/main/window-state.ts
Normal 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 */
|
||||
}
|
||||
}
|
||||
7
packages/desktop/src/preload/preload.ts
Normal file
7
packages/desktop/src/preload/preload.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { contextBridge } from 'electron';
|
||||
|
||||
// Preload minimal (sandbox activé) : expose seulement un marqueur permettant à la SPA de détecter
|
||||
// qu'elle tourne dans l'app de bureau. Aucun accès Node/fs exposé au renderer.
|
||||
contextBridge.exposeInMainWorld('arboretumDesktop', {
|
||||
isDesktop: true,
|
||||
});
|
||||
17
packages/desktop/tsconfig.json
Normal file
17
packages/desktop/tsconfig.json
Normal 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"]
|
||||
}
|
||||
33
packages/server/CHANGELOG.md
Normal file
33
packages/server/CHANGELOG.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Changelog
|
||||
|
||||
Notable changes to `@johanleroy/git-arboretum` (the Arboretum daemon). The VS Code
|
||||
extension keeps its own changelog in `packages/vscode/CHANGELOG.md`.
|
||||
|
||||
## 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.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@johanleroy/git-arboretum",
|
||||
"version": "2.0.0",
|
||||
"version": "3.3.0",
|
||||
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
||||
@@ -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-'));
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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.
|
||||
// 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';
|
||||
@@ -23,7 +23,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-p10-'));
|
||||
|
||||
@@ -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-p11-'));
|
||||
|
||||
@@ -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-p12-'));
|
||||
|
||||
202
packages/server/scripts/acceptance-p13.mjs
Normal file
202
packages/server/scripts/acceptance-p13.mjs
Normal 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);
|
||||
}
|
||||
@@ -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-'));
|
||||
|
||||
@@ -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,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-'));
|
||||
|
||||
@@ -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-'));
|
||||
|
||||
@@ -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-p7-'));
|
||||
|
||||
@@ -16,7 +16,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-p8-'));
|
||||
|
||||
@@ -16,7 +16,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-p9-'));
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
||||
projectsDir: config.claudeProjectsDir,
|
||||
sessionsDir: config.claudeSessionsDir,
|
||||
});
|
||||
// Archivage auto des sessions terminées (P10). Démarré dans runDaemon() — jamais ici (tests).
|
||||
// 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).
|
||||
@@ -112,9 +112,9 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
||||
// 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'.
|
||||
// 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.
|
||||
// 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);
|
||||
|
||||
@@ -176,7 +176,7 @@ 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');
|
||||
@@ -195,7 +195,7 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
||||
registerAuthRoutes(app, auth, limiter, serverVersion, db);
|
||||
registerSessionRoutes(app, manager, discovery, sessionArchive, db);
|
||||
registerProjectRoutes(app, manager, db);
|
||||
registerRepoRoutes(app, worktrees, db);
|
||||
registerRepoRoutes(app, worktrees, db, manager);
|
||||
registerGroupRoutes(app, groups, db, worktrees, manager);
|
||||
registerWorktreeRoutes(app, worktrees, db);
|
||||
registerGitRoutes(app, worktrees, db);
|
||||
@@ -207,12 +207,12 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
||||
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, 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 });
|
||||
|
||||
@@ -131,7 +131,7 @@ export function renderSystemdUnit(input: { exec: string; scriptArgs: string[]; p
|
||||
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
|
||||
|
||||
@@ -195,14 +195,14 @@ ${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)
|
||||
@@ -218,7 +218,7 @@ 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)
|
||||
--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
|
||||
@@ -257,7 +257,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();
|
||||
}
|
||||
@@ -294,7 +294,7 @@ 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`);
|
||||
|
||||
@@ -15,7 +15,7 @@ export interface Config {
|
||||
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). */
|
||||
/** ~/.claude/projects (transcripts JSONL) : surchargeable via --claude-home (tests). */
|
||||
claudeProjectsDir: string;
|
||||
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
|
||||
claudeSessionsDir: string;
|
||||
@@ -35,11 +35,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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -15,6 +15,13 @@ export interface SpawnOptions {
|
||||
addDirs?: string[];
|
||||
/** chemin explicite du binaire `claude` (réglage UI) ; sinon résolution via PATH (`which`). */
|
||||
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;
|
||||
}
|
||||
|
||||
/** Diagnostic de résolution du binaire `claude` (exposé en lecture dans Réglages). */
|
||||
@@ -49,7 +56,7 @@ function isExecutable(path: string): boolean {
|
||||
|
||||
/**
|
||||
* Résout le binaire `claude`. Si `configuredPath` est fourni (réglage UI), il est utilisé tel quel
|
||||
* — validé exécutable, message clair sinon — et JAMAIS mis en cache (modifiable à chaud). Sinon :
|
||||
* (validé exécutable, message clair sinon) et JAMAIS mis en cache (modifiable à chaud). Sinon :
|
||||
* `which claude`, mis en cache. Un service systemd/launchd démarre avec un PATH minimal sans
|
||||
* ~/.local/bin → `which claude` y échoue ; d'où le réglage de chemin explicite (et le PATH figé par
|
||||
* `arboretum install`).
|
||||
@@ -81,6 +88,20 @@ export function diagnoseClaudeBin(configuredPath?: string | null): ClaudeBinDiag
|
||||
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 de login pour « Démarrer le projet » : `$SHELL` s'il est un shell interactif connu
|
||||
* (bash/zsh/fish), sinon fallback `bash`. Évite qu'un `$SHELL` exotique (dash…) sorte aussitôt
|
||||
* avec `-l -i` et laisse un terminal vide.
|
||||
*/
|
||||
function loginShell(): string {
|
||||
const shell = process.env.SHELL;
|
||||
if (shell && KNOWN_LOGIN_SHELLS.has(shell.split('/').pop() ?? '')) return shell;
|
||||
return 'bash';
|
||||
}
|
||||
|
||||
/** Module volontairement abstrait : le plan B « BYO API key / Agent SDK » se brancherait ici. */
|
||||
export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
@@ -89,11 +110,18 @@ export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
||||
COLORTERM: 'truecolor',
|
||||
};
|
||||
if (opts.command === 'bash') {
|
||||
// Lancement de projet : shell de login interactif de l'utilisateur (charge PATH/nvm/asdf).
|
||||
// `-l` (login) exécute les profils, `-i` (interactif) reste attaché après la commande auto-tapée.
|
||||
// On n'utilise `$SHELL` que s'il fait partie des shells interactifs connus supportant `-l -i`
|
||||
// (bash/zsh/fish) ; sinon fallback bash (ex. `$SHELL=dash` sortirait avec `-l -i`).
|
||||
if (opts.login) {
|
||||
return { file: loginShell(), args: ['-l', '-i'], env };
|
||||
}
|
||||
return { file: 'bash', args: ['--norc'], env };
|
||||
}
|
||||
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');
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -23,7 +23,7 @@ interface WatchEntry {
|
||||
refCount: number;
|
||||
/** nombre de sessions vivantes épinglant ce worktree. */
|
||||
sessionPins: number;
|
||||
/** épingle « permanente » (checkout principal d'un repo enregistré) — jamais évincée (P11). */
|
||||
/** épingle « permanente » (checkout principal d'un repo enregistré) : jamais évincée (P11). */
|
||||
repoPins: number;
|
||||
lastUsed: number;
|
||||
debounce: NodeJS.Timeout | null;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Clients des services git distants (Gitea / GitLab / GitHub) — P12. Uniquement `fetch` global
|
||||
// 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';
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// 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.
|
||||
// getSecret()/authFor() sont INTERNES (clone, listRepos, test) : jamais routés.
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type {
|
||||
CreateGitCredentialRequest,
|
||||
@@ -137,7 +137,7 @@ export class GitCredentialsManager {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Secret déchiffré — INTERNE (clone/listRepos/test). Jamais exposé par une route. */
|
||||
/** 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;
|
||||
|
||||
@@ -199,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[] = [];
|
||||
@@ -476,7 +476,7 @@ 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. */
|
||||
/** `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);
|
||||
@@ -532,7 +532,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,
|
||||
@@ -583,7 +583,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).
|
||||
@@ -610,13 +610,13 @@ const GIT_CLONE_TIMEOUT_MS = 10 * 60_000; // 10 min : un clone réseau peut êtr
|
||||
|
||||
export interface CloneProgress {
|
||||
phase: string;
|
||||
/** pourcentage 0–100 si git le rapporte, sinon null. */
|
||||
/** 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.
|
||||
* 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: {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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
packages/server/src/core/launch-detect.ts
Normal file
83
packages/server/src/core/launch-detect.ts
Normal 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)];
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
// 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
|
||||
// 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
|
||||
* 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}.
|
||||
*/
|
||||
|
||||
@@ -40,8 +40,29 @@ type HistoricalRow = {
|
||||
added_dirs: string | null;
|
||||
group_id: string | null;
|
||||
archived_at: string | null;
|
||||
launch_run_id: string | null;
|
||||
};
|
||||
|
||||
/** Longueur max d'une commande auto-tapée (garde-fou ; une ligne shell raisonnable). */
|
||||
const MAX_INITIAL_INPUT_LEN = 4096;
|
||||
|
||||
/**
|
||||
* Assainit une commande de lancement avant de l'écrire dans le PTY : trim, borne de longueur,
|
||||
* retrait de tous les caractères de contrôle (dont retours chariot/ligne : le `\r` de soumission
|
||||
* est ajouté par l'appelant). Empêche l'injection de plusieurs lignes / séquences de contrôle par
|
||||
* le champ de commande ; le modèle de menace reste inchangé (terminal = RCE par conception).
|
||||
*/
|
||||
function sanitizeInitialInput(raw: string): string {
|
||||
let out = '';
|
||||
for (const ch of raw.slice(0, MAX_INITIAL_INPUT_LEN)) {
|
||||
const code = ch.codePointAt(0) ?? 0;
|
||||
// saute les caractères de contrôle C0 (0x00-0x1F) et DEL (0x7F) : ni multi-lignes ni séquences ANSI.
|
||||
if (code < 0x20 || code === 0x7f) continue;
|
||||
out += ch;
|
||||
}
|
||||
return out.trim();
|
||||
}
|
||||
|
||||
/** Parse la colonne `added_dirs` (JSON array de chemins) de façon défensive ; [] si NULL/invalide. */
|
||||
function parseAddedDirs(raw: string | null): string[] {
|
||||
if (!raw) return [];
|
||||
@@ -85,6 +106,8 @@ interface ManagedSession {
|
||||
addedDirs: string[];
|
||||
/** groupe propriétaire d'une session de groupe multi-repo ; null sinon (P6). */
|
||||
groupId: string | null;
|
||||
/** identifiant partagé par les terminaux d'un même « Démarrer le projet » ; null sinon. */
|
||||
launchRunId: string | null;
|
||||
/** détection d'état fin (busy/waiting/idle + dialogue) ; null pour bash (P3-B). */
|
||||
tracker: SessionActivityTracker | null;
|
||||
/** dernière activité notifiée (détection du front montant vers `waiting` pour le push P4-B). */
|
||||
@@ -117,6 +140,14 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
addDirs?: string[];
|
||||
/** groupe propriétaire (session de groupe, P6). */
|
||||
groupId?: string;
|
||||
/** shell de login interactif (charge le PATH utilisateur) : lancement de projet uniquement. */
|
||||
login?: boolean;
|
||||
/** commande auto-tapée dans le PTY juste après le spawn (« Démarrer le projet »). */
|
||||
initialInput?: string;
|
||||
/** titre initial de la session (libellé de l'onglet ; ex. label de commande de lancement). */
|
||||
title?: string;
|
||||
/** identifiant partagé par tous les terminaux d'un même lancement de projet. */
|
||||
launchRunId?: string;
|
||||
}): SessionSummary {
|
||||
const cwd = opts.cwd;
|
||||
if (!existsSync(cwd) || !statSync(cwd).isDirectory()) {
|
||||
@@ -129,7 +160,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
throw Object.assign(new Error(`Not a directory: ${dir}`), { statusCode: 400 });
|
||||
}
|
||||
}
|
||||
// Un resume/fork est toujours une session claude (le cwd d'origine est garanti par l'appelant — S1).
|
||||
// Un resume/fork est toujours une session claude (le cwd d'origine est garanti par l'appelant, S1).
|
||||
const command = opts.resume ? 'claude' : (opts.command ?? 'claude');
|
||||
// Override de chemin du binaire claude (réglage UI) lu à chaque spawn → effet sans redémarrage.
|
||||
const claudeBinPath = command === 'claude' ? readClaudeBinPath(this.db) : null;
|
||||
@@ -138,6 +169,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
...(claudeBinPath ? { claudeBinPath } : {}),
|
||||
...(opts.resume ? { resume: opts.resume } : {}),
|
||||
...(addedDirs.length ? { addDirs: addedDirs } : {}),
|
||||
...(opts.login ? { login: true } : {}),
|
||||
});
|
||||
const id = randomUUID();
|
||||
const proc = pty.spawn(spec.file, spec.args, {
|
||||
@@ -151,7 +183,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
id,
|
||||
cwd,
|
||||
command,
|
||||
title: null,
|
||||
title: opts.title ?? null,
|
||||
createdAt: new Date().toISOString(),
|
||||
proc,
|
||||
ring: new RingBuffer(RING_CAPACITY),
|
||||
@@ -162,6 +194,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
claudeSessionId: null,
|
||||
addedDirs,
|
||||
groupId: opts.groupId ?? null,
|
||||
launchRunId: opts.launchRunId ?? null,
|
||||
tracker: null,
|
||||
prevActivity: null,
|
||||
notifyTimer: null,
|
||||
@@ -177,19 +210,28 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
}
|
||||
this.live.set(id, session);
|
||||
this.db
|
||||
.prepare('INSERT INTO sessions (id, cwd, command, created_at, resumed_from, added_dirs, group_id) VALUES (?, ?, ?, ?, ?, ?, ?)')
|
||||
.prepare('INSERT INTO sessions (id, cwd, command, title, created_at, resumed_from, added_dirs, group_id, launch_run_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(
|
||||
id,
|
||||
cwd,
|
||||
command,
|
||||
session.title,
|
||||
session.createdAt,
|
||||
opts.resume?.claudeSessionId ?? null,
|
||||
addedDirs.length ? JSON.stringify(addedDirs) : null,
|
||||
session.groupId,
|
||||
session.launchRunId,
|
||||
);
|
||||
|
||||
proc.onData((data) => this.handleOutput(session, Buffer.from(data, 'utf8')));
|
||||
proc.onExit(({ exitCode, signal }) => this.handleExit(session, exitCode, signal ?? null));
|
||||
// Auto-type de la commande de lancement APRÈS onData : la commande et sa sortie entrent dans le
|
||||
// ring et sont rejouées à l'attach. Les octets sont mis en file par le tty tant que le shell
|
||||
// n'a pas commencé à lire → pas de course. Un seul `\r` final (aligné sur answer()).
|
||||
if (opts.initialInput) {
|
||||
const line = sanitizeInitialInput(opts.initialInput);
|
||||
if (line) proc.write(`${line}\r`);
|
||||
}
|
||||
if (command === 'claude') this.captureClaudeSessionId(session);
|
||||
|
||||
const summary = this.summarize(session);
|
||||
@@ -197,7 +239,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** Résout le claudeSessionId du CLI en pollant le registre par pid, puis le persiste (waitReady — S1). */
|
||||
/** Résout le claudeSessionId du CLI en pollant le registre par pid, puis le persiste (waitReady, S1). */
|
||||
private captureClaudeSessionId(s: ManagedSession): void {
|
||||
const deadline = Date.now() + CLAUDE_ID_TIMEOUT_MS;
|
||||
const tick = (): void => {
|
||||
@@ -269,7 +311,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
|
||||
const liveIds = new Set(this.live.keys());
|
||||
const rows = this.db
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at FROM sessions ORDER BY created_at DESC LIMIT 100')
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at, launch_run_id FROM sessions ORDER BY created_at DESC LIMIT 100')
|
||||
.all() as HistoricalRow[];
|
||||
const historical: SessionSummary[] = rows
|
||||
.filter((r) => !liveIds.has(r.id))
|
||||
@@ -302,19 +344,20 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
registryStatus: null,
|
||||
...(addedDirs.length ? { addedDirs } : {}),
|
||||
groupId: r.group_id,
|
||||
launchRunId: r.launch_run_id,
|
||||
archived: r.archived_at != null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Ré-émet un `session_update` pour une session historique (P10) — utilisé au dés-archivage pour
|
||||
* Ré-émet un `session_update` pour une session historique (P10) : utilisé au dés-archivage pour
|
||||
* que tous les clients rafraîchissent le row (le champ `archived` repasse à false). No-op si la
|
||||
* session est vivante (déjà couverte par le flux live) ou inconnue.
|
||||
*/
|
||||
emitHistoricalUpdate(id: string): void {
|
||||
if (this.live.has(id)) return;
|
||||
const r = this.db
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at FROM sessions WHERE id = ?')
|
||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id, archived_at, launch_run_id FROM sessions WHERE id = ?')
|
||||
.get(id) as HistoricalRow | undefined;
|
||||
if (!r) return;
|
||||
this.emit('session_update', this.historicalSummary(r));
|
||||
@@ -345,7 +388,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Arrêt du daemon : SIGTERM à toutes les sessions (le CLI nettoie son registre sur SIGTERM — spike S1). */
|
||||
/** Arrêt du daemon : SIGTERM à toutes les sessions (le CLI nettoie son registre sur SIGTERM, spike S1). */
|
||||
shutdown(): void {
|
||||
for (const id of this.live.keys()) this.kill(id);
|
||||
}
|
||||
@@ -396,7 +439,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
/**
|
||||
* Répond à un dialogue Claude sans clavier (P4-A) : traduit une intention de haut
|
||||
* niveau en keystrokes PTY, validée contre l'état fin du tracker (P3-B).
|
||||
* - 'select' N : positionne le curseur sur l'option N puis confirme (`"N\r"`) — protocole acté spike S3.
|
||||
* - 'select' N : positionne le curseur sur l'option N puis confirme (`"N\r"`) : protocole acté spike S3.
|
||||
* - 'confirm' : valide l'option pré-sélectionnée (`"\r"`).
|
||||
* - 'deny' : refus universel (Esc).
|
||||
* Réutilise le chemin write (mono-utilisateur : tout interactif peut répondre, observers non).
|
||||
@@ -417,7 +460,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
s.proc.write(`${optionN}\r`);
|
||||
return 'ok';
|
||||
}
|
||||
// confirm/deny n'exigent qu'un état d'attente (le dialogue Trust précède le registre — S1).
|
||||
// confirm/deny n'exigent qu'un état d'attente (le dialogue Trust précède le registre, S1).
|
||||
if (act?.activity !== 'waiting') return 'invalid';
|
||||
s.proc.write(action === 'deny' ? '\x1b' : '\r');
|
||||
return 'ok';
|
||||
@@ -446,10 +489,10 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
// ---- interne ----
|
||||
|
||||
/**
|
||||
* Push P4-B : notifie sur le FRONT MONTANT vers un état qui requiert l'attention — `waiting`
|
||||
* Push P4-B : notifie sur le FRONT MONTANT vers un état qui requiert l'attention : `waiting`
|
||||
* (un dialogue bloque) ou `idle` atteint depuis `busy` (Claude a terminé sa réponse, la session
|
||||
* redevient disponible). Le tracker réémet souvent le même état → on ne réagit qu'au changement.
|
||||
* Debounce annulable : un état ultra-bref (Claude repart tout seul) ne déclenche pas de notif —
|
||||
* Debounce annulable : un état ultra-bref (Claude repart tout seul) ne déclenche pas de notif :
|
||||
* à l'échéance on revérifie l'état réel. Cible tous les abonnements (un seul utilisateur).
|
||||
*/
|
||||
private maybeNotify(s: ManagedSession, next: SessionActivity | null): void {
|
||||
@@ -558,6 +601,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
||||
dialog: act?.dialog ?? null,
|
||||
...(s.addedDirs.length ? { addedDirs: s.addedDirs } : {}),
|
||||
groupId: s.groupId,
|
||||
launchRunId: s.launchRunId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { SecretBox } from './secret-box.js';
|
||||
import { recordAudit } from './audit-log.js';
|
||||
|
||||
// web-push est publié en CommonJS : on le charge via require (verbatimModuleSyntax + NodeNext),
|
||||
// typé par l'import type — même pattern que @xterm/headless dans screen-reader.ts.
|
||||
// typé par l'import type, même pattern que @xterm/headless dans screen-reader.ts.
|
||||
const require = createRequire(import.meta.url);
|
||||
const webpush = require('web-push') as typeof import('web-push');
|
||||
|
||||
@@ -33,7 +33,7 @@ interface SubRow {
|
||||
auth: string;
|
||||
}
|
||||
|
||||
/** Envoi d'une notif à un abonnement — injectable pour les tests ; défaut = web-push réel. */
|
||||
/** Envoi d'une notif à un abonnement : injectable pour les tests ; défaut = web-push réel. */
|
||||
export type PushSender = (
|
||||
subscription: { endpoint: string; keys: { p256dh: string; auth: string } },
|
||||
payload: string,
|
||||
@@ -70,7 +70,7 @@ export class PushService {
|
||||
this.vapidPrivate = priv;
|
||||
}
|
||||
|
||||
/** Clé publique VAPID — sûre à exposer (applicationServerKey côté navigateur). */
|
||||
/** Clé publique VAPID : sûre à exposer (applicationServerKey côté navigateur). */
|
||||
publicKey(): string {
|
||||
return this.vapidPublic;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Planificateur de la découverte auto des repos : scan au démarrage + re-scan périodique.
|
||||
// Calqué sur DiscoveryService (sessions) — start()/stop() avec timer .unref(). Démarré depuis
|
||||
// Calqué sur DiscoveryService (sessions) : start()/stop() avec timer .unref(). Démarré depuis
|
||||
// runDaemon() UNIQUEMENT (jamais buildApp), ce qui isole naturellement les tests vitest du scan.
|
||||
// Lui-même sans état : il lit les racines/l'intervalle dans `settings` et délègue à WorktreeManager.
|
||||
import type { Db } from '../db/index.js';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Découverte auto des dépôts git : marche bornée du système de fichiers à la recherche de `.git`.
|
||||
// Fonction PURE et tolérante (ne lève jamais) — testable isolément comme parseWorktreePorcelain.
|
||||
// Fonction PURE et tolérante (ne lève jamais) : testable isolément comme parseWorktreePorcelain.
|
||||
// N'appelle JAMAIS git (détection par présence de `.git`) : la validation réelle (isRepo) et la
|
||||
// résolution de default_branch se font paresseusement à l'enregistrement, pas par dépôt scanné.
|
||||
import { readdir } from 'node:fs/promises';
|
||||
@@ -39,7 +39,7 @@ interface Frame {
|
||||
* - un dossier contenant `.git` (fichier OU dossier → couvre les worktrees liés) est un repo :
|
||||
* on l'enregistre ; en profondeur on NE descend PAS dedans (sous-modules/worktrees imbriqués
|
||||
* ignorés). EXCEPTION : une racine fournie (depth 0) qui est elle-même un repo est aussi un
|
||||
* conteneur — on l'enregistre ET on continue de descendre pour trouver les repos internes ;
|
||||
* conteneur : on l'enregistre ET on continue de descendre pour trouver les repos internes ;
|
||||
* - on n'empile que les vrais sous-dossiers (`d.isDirectory()`), donc les symlinks ne sont PAS
|
||||
* suivis (anti-cycle + anti-sortie de racine), et on saute dotdirs + excludeDirs ;
|
||||
* - bornes : `maxDepth`, `maxRepos`, et un éventuel `signal` (timeout global) ;
|
||||
|
||||
@@ -50,7 +50,7 @@ export function normalizeScanRoots(raw: unknown): string[] | null {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Valide un intervalle (entier 0–MAX_SCAN_INTERVAL_MIN). Retourne null si invalide. */
|
||||
/** Valide un intervalle (entier 0-MAX_SCAN_INTERVAL_MIN). Retourne null si invalide. */
|
||||
export function normalizeScanIntervalMin(raw: unknown): number | null {
|
||||
if (typeof raw !== 'number' || !Number.isInteger(raw)) return null;
|
||||
if (raw < 0 || raw > MAX_SCAN_INTERVAL_MIN) return null;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Reconstruction d'écran via @xterm/headless : terminal headless PERSISTANT par session, alimenté
|
||||
// incrémentalement par le flux PTY. Remplace le strip ANSI naïf (qui « mange les espaces » et casse
|
||||
// la détection des dialogues — verdict S1/S3). Aucune dépendance DOM (usage Node).
|
||||
// la détection des dialogues, verdict S1/S3). Aucune dépendance DOM (usage Node).
|
||||
import { createRequire } from 'node:module';
|
||||
import type { Terminal as XtermTerminal } from '@xterm/headless';
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ export class SessionArchiveService extends EventEmitter<SessionArchiveEvents> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Diffuse l'archivage d'une session (déjà archivée + auditée par l'appelant — ex. route manuelle). */
|
||||
/** Diffuse l'archivage d'une session (déjà archivée + auditée par l'appelant, ex. route manuelle). */
|
||||
emitArchived(id: string, archivedAt: string): void {
|
||||
this.emit('session_archived', { id, archivedAt });
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { existsSync, realpathSync } from 'node:fs';
|
||||
import type {
|
||||
DiscoverReposResponse,
|
||||
HookRunResult,
|
||||
LaunchCommand,
|
||||
PostCreateHook,
|
||||
RepoSummary,
|
||||
SessionSummary,
|
||||
@@ -71,6 +72,8 @@ interface RepoRow {
|
||||
pre_trust: number;
|
||||
created_at: string;
|
||||
hidden: number;
|
||||
/** commandes de démarrage du projet (JSON array de LaunchCommand) ; '[]' par défaut. */
|
||||
launch_commands: string;
|
||||
}
|
||||
|
||||
export interface WorktreeManagerEvents {
|
||||
@@ -78,7 +81,7 @@ export interface WorktreeManagerEvents {
|
||||
repo_removed: [string];
|
||||
worktree_update: [{ repoId: string; worktree: WorktreeSummary }];
|
||||
worktree_removed: [{ repoId: string; path: string }];
|
||||
/** P7 — le détail (liste des changements/diff) d'un worktree regardé a changé ; relayé en push
|
||||
/** P7 : le détail (liste des changements/diff) d'un worktree regardé a changé ; relayé en push
|
||||
* ciblé `worktree_changes` aux seules connexions ayant `watch`é cette clé. */
|
||||
worktree_changes: [{ repoId: string; path: string }];
|
||||
}
|
||||
@@ -101,6 +104,28 @@ function parseHooks(json: string): PostCreateHook[] {
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse la colonne `launch_commands` (JSON array de LaunchCommand) de façon défensive ; [] si invalide. */
|
||||
function parseLaunchCommands(json: string): LaunchCommand[] {
|
||||
try {
|
||||
const arr = JSON.parse(json) as unknown;
|
||||
if (!Array.isArray(arr)) return [];
|
||||
return arr
|
||||
.filter(
|
||||
(c): c is LaunchCommand =>
|
||||
!!c && typeof c.id === 'string' && typeof c.label === 'string' && typeof c.run === 'string' && typeof c.enabled === 'boolean',
|
||||
)
|
||||
.map((c) => ({
|
||||
id: c.id,
|
||||
label: c.label,
|
||||
run: c.run,
|
||||
enabled: c.enabled,
|
||||
...(typeof c.cwd === 'string' && c.cwd.trim() !== '' ? { cwd: c.cwd } : {}),
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function runHook(cwd: string, hook: PostCreateHook): Promise<HookRunResult> {
|
||||
return new Promise((resolveP) => {
|
||||
const t0 = Date.now();
|
||||
@@ -136,7 +161,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
private readonly fsWatcher?: FsWatcherService,
|
||||
) {
|
||||
super();
|
||||
// P7 — un changement FS sur un worktree regardé invalide le cache, rediffuse le status frais
|
||||
// P7 : un changement FS sur un worktree regardé invalide le cache, rediffuse le status frais
|
||||
// (worktree_update : compteurs légers pour tout le dashboard) et signale aux clients qui le
|
||||
// regardent de re-fetcher le détail (worktree_changes ciblé). On résout repoId → row à la volée.
|
||||
this.fsWatcher?.on('worktree_fs_change', ({ repoId, path }) => {
|
||||
@@ -160,6 +185,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
label: row.label,
|
||||
defaultBranch: row.default_branch,
|
||||
postCreateHooks: parseHooks(row.post_create_hooks),
|
||||
launchCommands: parseLaunchCommands(row.launch_commands),
|
||||
preTrust: row.pre_trust === 1,
|
||||
createdAt: row.created_at,
|
||||
valid: await isRepo(row.path),
|
||||
@@ -167,12 +193,18 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
};
|
||||
}
|
||||
|
||||
/** Résumé d'un repo par id (null si inconnu). Sert notamment au lancement de projet. */
|
||||
async getRepo(id: string): Promise<RepoSummary | null> {
|
||||
const row = this.getRepoRow(id);
|
||||
return row ? this.rowToSummary(row) : null;
|
||||
}
|
||||
|
||||
async listRepos(): Promise<RepoSummary[]> {
|
||||
const rows = this.db.prepare('SELECT * FROM repos ORDER BY created_at ASC').all() as unknown as RepoRow[];
|
||||
return Promise.all(rows.map((r) => this.rowToSummary(r)));
|
||||
}
|
||||
|
||||
async addRepo(opts: { path: string; label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean }): Promise<RepoSummary> {
|
||||
async addRepo(opts: { path: string; label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; launchCommands?: LaunchCommand[] }): Promise<RepoSummary> {
|
||||
const path = opts.path;
|
||||
if (!isSafeAbsolutePath(path)) throw httpError(400, 'BAD_REQUEST', 'path must be an absolute, normalized path');
|
||||
if (!(await isRepo(path))) throw httpError(400, 'NOT_A_REPO', `Not a git repository root: ${path}`);
|
||||
@@ -187,11 +219,12 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
pre_trust: opts.preTrust ? 1 : 0,
|
||||
created_at: new Date().toISOString(),
|
||||
hidden: 0,
|
||||
launch_commands: JSON.stringify(opts.launchCommands ?? []),
|
||||
};
|
||||
try {
|
||||
this.db
|
||||
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at, row.hidden);
|
||||
.prepare('INSERT INTO repos (id, path, label, default_branch, post_create_hooks, pre_trust, created_at, hidden, launch_commands) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(row.id, row.path, row.label, row.default_branch, row.post_create_hooks, row.pre_trust, row.created_at, row.hidden, row.launch_commands);
|
||||
} catch (err) {
|
||||
// Course possible avec un scan concurrent qui aurait inséré le même path entre le SELECT
|
||||
// d'unicité et cet INSERT (contrainte UNIQUE sur path) → on rend le même 409 explicite.
|
||||
@@ -207,7 +240,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
}
|
||||
|
||||
/**
|
||||
* P11 — arme un watcher PERMANENT sur le checkout principal de chaque repo visible : un
|
||||
* P11 : arme un watcher PERMANENT sur le checkout principal de chaque repo visible : un
|
||||
* `git checkout`/`switch` en CLI sur le principal est ainsi rediffusé en temps réel sans qu'un
|
||||
* client ne l'ait « regardé ». Appelé depuis runDaemon (jamais buildApp → pas d'effet en tests purs).
|
||||
*/
|
||||
@@ -220,16 +253,17 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
this.fsWatcher?.pinRepo(row.id, resolve(row.path));
|
||||
}
|
||||
|
||||
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
|
||||
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean; launchCommands?: LaunchCommand[] }): Promise<RepoSummary> {
|
||||
const row = this.getRepoRow(id);
|
||||
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
|
||||
if (patch.postCreateHooks !== undefined) row.post_create_hooks = JSON.stringify(patch.postCreateHooks);
|
||||
if (patch.preTrust !== undefined) row.pre_trust = patch.preTrust ? 1 : 0;
|
||||
if (patch.hidden !== undefined) row.hidden = patch.hidden ? 1 : 0;
|
||||
if (patch.launchCommands !== undefined) row.launch_commands = JSON.stringify(patch.launchCommands);
|
||||
this.db
|
||||
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ?, hidden = ? WHERE id = ?')
|
||||
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
|
||||
.prepare('UPDATE repos SET label = ?, post_create_hooks = ?, pre_trust = ?, hidden = ?, launch_commands = ? WHERE id = ?')
|
||||
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, row.launch_commands, id);
|
||||
const summary = await this.rowToSummary(row);
|
||||
this.emit('repo_update', summary);
|
||||
// P11 : masqué → on libère le watcher permanent du principal ; ré-affiché → on le réarme.
|
||||
@@ -252,7 +286,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
|
||||
/**
|
||||
* Découvre les repos git sous `roots` et auto-enregistre les NOUVEAUX (path absent de la DB).
|
||||
* Idempotent et anti-résurrection : un path déjà présent — visible OU masqué — n'est jamais
|
||||
* Idempotent et anti-résurrection : un path déjà présent (visible OU masqué) n'est jamais
|
||||
* réécrit (INSERT ... ON CONFLICT DO NOTHING). Les scans concurrents sont coalescés. Tolérant :
|
||||
* ne lève pas (le scanner avale les erreurs FS). N'appelle aucun git pendant le scan
|
||||
* (default_branch=NULL, résolu paresseusement par rowToSummary à l'affichage).
|
||||
@@ -287,6 +321,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
pre_trust: 0,
|
||||
created_at: new Date().toISOString(),
|
||||
hidden: 0,
|
||||
launch_commands: '[]',
|
||||
};
|
||||
const res = insert.run(row.id, row.path, row.label, row.created_at);
|
||||
if (res.changes === 1) {
|
||||
@@ -302,7 +337,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
|
||||
/**
|
||||
* Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree.
|
||||
* Les sessions explicitement masquées (`hidden`) sont exclues — cohérent avec `/api/v1/sessions`
|
||||
* Les sessions explicitement masquées (`hidden`) sont exclues, cohérent avec `/api/v1/sessions`
|
||||
* (sans quoi le masquage était ignoré dans les fiches worktree). Le tri managées/externes est laissé
|
||||
* au client (interrupteur « afficher les externes »), qui dispose du champ `source`. La garde de
|
||||
* suppression réclame en revanche TOUTES les sessions vivantes (`includeHidden`) pour rester sûre.
|
||||
@@ -351,7 +386,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
// quand l'utilisateur active « afficher les masqués ».
|
||||
const rows = this.db.prepare('SELECT id FROM repos WHERE hidden = 0 ORDER BY created_at ASC').all() as Array<{ id: string }>;
|
||||
// Tolérance par repo : avec la découverte auto, un repo douteux (git en échec, chemin disparu,
|
||||
// permission) ne doit JAMAIS faire planter tout l'endpoint — il ne contribue alors aucun worktree.
|
||||
// permission) ne doit JAMAIS faire planter tout l'endpoint, il ne contribue alors aucun worktree.
|
||||
const lists = await Promise.all(rows.map((r) => this.listRepoWorktrees(r.id).catch(() => [])));
|
||||
return lists.flat();
|
||||
}
|
||||
@@ -420,7 +455,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
});
|
||||
}
|
||||
|
||||
/** Branches locales/remote + branche par défaut d'un repo — alimente le sélecteur de base côté UI. */
|
||||
/** Branches locales/remote + branche par défaut d'un repo : alimente le sélecteur de base côté UI. */
|
||||
async listRepoBranches(repoId: string): Promise<{ local: string[]; remote: string[]; default: string | null }> {
|
||||
const row = this.getRepoRow(repoId);
|
||||
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||
@@ -444,16 +479,16 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
const mode = opts.mode ?? 'all';
|
||||
return this.withLock(repoId, async () => {
|
||||
if (opts.amend && !(await isUnpushed(w.path))) {
|
||||
throw httpError(409, 'ALREADY_PUSHED', 'Last commit is already pushed — amend would rewrite shared history');
|
||||
throw httpError(409, 'ALREADY_PUSHED', 'Last commit is already pushed: amend would rewrite shared history');
|
||||
}
|
||||
const st = await worktreeStatus(w.path);
|
||||
// Garde-fou « rien à committer » (sauf amend, qui peut ne changer que le message).
|
||||
if (!opts.amend) {
|
||||
if (mode === 'all' && st.dirtyCount === 0) {
|
||||
throw httpError(409, 'NOTHING_TO_COMMIT', 'Nothing to commit — working tree is clean');
|
||||
throw httpError(409, 'NOTHING_TO_COMMIT', 'Nothing to commit: working tree is clean');
|
||||
}
|
||||
if (mode === 'staged' && (st.stagedCount ?? 0) === 0) {
|
||||
throw httpError(409, 'NOTHING_STAGED', 'Nothing staged — stage files first');
|
||||
throw httpError(409, 'NOTHING_STAGED', 'Nothing staged: stage files first');
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -601,6 +636,55 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
return abs;
|
||||
}
|
||||
|
||||
/**
|
||||
* « Démarrer le projet » : résout le répertoire de base du lancement. Priorité au worktree
|
||||
* `worktreePath` (validé comme worktree connu du repo), sinon worktree portant `branch`, sinon
|
||||
* checkout principal. Le client ne passe JAMAIS un chemin brut non validé (défense en profondeur).
|
||||
*/
|
||||
async resolveLaunchBase(repoId: string, opts: { worktreePath?: string; branch?: string }): Promise<string> {
|
||||
const row = this.getRepoRow(repoId);
|
||||
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||
const wp = opts.worktreePath?.trim();
|
||||
if (wp) {
|
||||
if (!isSafeAbsolutePath(wp)) throw httpError(400, 'BAD_PATH', 'Worktree path must be absolute and normalized');
|
||||
const w = await this.findWorktree(row, wp);
|
||||
if (!w) throw httpError(404, 'NO_RESOLVABLE_WORKTREE', 'No such worktree under this repo');
|
||||
return resolve(w.path);
|
||||
}
|
||||
const branch = opts.branch?.trim();
|
||||
if (branch) {
|
||||
const wts = await this.listRepoWorktrees(repoId);
|
||||
const match = wts.find((w) => w.branch === branch);
|
||||
if (!match) throw httpError(404, 'NO_RESOLVABLE_WORKTREE', `No worktree on branch ${branch}`);
|
||||
return resolve(match.path);
|
||||
}
|
||||
return resolve(row.path); // checkout principal
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout le sous-répertoire relatif d'une commande de lancement, borné au répertoire de base
|
||||
* (anti `..`, anti symlink sortant), calqué sur assertPathInWorktree. Renvoie `base` si vide.
|
||||
*/
|
||||
resolveLaunchSubdir(baseDir: string, relCwd?: string): string {
|
||||
const base = resolve(baseDir);
|
||||
const rel = relCwd?.trim();
|
||||
if (!rel) return base;
|
||||
if (!isSafeRelativePath(rel)) throw httpError(400, 'BAD_PATH', 'Invalid launch cwd');
|
||||
const abs = resolve(join(base, rel));
|
||||
if (abs !== base && !abs.startsWith(base + sep)) throw httpError(403, 'PATH_OUTSIDE_WORKTREE', 'Launch cwd escapes the worktree');
|
||||
if (existsSync(abs)) {
|
||||
let real: string;
|
||||
try {
|
||||
real = realpathSync(abs);
|
||||
} catch {
|
||||
throw httpError(400, 'BAD_PATH', 'Cannot resolve launch cwd');
|
||||
}
|
||||
const realBase = realpathSync(base);
|
||||
if (real !== realBase && !real.startsWith(realBase + sep)) throw httpError(403, 'PATH_OUTSIDE_WORKTREE', 'Launch cwd escapes the worktree (symlink)');
|
||||
}
|
||||
return abs;
|
||||
}
|
||||
|
||||
/** Arme le watcher FS sur un worktree (validé) pour le push temps réel du détail. */
|
||||
async watch(repoId: string, path: string): Promise<void> {
|
||||
if (!this.fsWatcher) return;
|
||||
@@ -646,17 +730,17 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
return this.withLock(repoId, async () => {
|
||||
if (!force) {
|
||||
if ((await worktreeStatus(w.path)).dirtyCount > 0) {
|
||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — commit or pass force');
|
||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes: commit or pass force');
|
||||
}
|
||||
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
|
||||
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes — commit/stash or pass force');
|
||||
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes: commit/stash or pass force');
|
||||
}
|
||||
}
|
||||
try {
|
||||
await removeWorktree(row.path, w.path, force);
|
||||
} catch (err) {
|
||||
if (!force && isDirtyWorktreeError(err)) {
|
||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — pass force to promote anyway');
|
||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes: pass force to promote anyway');
|
||||
}
|
||||
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
|
||||
}
|
||||
@@ -672,7 +756,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lance UNE session dans le checkout principal du repo (`repo.path`) — pour « bosser sur la branche
|
||||
* Lance UNE session dans le checkout principal du repo (`repo.path`) : pour « bosser sur la branche
|
||||
* principale » sans créer de worktree. Si `branch` est fourni, crée/bascule d'abord cette branche
|
||||
* dans ce checkout (`git switch[-c]`), refusé si l'arbre est sale (on n'écrase pas un HEAD modifié).
|
||||
* Volontairement SANS hooks ni pré-trust (contraste avec createWorktree) : le checkout principal
|
||||
@@ -691,7 +775,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
if (branch !== undefined) {
|
||||
// garde-fou : ne pas basculer le HEAD du checkout principal s'il a des changements non sauvegardés.
|
||||
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
|
||||
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes — commit or stash before switching branch');
|
||||
throw httpError(409, 'DIRTY_TREE', 'Main checkout has uncommitted changes: commit or stash before switching branch');
|
||||
}
|
||||
try {
|
||||
await switchBranch(row.path, { branch, create: req.newBranch ?? true });
|
||||
@@ -731,14 +815,14 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
||||
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'Cannot remove the main worktree');
|
||||
// garde-fou : une session vivante tourne dans ce worktree → exiger une confirmation explicite.
|
||||
if (!force && this.sessionsForCwd(w.path, { includeHidden: true }).some((s) => s.live)) {
|
||||
throw httpError(409, 'SESSION_LIVE_IN_WORKTREE', 'A live session runs in this worktree — pass force to delete anyway');
|
||||
throw httpError(409, 'SESSION_LIVE_IN_WORKTREE', 'A live session runs in this worktree: pass force to delete anyway');
|
||||
}
|
||||
return this.withLock(repoId, async () => {
|
||||
try {
|
||||
await removeWorktree(row.path, w.path, force);
|
||||
} catch (err) {
|
||||
if (!force && isDirtyWorktreeError(err)) {
|
||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes — pass force to delete anyway');
|
||||
throw httpError(409, 'WORKTREE_DIRTY', 'Worktree has uncommitted changes: pass force to delete anyway');
|
||||
}
|
||||
throw httpError(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P2 — découverte & reprise : corrélation avec les sessions Claude sur disque.
|
||||
// P2 : découverte & reprise : corrélation avec les sessions Claude sur disque.
|
||||
id: 2,
|
||||
sql: `
|
||||
ALTER TABLE sessions ADD COLUMN claude_session_id TEXT;
|
||||
@@ -38,7 +38,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P3 — repos enregistrés. Les worktrees sont dérivés à la volée de git (non persistés).
|
||||
// P3 : repos enregistrés. Les worktrees sont dérivés à la volée de git (non persistés).
|
||||
id: 3,
|
||||
sql: `
|
||||
CREATE TABLE repos (
|
||||
@@ -53,7 +53,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P4 — abonnements Web Push. Liés au token d'auth (token_id) ; clés VAPID en settings.
|
||||
// P4 : abonnements Web Push. Liés au token d'auth (token_id) ; clés VAPID en settings.
|
||||
id: 4,
|
||||
sql: `
|
||||
CREATE TABLE push_subscriptions (
|
||||
@@ -70,7 +70,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P5 — groupes de travail. Un groupe = collection de repos (many-to-many).
|
||||
// P5 : groupes de travail. Un groupe = collection de repos (many-to-many).
|
||||
// Worktrees/sessions NON persistés ici : servis par WorktreeManager/PtyManager
|
||||
// et filtrés côté client par repoId. CASCADE s'appuie sur PRAGMA foreign_keys = ON (cf. openDb).
|
||||
id: 5,
|
||||
@@ -103,7 +103,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
{
|
||||
// Journal d'audit (conformité entreprise : GDPR/SOX/ISO 27001). Trace les mutations
|
||||
// sensibles (tokens, réglages, secrets, abonnements push, groupes). Ne contient JAMAIS
|
||||
// de secret en clair — `details` est un JSON de métadonnées non sensibles.
|
||||
// de secret en clair, `details` est un JSON de métadonnées non sensibles.
|
||||
id: 7,
|
||||
sql: `
|
||||
CREATE TABLE audit_logs (
|
||||
@@ -119,7 +119,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P6 — session de groupe multi-repo. Une session peut couvrir plusieurs répertoires (--add-dir)
|
||||
// P6 : session de groupe multi-repo. Une session peut couvrir plusieurs répertoires (--add-dir)
|
||||
// et appartenir à un groupe. `added_dirs` : JSON array de chemins absolus (NULL si mono-repo).
|
||||
// `group_id` : pas de FK (ALTER ADD COLUMN sqlite n'en pose pas) ; nettoyé à la suppression du groupe.
|
||||
id: 8,
|
||||
@@ -143,7 +143,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P10 — archivage automatique des sessions terminées (rétention configurable, défaut 30 j).
|
||||
// P10 : archivage automatique des sessions terminées (rétention configurable, défaut 30 j).
|
||||
// `archived_at` NULL = active. Soft-archive : JAMAIS de DELETE (resume/fork restent intacts).
|
||||
// Sémantique distincte de hidden_sessions (#9) : `hidden` est manuel et indexé par
|
||||
// claude_session_id ; `archived` est automatique par ancienneté, indexé par `id`, et ne
|
||||
@@ -155,7 +155,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P12 — connexions aux services git distants (Gitea/GitLab/GitHub). Les SECRETS (PAT, app
|
||||
// P12 : connexions aux services git distants (Gitea/GitLab/GitHub). Les SECRETS (PAT, app
|
||||
// password, tokens OAuth) sont chiffrés par SecretBox AVANT insertion (colonnes *_encrypted) :
|
||||
// la base ne contient jamais de secret en clair. `ssh_key_path`/`oauth_*` sont posés dès
|
||||
// maintenant (schéma stable) mais exploités en P12b/P12c. `test_result` = dernier diagnostic.
|
||||
@@ -181,7 +181,7 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
`,
|
||||
},
|
||||
{
|
||||
// P12 — un repo enregistré peut provenir d'un clone : on retient sa source (remote_url),
|
||||
// P12 : un repo enregistré peut provenir d'un clone : on retient sa source (remote_url),
|
||||
// le service détecté et le credential utilisé. PAS de FK sur credential_id (cohérent avec
|
||||
// sessions.group_id #8) : la suppression d'un credential nullifie ce champ côté manager.
|
||||
id: 12,
|
||||
@@ -191,6 +191,16 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
||||
ALTER TABLE repos ADD COLUMN credential_id TEXT;
|
||||
`,
|
||||
},
|
||||
{
|
||||
// « Démarrer le projet » : commandes de démarrage multi-terminaux, stockées en JSON sur le
|
||||
// repo (miroir de post_create_hooks). Chaque terminal lancé porte un launch_run_id partagé
|
||||
// (regroupement UI + « tout arrêter ») ; pas de FK (cohérent avec sessions.group_id #8).
|
||||
id: 13,
|
||||
sql: `
|
||||
ALTER TABLE repos ADD COLUMN launch_commands TEXT NOT NULL DEFAULT '[]';
|
||||
ALTER TABLE sessions ADD COLUMN launch_run_id TEXT;
|
||||
`,
|
||||
},
|
||||
];
|
||||
|
||||
export type Db = DatabaseSync;
|
||||
@@ -205,7 +215,7 @@ export function openDb(path: string): Db {
|
||||
}
|
||||
|
||||
/**
|
||||
* Restreint la base (et ses fichiers WAL/SHM) à 0o600 — proprio uniquement. La base contient des
|
||||
* Restreint la base (et ses fichiers WAL/SHM) à 0o600, proprio uniquement. La base contient des
|
||||
* secrets (server_secret, clé privée VAPID, hashs de tokens) : elle ne doit jamais être lisible par
|
||||
* d'autres utilisateurs du système. Best-effort : ignoré sur les FS sans permissions POSIX.
|
||||
*/
|
||||
@@ -268,7 +278,7 @@ export function unhideSession(db: Db, claudeSessionId: string): void {
|
||||
db.prepare('DELETE FROM hidden_sessions WHERE claude_session_id = ?').run(claudeSessionId);
|
||||
}
|
||||
|
||||
// ---- Archivage des sessions terminées (par id, soft-archive — P10) ----
|
||||
// ---- Archivage des sessions terminées (par id, soft-archive, P10) ----
|
||||
|
||||
/** Archive une session managée (idempotent : ne touche pas une session déjà archivée). */
|
||||
export function archiveSession(db: Db, id: string, archivedAt: string): void {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { readFileSync, writeSync } from 'node:fs';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { loadConfig, type Config } from './config.js';
|
||||
@@ -40,7 +40,7 @@ export async function runDaemon(config: Config): Promise<void> {
|
||||
if (config.autoDiscover) repoDiscovery.start(); // découverte auto des repos : scan au boot + re-scan périodique
|
||||
|
||||
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
|
||||
app.log.info(`Arboretum v${pkg.version} — ${url}`);
|
||||
app.log.info(`Arboretum v${pkg.version} : ${url}`);
|
||||
if (bootstrapToken) {
|
||||
// Affiché une seule fois : le hash seul est stocké.
|
||||
printTokenBanner(bootstrapToken, url);
|
||||
@@ -48,11 +48,25 @@ export async function runDaemon(config: Config): Promise<void> {
|
||||
console.log('Tokens are stored hashed and cannot be re-printed. Create a new one from Settings (or reset the db).');
|
||||
}
|
||||
|
||||
// Handshake pour un shell embarquant le daemon (app de bureau) : si ARBORETUM_EMIT_TOKEN_FD est
|
||||
// fourni, on mint un token frais et on l'écrit en JSON sur ce descripteur (pipe stdio privé
|
||||
// parent<->enfant). Additif : sans cette variable, comportement strictement inchangé. Le token ne
|
||||
// transite jamais par le renderer et n'est pas affiché.
|
||||
const emitFd = process.env.ARBORETUM_EMIT_TOKEN_FD;
|
||||
if (emitFd) {
|
||||
try {
|
||||
const token = auth.createToken('desktop');
|
||||
writeSync(Number(emitFd), `${JSON.stringify({ token, url })}\n`);
|
||||
} catch (err) {
|
||||
app.log.warn(`token handshake failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
let shuttingDown = false;
|
||||
const shutdown = (signal: string): void => {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
app.log.info(`${signal} received — draining sessions then exiting`);
|
||||
app.log.info(`${signal} received: draining sessions then exiting`);
|
||||
discovery.stop();
|
||||
sessionArchive.stop();
|
||||
repoDiscovery.stop();
|
||||
|
||||
@@ -80,7 +80,7 @@ export function registerAuthRoutes(
|
||||
const body = req.body as Partial<CreateTokenRequest> | null;
|
||||
const label = typeof body?.label === 'string' ? body.label.trim() : '';
|
||||
if (label.length < 1 || label.length > 64) {
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 1–64 characters' } });
|
||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'label must be 1-64 characters' } });
|
||||
}
|
||||
const { id, token } = auth.createTokenRecord(label);
|
||||
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'token.create', resourceId: id, details: { label } });
|
||||
|
||||
@@ -101,7 +101,7 @@ export function registerGroupRoutes(
|
||||
});
|
||||
|
||||
// Session de groupe (P6) : UNE session Claude couvrant tous les repos du groupe (--add-dir).
|
||||
// Les répertoires sont résolus côté serveur depuis les propres worktrees du groupe — le client
|
||||
// Les répertoires sont résolus côté serveur depuis les propres worktrees du groupe : le client
|
||||
// ne passe jamais de chemin brut. `branch` présent → worktree de cette branche par repo ;
|
||||
// absent → le worktree principal de chaque repo.
|
||||
app.post('/api/v1/groups/:id/session', async (req, reply) => {
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||
import type { CreateRepoRequest, DiscoverReposResponse, RepoResponse, ReposListResponse, UpdateRepoRequest } from '@arboretum/shared';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type {
|
||||
CreateRepoRequest,
|
||||
DetectLaunchResponse,
|
||||
DiscoverReposResponse,
|
||||
RepoResponse,
|
||||
ReposListResponse,
|
||||
SessionSummary,
|
||||
StartLaunchRequest,
|
||||
StartLaunchResponse,
|
||||
UpdateRepoRequest,
|
||||
} from '@arboretum/shared';
|
||||
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||
import type { PtyManager } from '../core/pty-manager.js';
|
||||
import type { Db } from '../db/index.js';
|
||||
import { readScanRoots } from '../core/scan-settings.js';
|
||||
import { recordAudit } from '../core/audit-log.js';
|
||||
import { detectLaunchCommands } from '../core/launch-detect.js';
|
||||
|
||||
/** Mappe une erreur du manager (statusCode + code) vers une réponse REST normalisée. */
|
||||
export function sendManagerError(reply: FastifyReply, err: unknown): FastifyReply {
|
||||
@@ -10,7 +24,7 @@ export function sendManagerError(reply: FastifyReply, err: unknown): FastifyRepl
|
||||
return reply.status(e.statusCode ?? 500).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
|
||||
}
|
||||
|
||||
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||
export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db, manager: PtyManager): void {
|
||||
app.get('/api/v1/repos', async (): Promise<ReposListResponse> => ({ repos: await wt.listRepos() }));
|
||||
|
||||
// Scan manuel : découvre et auto-enregistre les repos sous les racines configurées (settings).
|
||||
@@ -34,6 +48,7 @@ export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db
|
||||
...(body.label !== undefined ? { label: body.label } : {}),
|
||||
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
|
||||
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
|
||||
...(body.launchCommands !== undefined ? { launchCommands: body.launchCommands } : {}),
|
||||
});
|
||||
const res: RepoResponse = { repo };
|
||||
return reply.status(201).send(res);
|
||||
@@ -51,6 +66,7 @@ export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db
|
||||
...(body.postCreateHooks !== undefined ? { postCreateHooks: body.postCreateHooks } : {}),
|
||||
...(body.preTrust !== undefined ? { preTrust: body.preTrust } : {}),
|
||||
...(typeof body.hidden === 'boolean' ? { hidden: body.hidden } : {}),
|
||||
...(body.launchCommands !== undefined ? { launchCommands: body.launchCommands } : {}),
|
||||
});
|
||||
const res: RepoResponse = { repo };
|
||||
return reply.send(res);
|
||||
@@ -66,4 +82,79 @@ export function registerRepoRoutes(app: FastifyInstance, wt: WorktreeManager, db
|
||||
}
|
||||
return reply.send({ ok: true });
|
||||
});
|
||||
|
||||
// « Démarrer le projet » : suggestions de commandes détectées dans le répertoire cible
|
||||
// (package.json/Procfile/docker-compose). Le worktree cible est résolu côté serveur.
|
||||
app.get('/api/v1/repos/:id/launch/detect', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const query = (req.query as { worktreePath?: string }) ?? {};
|
||||
try {
|
||||
const base = await wt.resolveLaunchBase(id, {
|
||||
...(typeof query.worktreePath === 'string' ? { worktreePath: query.worktreePath } : {}),
|
||||
});
|
||||
return reply.send({ suggestions: detectLaunchCommands(base) } satisfies DetectLaunchResponse);
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
}
|
||||
});
|
||||
|
||||
// « Démarrer le projet » : lance un terminal (session managée) par commande activée, tous reliés
|
||||
// par un même launchRunId. Le cwd de chaque terminal est borné au worktree cible (anti-traversal).
|
||||
app.post('/api/v1/repos/:id/launch', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const body = (req.body as Partial<StartLaunchRequest> | null) ?? {};
|
||||
|
||||
let repo;
|
||||
try {
|
||||
repo = await wt.getRepo(id);
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
}
|
||||
if (!repo) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No repo with this id' } });
|
||||
|
||||
// Sélection explicite par `commandIds` (outrepasse `enabled`) ; sinon toutes les commandes activées.
|
||||
const wanted = Array.isArray(body.commandIds) ? new Set(body.commandIds) : null;
|
||||
const commands = wanted ? repo.launchCommands.filter((c) => wanted.has(c.id)) : repo.launchCommands.filter((c) => c.enabled);
|
||||
if (commands.length === 0) {
|
||||
return reply.status(400).send({ error: { code: 'NO_LAUNCH_COMMANDS', message: 'No launch command to start (define or enable commands first)' } });
|
||||
}
|
||||
|
||||
let base: string;
|
||||
try {
|
||||
base = await wt.resolveLaunchBase(id, {
|
||||
...(typeof body.worktreePath === 'string' ? { worktreePath: body.worktreePath } : {}),
|
||||
...(typeof body.branch === 'string' ? { branch: body.branch } : {}),
|
||||
});
|
||||
} catch (err) {
|
||||
return sendManagerError(reply, err);
|
||||
}
|
||||
|
||||
const launchRunId = randomUUID();
|
||||
const sessions: SessionSummary[] = [];
|
||||
const skipped: Array<{ id: string; reason: string }> = [];
|
||||
for (const cmd of commands) {
|
||||
if (cmd.run.trim() === '') {
|
||||
skipped.push({ id: cmd.id, reason: 'empty command' });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const cwd = wt.resolveLaunchSubdir(base, cmd.cwd);
|
||||
sessions.push(
|
||||
manager.spawn({ cwd, command: 'bash', login: true, initialInput: cmd.run, title: cmd.label, launchRunId }),
|
||||
);
|
||||
} catch (err) {
|
||||
skipped.push({ id: cmd.id, reason: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
}
|
||||
if (sessions.length === 0) {
|
||||
return reply.status(400).send({ error: { code: 'LAUNCH_FAILED', message: 'No launch command could be started', details: skipped } });
|
||||
}
|
||||
recordAudit(db, {
|
||||
actor: req.authContext?.tokenId ?? 'unknown',
|
||||
action: 'repo.launch',
|
||||
resourceId: id,
|
||||
details: { launchRunId, started: sessions.length, skipped: skipped.length },
|
||||
});
|
||||
return reply.status(201).send({ sessions, skipped } satisfies StartLaunchResponse);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ export function registerSessionRoutes(
|
||||
const claudeSessionId = managed ? managed.claudeSessionId : id;
|
||||
// Garde-fou anti-corruption : jamais de resume direct d'une session vivante (vérif FRAÎCHE).
|
||||
if (discovery.isClaudeSessionLive(claudeSessionId) || manager.findLiveByClaudeSessionId(claudeSessionId)) {
|
||||
return reply.status(409).send({ error: { code: 'SESSION_LIVE', message: 'Session is live — fork it instead' } });
|
||||
return reply.status(409).send({ error: { code: 'SESSION_LIVE', message: 'Session is live, fork it instead' } });
|
||||
}
|
||||
try {
|
||||
// Session de groupe (P6) : re-relie les mêmes répertoires (--add-dir) et son groupe au resume.
|
||||
@@ -104,7 +104,7 @@ export function registerSessionRoutes(
|
||||
});
|
||||
|
||||
// Masque une session découverte (ou managée morte) : exclue de la liste sauf ?includeHidden=true.
|
||||
// Reste reprenable/forkable — c'est un filtre d'affichage, pas une suppression.
|
||||
// Reste reprenable/forkable : c'est un filtre d'affichage, pas une suppression.
|
||||
app.post('/api/v1/sessions/:id/hide', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const sid = resolveClaudeSid(id);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Réglages exposés à l'UI (onglet Réglages). Frontière de sécurité CENTRALE : la table `settings`
|
||||
// contient aussi des SECRETS (server_secret, vapid_private). Ces routes n'exposent QUE des champs
|
||||
// non sensibles et n'écrivent QUE des clés explicitement allow-listées — jamais les secrets.
|
||||
// non sensibles et n'écrivent QUE des clés explicitement allow-listées : jamais les secrets.
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arboretum/shared';
|
||||
import type { Config } from '../config.js';
|
||||
@@ -119,7 +119,7 @@ export function registerSettingsRoutes(
|
||||
details: { keys: Object.keys(body) },
|
||||
});
|
||||
const snap = snapshot();
|
||||
// P11 — diffuse le nouvel état non sensible à tous les clients abonnés au topic 'settings'.
|
||||
// P11 · diffuse le nouvel état non sensible à tous les clients abonnés au topic 'settings'.
|
||||
settingsBus.emit('settings_update', snap.settings);
|
||||
return reply.send(snap);
|
||||
});
|
||||
|
||||
@@ -60,7 +60,7 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
|
||||
}
|
||||
});
|
||||
|
||||
// Branches du repo (locales + suivies de origin + défaut) — alimente le sélecteur de base côté UI.
|
||||
// Branches du repo (locales + suivies de origin + défaut) : alimente le sélecteur de base côté UI.
|
||||
app.get('/api/v1/repos/:id/branches', async (req, reply) => {
|
||||
const { id } = req.params as { id: string };
|
||||
try {
|
||||
|
||||
@@ -67,7 +67,7 @@ export function registerWsGateway(
|
||||
const onSessionExit = (e: { sessionId: string; exitCode: number | null; signal: number | null }): void => {
|
||||
if (subscribedSessions) send({ type: 'session_exit', ...e });
|
||||
};
|
||||
// P10 — une session managée vient d'être archivée (auto par ancienneté ou manuellement).
|
||||
// P10 · une session managée vient d'être archivée (auto par ancienneté ou manuellement).
|
||||
const onSessionArchived = (e: { id: string; archivedAt: string }): void => {
|
||||
if (subscribedSessions) send({ type: 'session_archived', sessionId: e.id });
|
||||
};
|
||||
@@ -93,15 +93,15 @@ export function registerWsGateway(
|
||||
const onGroupRemoved = (groupId: string): void => {
|
||||
if (subscribedGroups) send({ type: 'group_removed', groupId });
|
||||
};
|
||||
// P11 — un réglage a changé : relayé aux connexions abonnées au topic 'settings'.
|
||||
// P11 · un réglage a changé : relayé aux connexions abonnées au topic 'settings'.
|
||||
const onSettingsUpdate = (settings: SettingsBroadcast): void => {
|
||||
if (subscribedSettings) send({ type: 'settings_update', settings });
|
||||
};
|
||||
// P12 — progression d'un clone : relayée aux abonnés du topic 'clones'.
|
||||
// P12 · progression d'un clone : relayée aux abonnés du topic 'clones'.
|
||||
const onCloneUpdate = (operation: CloneOperation): void => {
|
||||
if (subscribedClones) send({ type: 'clone_update', operation });
|
||||
};
|
||||
// P7 — détail d'un worktree modifié : poussé UNIQUEMENT si cette connexion le regarde.
|
||||
// P7 · détail d'un worktree modifié : poussé UNIQUEMENT si cette connexion le regarde.
|
||||
const onWorktreeChanges = (e: { repoId: string; path: string }): void => {
|
||||
if (watched.has(watchKey(e.repoId, e.path))) send({ type: 'worktree_changes', ...e });
|
||||
};
|
||||
|
||||
@@ -77,7 +77,7 @@ afterAll(async () => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('app e2e — auth, origin et sessions', () => {
|
||||
describe('app e2e · auth, origin et sessions', () => {
|
||||
let t: TestApp;
|
||||
let cookieValue: string;
|
||||
|
||||
@@ -277,7 +277,7 @@ describe('app e2e — auth, origin et sessions', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('app e2e — rate limit du login', () => {
|
||||
describe('app e2e · rate limit du login', () => {
|
||||
it('mauvais token et bodies invalides → 401, puis 429 dès le 4e essai (backoff après 3 échecs consécutifs)', async () => {
|
||||
const t = makeApp('ratelimit-failures');
|
||||
const bad = await t.bundle.app.inject({ method: 'POST', url: '/api/v1/auth/login', payload: { token: 'arb_badbadbadbad' } });
|
||||
@@ -309,7 +309,7 @@ describe('app e2e — rate limit du login', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('app e2e — découverte, resume & fork (P2)', () => {
|
||||
describe('app e2e · découverte, resume & fork (P2)', () => {
|
||||
let t: TestApp;
|
||||
let projectsDir: string;
|
||||
let sessionsDir: string;
|
||||
@@ -370,7 +370,7 @@ describe('app e2e — découverte, resume & fork (P2)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('app e2e — découverte auto des repos & masquage', () => {
|
||||
describe('app e2e · découverte auto des repos & masquage', () => {
|
||||
let t: TestApp;
|
||||
let scanRoot: string;
|
||||
const bearer = (): Record<string, string> => ({ authorization: `Bearer ${t.token}` });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Lot 5 — sécurité enterprise : en-têtes de sécurité, journal d'audit, RGPD (export/suppression),
|
||||
// Lot 5 · sécurité enterprise : en-têtes de sécurité, journal d'audit, RGPD (export/suppression),
|
||||
// garde Content-Type. Vérifie le câblage de bout en bout via buildApp + token bootstrap.
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
@@ -4,7 +4,7 @@ import { buildSpawnSpec, diagnoseClaudeBin, resolveClaudeBin } from '../src/core
|
||||
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
|
||||
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||
|
||||
describe('buildSpawnSpec — session de groupe multi-repo (P6)', () => {
|
||||
describe('buildSpawnSpec · session de groupe multi-repo (P6)', () => {
|
||||
it('émet un --add-dir par répertoire supplémentaire (claude)', () => {
|
||||
const spec = buildSpawnSpec({ command: 'claude', addDirs: ['/a', '/b', '/c'] });
|
||||
expect(spec.file).toBe('/usr/bin/claude');
|
||||
@@ -28,7 +28,7 @@ describe('buildSpawnSpec — session de groupe multi-repo (P6)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveClaudeBin / diagnoseClaudeBin — override de chemin (réglage UI)', () => {
|
||||
describe('resolveClaudeBin / diagnoseClaudeBin · override de chemin (réglage UI)', () => {
|
||||
// process.execPath (node) est un fichier exécutable réel garanti sur la machine de test.
|
||||
const realBin = process.execPath;
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
launchAgentPlistPath,
|
||||
} from '../src/cli/install.js';
|
||||
|
||||
describe('cli install — detectPlatform', () => {
|
||||
describe('cli install · detectPlatform', () => {
|
||||
it('accepte linux et darwin', () => {
|
||||
expect(detectPlatform('linux')).toBe('linux');
|
||||
expect(detectPlatform('darwin')).toBe('darwin');
|
||||
@@ -26,7 +26,7 @@ describe('cli install — detectPlatform', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('cli install — buildServiceArgs', () => {
|
||||
describe('cli install · buildServiceArgs', () => {
|
||||
it('aucun flag → aucun argument (le service garde les défauts loopback)', () => {
|
||||
expect(buildServiceArgs(parseInstallArgs([]))).toEqual([]);
|
||||
});
|
||||
@@ -47,7 +47,7 @@ describe('cli install — buildServiceArgs', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('cli install — resolveBin', () => {
|
||||
describe('cli install · resolveBin', () => {
|
||||
it('par défaut : node (process.execPath) + dist/index.js', () => {
|
||||
const { exec, args } = resolveBin({});
|
||||
expect(exec).toBe(process.execPath);
|
||||
@@ -64,7 +64,7 @@ describe('cli install — resolveBin', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('cli install — renderSystemdUnit', () => {
|
||||
describe('cli install · renderSystemdUnit', () => {
|
||||
it('contient le ExecStart calculé et les directives clés', () => {
|
||||
const unit = renderSystemdUnit({ exec: '/usr/bin/node', scriptArgs: ['/opt/arboretum/index.js', '--port', '7317'] });
|
||||
expect(unit).toContain('ExecStart=/usr/bin/node /opt/arboretum/index.js --port 7317');
|
||||
@@ -101,7 +101,7 @@ describe('cli install — renderSystemdUnit', () => {
|
||||
});
|
||||
expect(unit).toMatchInlineSnapshot(`
|
||||
"[Unit]
|
||||
Description=Arboretum — git worktree & Claude Code dashboard
|
||||
Description=Arboretum · git worktree & Claude Code dashboard
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
@@ -120,7 +120,7 @@ describe('cli install — renderSystemdUnit', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('cli install — renderLaunchAgentPlist', () => {
|
||||
describe('cli install · renderLaunchAgentPlist', () => {
|
||||
const base = {
|
||||
label: 'fr.lidge.arboretum',
|
||||
programArguments: ['/usr/bin/node', '/opt/index.js', '--port', '7317'],
|
||||
@@ -163,13 +163,13 @@ describe('cli install — renderLaunchAgentPlist', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('cli install — xmlEscape', () => {
|
||||
describe('cli install · xmlEscape', () => {
|
||||
it('échappe &, < et >', () => {
|
||||
expect(xmlEscape('a & b < c > d')).toBe('a & b < c > d');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cli install — chemins', () => {
|
||||
describe('cli install · chemins', () => {
|
||||
const savedXdg = process.env.XDG_CONFIG_HOME;
|
||||
afterEach(() => {
|
||||
if (savedXdg === undefined) delete process.env.XDG_CONFIG_HOME;
|
||||
|
||||
@@ -24,7 +24,7 @@ async function replay(fixture: string): Promise<Array<{ dialog: ClassifiedDialog
|
||||
return seen;
|
||||
}
|
||||
|
||||
describe('ScreenReader (@xterm/headless) — anti strip-ANSI naïf', () => {
|
||||
describe('ScreenReader (@xterm/headless) · anti strip-ANSI naïf', () => {
|
||||
it('préserve les espaces du dialogue (« Do you want to create », pas « Doyouwant »)', async () => {
|
||||
const seen = await replay('perm-write2.raw');
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
@@ -32,7 +32,7 @@ describe('ScreenReader (@xterm/headless) — anti strip-ANSI naïf', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('classifyDialog — unitaire (lignes synthétiques)', () => {
|
||||
describe('classifyDialog · unitaire (lignes synthétiques)', () => {
|
||||
it('trust', () => {
|
||||
const d = classifyDialog(['Do you trust the files in this folder?', '❯ 1. Yes, I trust this folder', '2. No, exit']);
|
||||
expect(d?.kind).toBe('trust');
|
||||
@@ -81,7 +81,7 @@ describe('détection sur fixtures réelles S3 (replay headless)', () => {
|
||||
|
||||
// Campagne de fiabilité P4-C : chaque type de dialogue ciblé par la supervision mobile doit être
|
||||
// classifié de façon fiable (cf. « reste à faire P4 » du verdict S3 : couvrir le refus Esc et le plan).
|
||||
describe('campagne de fiabilité P4-C — tous les types de dialogue', () => {
|
||||
describe('campagne de fiabilité P4-C · tous les types de dialogue', () => {
|
||||
const realCaptures: Array<{ fixture: string; kind: DialogKind }> = [
|
||||
{ fixture: 'trust.raw', kind: 'trust' },
|
||||
{ fixture: 'perm-write2.raw', kind: 'permission' },
|
||||
@@ -101,7 +101,7 @@ describe('campagne de fiabilité P4-C — tous les types de dialogue', () => {
|
||||
expect(seen.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('plan (synthétique — pas de capture réelle) : « Would you like to proceed? »', () => {
|
||||
it('plan (synthétique, pas de capture réelle) : « Would you like to proceed? »', () => {
|
||||
const d = classifyDialog([
|
||||
'Here is my implementation plan:',
|
||||
' - step one',
|
||||
|
||||
@@ -184,7 +184,7 @@ describe('branche : existence, liste, courante, commit', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('P7 — parseurs purs (status v2 / numstat)', () => {
|
||||
describe('P7 · parseurs purs (status v2 / numstat)', () => {
|
||||
it('parsePorcelainV2 : modifié, untracked, renommé', () => {
|
||||
const z =
|
||||
'1 .M N... 100644 100644 100644 h1 h2 file.txt\x00' +
|
||||
@@ -217,7 +217,7 @@ describe('P7 — parseurs purs (status v2 / numstat)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('P7 — changes / diff / staging / commit sélectif (repo tmp)', () => {
|
||||
describe('P7 · changes / diff / staging / commit sélectif (repo tmp)', () => {
|
||||
it('listChanges : untracked + modifié non indexé + indexé', async () => {
|
||||
const repo = makeTmpRepo();
|
||||
writeFileSync(join(repo, 'untracked.txt'), 'x\n');
|
||||
|
||||
55
packages/server/test/launch-detect.test.ts
Normal file
55
packages/server/test/launch-detect.test.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { afterAll, describe, expect, it } from 'vitest';
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { detectLaunchCommands } from '../src/core/launch-detect.js';
|
||||
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'launch-detect-'));
|
||||
afterAll(() => rmSync(tmp, { recursive: true, force: true }));
|
||||
|
||||
function fixture(name: string, files: Record<string, string>): string {
|
||||
const dir = join(tmp, name);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const [f, content] of Object.entries(files)) writeFileSync(join(dir, f), content);
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe('detectLaunchCommands', () => {
|
||||
it('extrait les scripts npm (par défaut : npm run), active les scripts de dev', () => {
|
||||
const dir = fixture('npm', {
|
||||
'package.json': JSON.stringify({ scripts: { dev: 'vite', build: 'vite build', 'test:unit': 'vitest' } }),
|
||||
});
|
||||
const cmds = detectLaunchCommands(dir);
|
||||
const dev = cmds.find((c) => c.run === 'npm run dev');
|
||||
const build = cmds.find((c) => c.run === 'npm run build');
|
||||
expect(dev?.enabled).toBe(true); // heuristique : dev/start/serve/watch activés
|
||||
expect(build?.enabled).toBe(false);
|
||||
expect(cmds.some((c) => c.run === 'npm run test:unit')).toBe(true);
|
||||
});
|
||||
|
||||
it('utilise pnpm/yarn selon le lockfile présent', () => {
|
||||
const pnpm = fixture('pnpm', { 'package.json': JSON.stringify({ scripts: { dev: 'x' } }), 'pnpm-lock.yaml': '' });
|
||||
expect(detectLaunchCommands(pnpm).find((c) => c.label === 'dev')?.run).toBe('pnpm run dev');
|
||||
const yarn = fixture('yarn', { 'package.json': JSON.stringify({ scripts: { dev: 'x' } }), 'yarn.lock': '' });
|
||||
expect(detectLaunchCommands(yarn).find((c) => c.label === 'dev')?.run).toBe('yarn dev');
|
||||
});
|
||||
|
||||
it('lit le Procfile (name: command), toutes activées', () => {
|
||||
const dir = fixture('proc', { Procfile: 'web: bundle exec puma\nworker: rake jobs:work\n# comment\n' });
|
||||
const cmds = detectLaunchCommands(dir);
|
||||
expect(cmds.find((c) => c.label === 'web')?.run).toBe('bundle exec puma');
|
||||
expect(cmds.find((c) => c.label === 'worker')?.enabled).toBe(true);
|
||||
expect(cmds).toHaveLength(2); // la ligne de commentaire est ignorée
|
||||
});
|
||||
|
||||
it('suggère docker compose up si un fichier compose est présent', () => {
|
||||
const dir = fixture('compose', { 'compose.yaml': 'services: {}' });
|
||||
expect(detectLaunchCommands(dir).some((c) => c.run === 'docker compose up')).toBe(true);
|
||||
});
|
||||
|
||||
it('tolère un répertoire vide ou un package.json invalide', () => {
|
||||
expect(detectLaunchCommands(join(tmp, 'inexistant'))).toEqual([]);
|
||||
const bad = fixture('bad', { 'package.json': '{ not json' });
|
||||
expect(detectLaunchCommands(bad)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -463,7 +463,7 @@ describe('PtyManager (pty mocké)', () => {
|
||||
manager.attach(summary.id, b, 80, 24);
|
||||
|
||||
const chunk = 'x'.repeat(200 * 1024); // 200 Kio ASCII
|
||||
pty.emitData(chunk); // a=200K, b=200K — sous HIGH (384K)
|
||||
pty.emitData(chunk); // a=200K, b=200K : sous HIGH (384K)
|
||||
expect(pty.pause).not.toHaveBeenCalled();
|
||||
|
||||
manager.ack(summary.id, b, 200 * 1024); // b rattrape tout
|
||||
@@ -516,7 +516,7 @@ describe('PtyManager (pty mocké)', () => {
|
||||
const chunks = ['A', 'B', 'C', 'D'].map((c) => c.repeat(mib));
|
||||
|
||||
pty.emitData(chunks[0]!); // outstanding 1 Mio
|
||||
pty.emitData(chunks[1]!); // outstanding 2 Mio — pas strictement > LAGGING_BYTES
|
||||
pty.emitData(chunks[1]!); // outstanding 2 Mio : pas strictement > LAGGING_BYTES
|
||||
expect(a.lagging).toBe(false);
|
||||
expect(a.sendOutput).toHaveBeenCalledTimes(2);
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ function mulberry32(seed: number): () => number {
|
||||
|
||||
const buf = (s: string): Buffer => Buffer.from(s, 'ascii');
|
||||
|
||||
describe('RingBuffer — écriture simple', () => {
|
||||
describe('RingBuffer · écriture simple', () => {
|
||||
it('écrit puis relit sans wrap', () => {
|
||||
const ring = new RingBuffer(16);
|
||||
ring.write(buf('hello'));
|
||||
@@ -76,7 +76,7 @@ describe('RingBuffer — écriture simple', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('RingBuffer — wrap-around', () => {
|
||||
describe('RingBuffer · wrap-around', () => {
|
||||
it('wrap simple : le chunk chevauche la frontière du buffer', () => {
|
||||
const ring = new RingBuffer(8);
|
||||
ring.write(buf('01234')); // pos 0..5
|
||||
@@ -120,7 +120,7 @@ describe('RingBuffer — wrap-around', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('RingBuffer — chunk >= capacité', () => {
|
||||
describe('RingBuffer · chunk >= capacité', () => {
|
||||
it('chunk == capacité sur un ring vierge', () => {
|
||||
const ring = new RingBuffer(8);
|
||||
ring.write(buf('abcdefgh'));
|
||||
@@ -156,7 +156,7 @@ describe('RingBuffer — chunk >= capacité', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('RingBuffer — readFrom', () => {
|
||||
describe('RingBuffer · readFrom', () => {
|
||||
function filled(): RingBuffer {
|
||||
// total = 10, capacité 8 → fenêtre = offsets [2, 10)
|
||||
const ring = new RingBuffer(8);
|
||||
@@ -192,7 +192,7 @@ describe('RingBuffer — readFrom', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('RingBuffer — totalOffset monotone', () => {
|
||||
describe('RingBuffer · totalOffset monotone', () => {
|
||||
it('croît exactement de la taille de chaque chunk, jamais ne décroît', () => {
|
||||
const ring = new RingBuffer(8);
|
||||
const rand = mulberry32(0x5eed);
|
||||
@@ -207,7 +207,7 @@ describe('RingBuffer — totalOffset monotone', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('RingBuffer — équivalence avec le modèle de référence (property test)', () => {
|
||||
describe('RingBuffer · équivalence avec le modèle de référence (property test)', () => {
|
||||
it('tail et readFrom identiques au modèle pour 500 écritures aléatoires (chunks < capacité)', () => {
|
||||
const capacity = 64;
|
||||
const ring = new RingBuffer(capacity);
|
||||
|
||||
@@ -101,7 +101,7 @@ describe('GET /api/v1/settings', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/settings — sécurité', () => {
|
||||
describe('PATCH /api/v1/settings · sécurité', () => {
|
||||
it('ignore toute clé hors allow-list (ne touche pas aux secrets)', async () => {
|
||||
const before = getSetting(db, 'server_secret');
|
||||
await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { server_secret: 'pwned', vapid_private: 'pwned' } });
|
||||
@@ -115,7 +115,7 @@ describe('PATCH /api/v1/settings — sécurité', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/settings — découverte des dépôts', () => {
|
||||
describe('PATCH /api/v1/settings · découverte des dépôts', () => {
|
||||
it('enregistre des scanRoots et un intervalle valides et les renvoie', async () => {
|
||||
const res = await bundle.app.inject({
|
||||
method: 'PATCH',
|
||||
@@ -148,7 +148,7 @@ describe('PATCH /api/v1/settings — découverte des dépôts', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/settings — Claude CLI', () => {
|
||||
describe('PATCH /api/v1/settings · Claude CLI', () => {
|
||||
// process.execPath (node) est un fichier exécutable réel garanti sur la machine de test.
|
||||
const realBin = process.execPath;
|
||||
|
||||
@@ -191,7 +191,7 @@ describe('PATCH /api/v1/settings — Claude CLI', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PATCH /api/v1/settings — rétention des sessions (P10)', () => {
|
||||
describe('PATCH /api/v1/settings · rétention des sessions (P10)', () => {
|
||||
it('enregistre une rétention valide et l’expose', async () => {
|
||||
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { retentionDays: 7 } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Types REST partagés (préfixe /api/v1).
|
||||
import type { CloneOperation, GroupSummary, PostCreateHook, RepoSummary, SessionSummary, SettingsBroadcast, WorktreeSummary } from './protocol.js';
|
||||
import type { CloneOperation, GroupSummary, LaunchCommand, PostCreateHook, RepoSummary, SessionSummary, SettingsBroadcast, WorktreeSummary } from './protocol.js';
|
||||
|
||||
export interface ApiError {
|
||||
error: { code: string; message: string; details?: unknown };
|
||||
@@ -14,7 +14,7 @@ export interface LoginResponse {
|
||||
}
|
||||
export interface MeResponse {
|
||||
ok: true;
|
||||
/** id du token de la session courante — sert à marquer « courant » dans la liste des tokens. */
|
||||
/** id du token de la session courante : sert à marquer « courant » dans la liste des tokens. */
|
||||
tokenId: string;
|
||||
tokenLabel: string;
|
||||
serverVersion: string;
|
||||
@@ -38,18 +38,18 @@ export interface CreateTokenRequest {
|
||||
export interface CreateTokenResponse {
|
||||
id: string;
|
||||
label: string;
|
||||
/** valeur en clair — affichée une seule fois, jamais re-récupérable. */
|
||||
/** valeur en clair : affichée une seule fois, jamais re-récupérable. */
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface CreateSessionRequest {
|
||||
cwd: string;
|
||||
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */
|
||||
/** binaire à lancer : défaut "claude" ; "bash" sert aux tests d'acceptation sans quota */
|
||||
command?: 'claude' | 'bash';
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/projects — crée un NOUVEAU dossier de projet `<root>/<name>` (le serveur ne crée
|
||||
* POST /api/v1/projects : crée un NOUVEAU dossier de projet `<root>/<name>` (le serveur ne crée
|
||||
* jamais de dossier ailleurs) puis y lance une session. Le `git init` est optionnel (case à cocher).
|
||||
* Réponse : `CreateProjectResponse`.
|
||||
*/
|
||||
@@ -60,7 +60,7 @@ export interface CreateProjectRequest {
|
||||
name: string;
|
||||
/** true → `git init` dans le nouveau dossier avant la session (défaut false). */
|
||||
gitInit?: boolean;
|
||||
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests sans quota. */
|
||||
/** binaire à lancer : défaut "claude" ; "bash" sert aux tests sans quota. */
|
||||
command?: 'claude' | 'bash';
|
||||
}
|
||||
export interface CreateProjectResponse {
|
||||
@@ -76,13 +76,13 @@ export interface SessionsListResponse {
|
||||
export interface SessionResponse {
|
||||
session: SessionSummary;
|
||||
}
|
||||
/** POST /sessions/hide-discovered — masque tout l'historique de sessions externes visible. */
|
||||
/** POST /sessions/hide-discovered : masque tout l'historique de sessions externes visible. */
|
||||
export interface HideDiscoveredResponse {
|
||||
/** nombre de sessions effectivement masquées. */
|
||||
hidden: number;
|
||||
}
|
||||
|
||||
// POST /sessions/:id/resume et /sessions/:id/fork (P2) : aucun corps — cwd et command
|
||||
// POST /sessions/:id/resume et /sessions/:id/fork (P2) : aucun corps, cwd et command
|
||||
// sont TOUJOURS dérivés du :id (lu sur disque), jamais fournis par le client (cf. spike S1).
|
||||
export type ResumeSessionRequest = Record<string, never>;
|
||||
export type ForkSessionRequest = Record<string, never>;
|
||||
@@ -99,6 +99,8 @@ export interface CreateRepoRequest {
|
||||
label?: string;
|
||||
postCreateHooks?: PostCreateHook[];
|
||||
preTrust?: boolean;
|
||||
/** commandes de démarrage du projet (« Démarrer le projet »). */
|
||||
launchCommands?: LaunchCommand[];
|
||||
}
|
||||
export interface UpdateRepoRequest {
|
||||
label?: string;
|
||||
@@ -106,6 +108,8 @@ export interface UpdateRepoRequest {
|
||||
preTrust?: boolean;
|
||||
/** true = masquer le repo (exclu du dashboard, conservé en DB) ; false = ré-afficher. */
|
||||
hidden?: boolean;
|
||||
/** commandes de démarrage du projet (« Démarrer le projet »). */
|
||||
launchCommands?: LaunchCommand[];
|
||||
}
|
||||
|
||||
/** Résultat d'un scan de découverte (POST /api/v1/repos/discover). */
|
||||
@@ -134,7 +138,7 @@ export interface HookRunResult {
|
||||
}
|
||||
/**
|
||||
* Stratégie de résolution de la branche d'un nouveau worktree :
|
||||
* - `auto` (défaut) : détecte l'existence de la branche — checkout si elle existe en local, suivi de
|
||||
* - `auto` (défaut) : détecte l'existence de la branche, checkout si elle existe en local, suivi de
|
||||
* `origin/<branch>` si elle n'existe que sur le remote, sinon création (`-b`). Robuste pour les
|
||||
* groupes hétérogènes où la branche peut déjà exister dans certains dépôts mais pas d'autres.
|
||||
* - `create` : force la création (`-b`), échoue si la branche existe déjà.
|
||||
@@ -167,7 +171,7 @@ export interface CreateWorktreeResponse {
|
||||
action: WorktreeBranchAction;
|
||||
}
|
||||
|
||||
/** GET /api/v1/repos/:id/branches — branches locales/remote pour alimenter un sélecteur de base. */
|
||||
/** GET /api/v1/repos/:id/branches : branches locales/remote pour alimenter un sélecteur de base. */
|
||||
export interface RepoBranchesResponse {
|
||||
local: string[];
|
||||
remote: string[];
|
||||
@@ -175,12 +179,12 @@ export interface RepoBranchesResponse {
|
||||
default: string | null;
|
||||
}
|
||||
|
||||
/** POST /api/v1/repos/:id/worktrees/commit — `git add -A` puis commit dans le worktree visé. */
|
||||
/** POST /api/v1/repos/:id/worktrees/commit : `git add -A` puis commit dans le worktree visé. */
|
||||
export interface CommitWorktreeRequest {
|
||||
path: string;
|
||||
message: string;
|
||||
/**
|
||||
* P7 — `all` (défaut, rétrocompat) : `git add -A` + commit (tout l'arbre) ; `staged` : commit
|
||||
* P7 : `all` (défaut, rétrocompat) : `git add -A` + commit (tout l'arbre) ; `staged` : commit
|
||||
* de l'index uniquement (staging sélectif préalable via /stage). `amend` réécrit le dernier
|
||||
* commit (refusé s'il est déjà poussé).
|
||||
*/
|
||||
@@ -214,7 +218,7 @@ export interface FileChange {
|
||||
/** ancien chemin pour un renommage/copie, sinon absent. */
|
||||
renamedFrom?: string;
|
||||
}
|
||||
/** GET /api/v1/repos/:id/worktrees/changes?path= — liste des fichiers modifiés d'un worktree. */
|
||||
/** GET /api/v1/repos/:id/worktrees/changes?path= : liste des fichiers modifiés d'un worktree. */
|
||||
export interface WorktreeChangesResponse {
|
||||
repoId: string;
|
||||
path: string;
|
||||
@@ -222,7 +226,7 @@ export interface WorktreeChangesResponse {
|
||||
/** true si la liste a été bornée (trop de changements). */
|
||||
truncated: boolean;
|
||||
}
|
||||
/** GET /api/v1/repos/:id/worktrees/diff?path=&file=&staged= — diff unifié d'un fichier. */
|
||||
/** GET /api/v1/repos/:id/worktrees/diff?path=&file=&staged= : diff unifié d'un fichier. */
|
||||
export interface FileDiffResponse {
|
||||
path: string;
|
||||
file: string;
|
||||
@@ -233,19 +237,19 @@ export interface FileDiffResponse {
|
||||
/** texte du diff unifié git (vide si binaire ou tooLarge). */
|
||||
diff: string;
|
||||
}
|
||||
/** GET /api/v1/repos/:id/files/content?wt=&path= — contenu d'un fichier (pour l'éditeur Monaco). */
|
||||
/** GET /api/v1/repos/:id/files/content?wt=&path= : contenu d'un fichier (pour l'éditeur Monaco). */
|
||||
export interface FileContentResponse {
|
||||
/** chemin relatif au worktree (POSIX). */
|
||||
path: string;
|
||||
content: string;
|
||||
encoding: 'utf-8';
|
||||
size: number;
|
||||
/** mtime du fichier en ms (st.mtimeMs) — base du garde-fou de conflit d'édition (P8). */
|
||||
/** mtime du fichier en ms (st.mtimeMs) : base du garde-fou de conflit d'édition (P8). */
|
||||
mtime: number;
|
||||
/** langage déduit de l'extension (pour Monaco), si reconnu. */
|
||||
language?: string;
|
||||
}
|
||||
/** PUT /api/v1/repos/:id/files/content — écriture d'un fichier (borné au worktree). */
|
||||
/** PUT /api/v1/repos/:id/files/content : écriture d'un fichier (borné au worktree). */
|
||||
export interface WriteFileRequest {
|
||||
/** chemin absolu du worktree. */
|
||||
wt: string;
|
||||
@@ -258,10 +262,10 @@ export interface WriteFileRequest {
|
||||
export interface WriteFileResponse {
|
||||
ok: true;
|
||||
size: number;
|
||||
/** mtime (ms) du fichier après écriture — le client le réutilise comme nouvelle base. */
|
||||
/** mtime (ms) du fichier après écriture : le client le réutilise comme nouvelle base. */
|
||||
mtime: number;
|
||||
}
|
||||
/** P7 — corps commun des mutations de staging/discard. */
|
||||
/** P7 : corps commun des mutations de staging/discard. */
|
||||
export interface WorktreeFilesRequest {
|
||||
path: string;
|
||||
/** chemins relatifs au worktree. */
|
||||
@@ -271,21 +275,21 @@ export interface WorktreeFilesRequest {
|
||||
export interface DiscardFilesRequest extends WorktreeFilesRequest {
|
||||
includeUntracked?: boolean;
|
||||
}
|
||||
/** POST /api/v1/repos/:id/worktrees/fetch — `git fetch --all --prune`. */
|
||||
/** POST /api/v1/repos/:id/worktrees/fetch : `git fetch --all --prune`. */
|
||||
export interface FetchWorktreeRequest {
|
||||
path: string;
|
||||
}
|
||||
/** POST /api/v1/repos/:id/worktrees/pull — `git pull` (ff-only par défaut). */
|
||||
/** POST /api/v1/repos/:id/worktrees/pull : `git pull` (ff-only par défaut). */
|
||||
export interface PullWorktreeRequest {
|
||||
path: string;
|
||||
mode?: 'ff-only' | 'rebase';
|
||||
}
|
||||
/** POST /api/v1/repos/:id/worktrees/push — pousse la branche du worktree (upstream auto si absent). */
|
||||
/** POST /api/v1/repos/:id/worktrees/push : pousse la branche du worktree (upstream auto si absent). */
|
||||
export interface PushWorktreeRequest {
|
||||
path: string;
|
||||
}
|
||||
/**
|
||||
* POST /api/v1/repos/:id/worktrees/promote — « passer en principal » : la branche du worktree devient
|
||||
* POST /api/v1/repos/:id/worktrees/promote : « passer en principal » : la branche du worktree devient
|
||||
* le checkout principal du dépôt (le worktree est supprimé, l'ancienne branche principale est conservée).
|
||||
*/
|
||||
export interface PromoteWorktreeRequest {
|
||||
@@ -300,12 +304,12 @@ export interface AdoptWorktreeRequest {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/repos/:id/session — lance UNE session dans le checkout principal du repo
|
||||
* POST /api/v1/repos/:id/session : lance UNE session dans le checkout principal du repo
|
||||
* (`repo.path`) pour « bosser sur la branche principale » sans créer de worktree.
|
||||
* Réponse : `SessionResponse`.
|
||||
*/
|
||||
export interface StartRepoSessionRequest {
|
||||
/** binaire à lancer — défaut "claude" ; "bash" sert aux tests sans quota. */
|
||||
/** binaire à lancer : défaut "claude" ; "bash" sert aux tests sans quota. */
|
||||
command?: 'claude' | 'bash';
|
||||
/** si fourni : crée/bascule cette branche dans le checkout principal avant la session. */
|
||||
branch?: string;
|
||||
@@ -313,6 +317,31 @@ export interface StartRepoSessionRequest {
|
||||
newBranch?: boolean;
|
||||
}
|
||||
|
||||
// ---- « Démarrer le projet » : lancement multi-terminaux ----
|
||||
/**
|
||||
* POST /api/v1/repos/:id/launch : lance un terminal par commande de démarrage activée du repo.
|
||||
* Le worktree cible est résolu côté serveur (le client ne passe jamais de chemin absolu brut) :
|
||||
* `worktreePath` prioritaire, sinon worktree de `branch`, sinon checkout principal.
|
||||
*/
|
||||
export interface StartLaunchRequest {
|
||||
/** worktree cible (chemin absolu d'un worktree connu du repo) ; défaut : checkout principal. */
|
||||
worktreePath?: string;
|
||||
/** alternative à `worktreePath` : worktree portant cette branche. */
|
||||
branch?: string;
|
||||
/** ids des commandes à lancer (défaut : toutes les commandes activées du repo). */
|
||||
commandIds?: string[];
|
||||
}
|
||||
export interface StartLaunchResponse {
|
||||
/** un terminal (session managée) par commande lancée, partageant le même launchRunId. */
|
||||
sessions: SessionSummary[];
|
||||
/** commandes non lancées (répertoire cible introuvable, cwd invalide…). */
|
||||
skipped: Array<{ id: string; reason: string }>;
|
||||
}
|
||||
/** GET /api/v1/repos/:id/launch/detect : suggestions de commandes détectées dans le projet. */
|
||||
export interface DetectLaunchResponse {
|
||||
suggestions: LaunchCommand[];
|
||||
}
|
||||
|
||||
// ---- Groupes de travail (P5) ----
|
||||
export interface GroupsListResponse {
|
||||
groups: GroupSummary[];
|
||||
@@ -360,15 +389,15 @@ export interface FsEntry {
|
||||
path: string;
|
||||
/** présent (true) uniquement en mode markRepos quand le dossier est un dépôt git */
|
||||
isRepo?: boolean;
|
||||
/** P7 — présent (true) en mode includeFiles quand l'entrée est un fichier (pas un dossier) */
|
||||
/** P7 : présent (true) en mode includeFiles quand l'entrée est un fichier (pas un dossier) */
|
||||
isFile?: boolean;
|
||||
}
|
||||
export interface FsListResponse {
|
||||
/** chemin absolu listé (normalisé) */
|
||||
path: string;
|
||||
/** parent (null à la racine `/`) — pour le bouton « remonter » */
|
||||
/** parent (null à la racine `/`) : pour le bouton « remonter » */
|
||||
parent: string | null;
|
||||
/** home de l'utilisateur côté serveur — point de départ par défaut */
|
||||
/** home de l'utilisateur côté serveur : point de départ par défaut */
|
||||
home: string;
|
||||
/** sous-dossiers uniquement, triés sans tenir compte de la casse */
|
||||
entries: FsEntry[];
|
||||
@@ -388,7 +417,7 @@ export interface PushUnsubscribeRequest {
|
||||
}
|
||||
|
||||
// ---- Réglages & info serveur (onglet Réglages) ----
|
||||
/** Config runtime non sensible du daemon — lecture seule (changée via flags CLI + redémarrage). */
|
||||
/** Config runtime non sensible du daemon : lecture seule (changée via flags CLI + redémarrage). */
|
||||
export interface ServerInfo {
|
||||
version: string;
|
||||
port: number;
|
||||
@@ -413,22 +442,22 @@ export interface ClaudeBinDiagnostic {
|
||||
ok: boolean;
|
||||
}
|
||||
export interface SettingsResponse {
|
||||
/** réglages modifiables à chaud (allow-list serveur — jamais les secrets). Cf. SettingsBroadcast. */
|
||||
/** réglages modifiables à chaud (allow-list serveur, jamais les secrets). Cf. SettingsBroadcast. */
|
||||
settings: SettingsBroadcast;
|
||||
server: ServerInfo;
|
||||
}
|
||||
export interface UpdateSettingsRequest {
|
||||
/** racines absolues à scanner (chemins normalisés, ≤ 16) ; remplace la liste. */
|
||||
scanRoots?: string[];
|
||||
/** intervalle du re-scan périodique en minutes (0–1440 ; 0 désactive). */
|
||||
/** intervalle du re-scan périodique en minutes (0-1440 ; 0 désactive). */
|
||||
scanIntervalMin?: number;
|
||||
/** chemin absolu du binaire `claude` (fichier exécutable) ; '' pour réinitialiser à l'auto-détection. */
|
||||
claudeBinPath?: string;
|
||||
/** override de la racine ~/.claude (répertoire existant) ; '' pour réinitialiser au défaut. */
|
||||
claudeHome?: string;
|
||||
/** auto-archivage des sessions terminées après N jours (0 = jamais ; sinon 1–3650). */
|
||||
/** auto-archivage des sessions terminées après N jours (0 = jamais ; sinon 1-3650). */
|
||||
retentionDays?: number;
|
||||
/** purge définitive après N jours (0 = désactivée ; sinon 1–3650). */
|
||||
/** purge définitive après N jours (0 = désactivée ; sinon 1-3650). */
|
||||
purgeDays?: number;
|
||||
}
|
||||
|
||||
@@ -505,7 +534,7 @@ export interface CreateGitCredentialRequest {
|
||||
/** instance self-hosted (Gitea/GitLab) ; absent = service public (github.com / gitlab.com). */
|
||||
baseUrl?: string;
|
||||
username?: string;
|
||||
/** PAT ou app password — chiffré côté serveur (SecretBox), jamais relu. */
|
||||
/** PAT ou app password : chiffré côté serveur (SecretBox), jamais relu. */
|
||||
secret?: string;
|
||||
}
|
||||
export interface UpdateGitCredentialRequest {
|
||||
@@ -546,13 +575,13 @@ export interface CloneRequest {
|
||||
credentialId: string;
|
||||
/** URL HTTPS du dépôt à cloner. */
|
||||
remoteUrl: string;
|
||||
/** dossier de destination (sous une racine de scan) — créé par le clone, refus si existant. */
|
||||
/** dossier de destination (sous une racine de scan) : créé par le clone, refus si existant. */
|
||||
dest: string;
|
||||
}
|
||||
export interface CloneStartResponse {
|
||||
operationId: string;
|
||||
}
|
||||
/** État d'un clone (GET /repos/clone/:id) — même forme que le push WS clone_update. */
|
||||
/** État d'un clone (GET /repos/clone/:id) : même forme que le push WS clone_update. */
|
||||
export interface CloneStatusResponse {
|
||||
operation: CloneOperation;
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from './protocol.js';
|
||||
export * from './api.js';
|
||||
export * from './wt-key.js';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Protocole WebSocket Arboretum — une connexion multiplexée par client.
|
||||
// Protocole WebSocket Arboretum : une connexion multiplexée par client.
|
||||
// Messages de contrôle : frames TEXTE JSON. Sortie terminal : frames BINAIRES
|
||||
// (un chunk PTY peut couper un caractère UTF-8 en frontière de frame ; le
|
||||
// décodage incombe à xterm.write(Uint8Array) côté client, jamais au transport).
|
||||
@@ -11,7 +11,7 @@ export const BINARY_FRAME = {
|
||||
HEADER_BYTES: 5,
|
||||
/** serveur → client : sortie terminal */
|
||||
OUTPUT: 0x01,
|
||||
/** serveur → client : resync — le client doit reset son terminal avant d'écrire le payload */
|
||||
/** serveur → client : resync, le client doit reset son terminal avant d'écrire le payload */
|
||||
RESYNC: 0x02,
|
||||
} as const;
|
||||
|
||||
@@ -53,7 +53,7 @@ export const FLOW = {
|
||||
|
||||
/**
|
||||
* Replay à l'attach : reset terminal + queue du ring (l'écran TUI se repeint en continu).
|
||||
* 1 Mo (≈ 10–15k lignes) pour permettre de remonter une vraie conversation Claude dans le terminal ;
|
||||
* 1 Mo (≈ 10-15k lignes) pour permettre de remonter une vraie conversation Claude dans le terminal ;
|
||||
* reste < LAGGING_BYTES (pas de faux lagging) et bien dans RING_CAPACITY.
|
||||
*/
|
||||
export const REPLAY_TAIL_BYTES = 1024 * 1024;
|
||||
@@ -122,6 +122,9 @@ export interface SessionSummary {
|
||||
addedDirs?: string[];
|
||||
/** groupe propriétaire d'une session de groupe (couvre plusieurs repos) ; null/absent sinon. */
|
||||
groupId?: string | null;
|
||||
// ---- Lancement de projet multi-terminaux (additif) ----
|
||||
/** identifiant partagé par tous les terminaux d'un même « Démarrer le projet » ; null/absent sinon. */
|
||||
launchRunId?: string | null;
|
||||
// ---- Masquage (additif) ----
|
||||
/** true = session découverte masquée par l'utilisateur (exclue de la liste sauf includeHidden). */
|
||||
hidden?: boolean;
|
||||
@@ -139,6 +142,22 @@ export interface PostCreateHook {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Commande de démarrage d'un projet (« Démarrer le projet ») : une commande shell longue durée
|
||||
* lancée dans un terminal PTY managé (serveur front, back, base…). Plusieurs commandes activées
|
||||
* = plusieurs terminaux ouverts d'un seul geste. Persistée en JSON sur le repo.
|
||||
*/
|
||||
export interface LaunchCommand {
|
||||
id: string;
|
||||
/** libellé court affiché dans l'onglet du terminal (ex. « web », « api »). */
|
||||
label: string;
|
||||
/** commande shell auto-tapée dans un shell de login interactif (ex. `npm run dev`). */
|
||||
run: string;
|
||||
/** sous-répertoire relatif au worktree où exécuter la commande (borné, jamais hors du worktree). */
|
||||
cwd?: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
export interface RepoSummary {
|
||||
id: string;
|
||||
/** chemin absolu de la racine du repo (main worktree). */
|
||||
@@ -146,6 +165,8 @@ export interface RepoSummary {
|
||||
label: string;
|
||||
defaultBranch: string | null;
|
||||
postCreateHooks: PostCreateHook[];
|
||||
/** commandes de démarrage du projet (« Démarrer le projet ») ; [] si aucune définie. */
|
||||
launchCommands: LaunchCommand[];
|
||||
/** pré-écrire hasTrustDialogAccepted dans ~/.claude.json à la création d'un worktree. */
|
||||
preTrust: boolean;
|
||||
createdAt: string;
|
||||
@@ -160,7 +181,7 @@ export interface WorktreeGitStatus {
|
||||
behind: number;
|
||||
dirtyCount: number;
|
||||
upstream: string | null;
|
||||
// ---- Champs additifs P7 (optionnels, rétrocompat) — compteurs bon marché calculés dans le
|
||||
// ---- Champs additifs P7 (optionnels, rétrocompat) : compteurs bon marché calculés dans le
|
||||
// même passage `status --porcelain=v2` que dirtyCount. La liste détaillée des changements
|
||||
// (FileChange[]) n'est JAMAIS diffusée ici : elle est servie à la demande (REST) et poussée
|
||||
// uniquement aux clients qui « regardent » le worktree (voir `worktree_changes`).
|
||||
@@ -231,7 +252,7 @@ export type CloneState = 'pending' | 'running' | 'done' | 'error';
|
||||
export interface CloneOperation {
|
||||
id: string;
|
||||
state: CloneState;
|
||||
/** progression 0–100 si git la communique, sinon null. */
|
||||
/** progression 0-100 si git la communique, sinon null. */
|
||||
progress: number | null;
|
||||
/** phase courante rapportée par git (« Receiving objects », « Resolving deltas »…). */
|
||||
phase: string | null;
|
||||
@@ -255,7 +276,7 @@ export type ClientMessage =
|
||||
| { type: 'resize'; channel: number; cols: number; rows: number }
|
||||
| { type: 'ack'; channel: number; bytes: number }
|
||||
| { type: 'sub'; topics: Array<'sessions' | 'worktrees' | 'groups' | 'settings' | 'clones'> }
|
||||
// P7 — abonnement ciblé au détail d'un worktree (diff/statut fin) : on ne pousse le détail
|
||||
// P7 : abonnement ciblé au détail d'un worktree (diff/statut fin) : on ne pousse le détail
|
||||
// qu'aux connexions qui « regardent » ce worktree (clé = repoId + path), indépendamment du
|
||||
// topic global 'worktrees' (qui ne transporte que les compteurs légers).
|
||||
| { type: 'watch'; repoId: string; path: string }
|
||||
@@ -270,20 +291,20 @@ export type ServerMessage =
|
||||
| { type: 'control_changed'; channel: number; controlling: boolean }
|
||||
| { type: 'session_update'; session: SessionSummary }
|
||||
| { type: 'session_exit'; sessionId: string; exitCode: number | null; signal: number | null }
|
||||
// P10 — une session managée vient d'être archivée (auto par ancienneté ou manuellement). Signal
|
||||
// P10 : une session managée vient d'être archivée (auto par ancienneté ou manuellement). Signal
|
||||
// léger : le client met à jour son row (badge archived) et le retire si « Show archived » est off.
|
||||
| { type: 'session_archived'; sessionId: string }
|
||||
// P11 — un réglage a changé (PATCH /settings) : on diffuse le snapshot non sensible aux abonnés
|
||||
// P11 : un réglage a changé (PATCH /settings) : on diffuse le snapshot non sensible aux abonnés
|
||||
// du topic 'settings' pour que tous les clients (et onglets) se synchronisent sans polling.
|
||||
| { type: 'settings_update'; settings: SettingsBroadcast }
|
||||
// P12 — progression/fin/erreur d'un clone, poussé aux abonnés du topic 'clones'. L'état complet
|
||||
// P12 : progression/fin/erreur d'un clone, poussé aux abonnés du topic 'clones'. L'état complet
|
||||
// (state) discrimine progress/done/error en un seul message.
|
||||
| { type: 'clone_update'; operation: CloneOperation }
|
||||
| { type: 'repo_update'; repo: RepoSummary }
|
||||
| { type: 'repo_removed'; repoId: string }
|
||||
| { type: 'worktree_update'; repoId: string; worktree: WorktreeSummary }
|
||||
| { type: 'worktree_removed'; repoId: string; path: string }
|
||||
// P7 — signal léger « le détail (diff/fichiers modifiés) de ce worktree a changé, refais un
|
||||
// P7 : signal léger « le détail (diff/fichiers modifiés) de ce worktree a changé, refais un
|
||||
// GET /changes ou /diff ». Envoyé UNIQUEMENT aux connexions ayant `watch`é cette clé. On ne
|
||||
// pousse pas le diff complet dans la frame (taille/flow control) : le client re-fetch en REST.
|
||||
| { type: 'worktree_changes'; repoId: string; path: string }
|
||||
|
||||
33
packages/shared/src/wt-key.ts
Normal file
33
packages/shared/src/wt-key.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
// Encodage du chemin absolu d'un worktree pour le segment d'URL /workspace/:repoId/:wt.
|
||||
// Source unique partagée par le front web ET l'extension VS Code (deep-link), pour éviter toute
|
||||
// divergence d'encodage. base64url (sans +, /, =) donne un segment propre et réversible.
|
||||
|
||||
/** Encode un chemin absolu en base64url (sûr en segment d'URL). */
|
||||
export function encodeWtKey(path: string): string {
|
||||
const b64 = btoa(unescape(encodeURIComponent(path)));
|
||||
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Décode une clé de worktree vers son chemin absolu. Tolérant à deux formats historiques :
|
||||
* - base64url (front web, encodeWtKey) ;
|
||||
* - chemin percent-encodé (ancien deep-link VS Code via encodeURIComponent) : reconnaissable au
|
||||
* caractère `%` que le base64url ne contient jamais.
|
||||
* Ne lève pas : renvoie la clé telle quelle en dernier recours.
|
||||
*/
|
||||
export function decodeWtKey(key: string): string {
|
||||
if (key.includes('%')) {
|
||||
try {
|
||||
return decodeURIComponent(key);
|
||||
} catch {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
const b64 = key.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const pad = b64.length % 4 === 0 ? '' : '='.repeat(4 - (b64.length % 4));
|
||||
try {
|
||||
return decodeURIComponent(escape(atob(b64 + pad)));
|
||||
} catch {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,7 @@ function assertInvariants(msg: ClientMessage): void {
|
||||
}
|
||||
}
|
||||
|
||||
describe('parseClientMessage — cas valides', () => {
|
||||
describe('parseClientMessage · cas valides', () => {
|
||||
it('hello', () => {
|
||||
expect(parseClientMessage('{"type":"hello","protocol":1}')).toEqual({ type: 'hello', protocol: 1 });
|
||||
});
|
||||
@@ -144,7 +144,7 @@ describe('parseClientMessage — cas valides', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseClientMessage — cas malformés', () => {
|
||||
describe('parseClientMessage · cas malformés', () => {
|
||||
it('JSON invalide ou non-objet', () => {
|
||||
for (const raw of ['', 'not json', '{', '42', '"str"', 'null', 'true', '[]', '[1,2]']) {
|
||||
expect(parseClientMessage(raw)).toBeNull();
|
||||
@@ -218,7 +218,7 @@ describe('parseClientMessage — cas malformés', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseClientMessage — fuzz rapide', () => {
|
||||
describe('parseClientMessage · fuzz rapide', () => {
|
||||
it('ne lève jamais et tout message accepté respecte les invariants', () => {
|
||||
const rand = mulberry32(0xa5b0e7);
|
||||
const types = ['hello', 'attach', 'detach', 'stdin', 'answer', 'resize', 'ack', 'sub', 'ping', 'unknown', '', 'HELLO', 42, null];
|
||||
|
||||
24
packages/shared/test/wt-key.test.ts
Normal file
24
packages/shared/test/wt-key.test.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { encodeWtKey, decodeWtKey } from '../src/wt-key.js';
|
||||
|
||||
describe('wt-key', () => {
|
||||
it('encode puis decode restitue le chemin (aller-retour)', () => {
|
||||
for (const p of ['/home/johan/repo', '/a/b c/é', '/tmp/x-y_z', 'C:/Users/x/proj']) {
|
||||
expect(decodeWtKey(encodeWtKey(p))).toBe(p);
|
||||
}
|
||||
});
|
||||
|
||||
it('un segment base64url ne contient ni %, ni +, ni /, ni =', () => {
|
||||
const k = encodeWtKey('/home/johan/mon repo/sous-dossier');
|
||||
expect(k).not.toMatch(/[%+/=]/);
|
||||
});
|
||||
|
||||
it('décode aussi un chemin percent-encodé (ancien deep-link VS Code)', () => {
|
||||
const raw = encodeURIComponent('/home/johan/repo');
|
||||
expect(decodeWtKey(raw)).toBe('/home/johan/repo');
|
||||
});
|
||||
|
||||
it('ne lève pas sur une clé invalide', () => {
|
||||
expect(() => decodeWtKey('!!!not-valid')).not.toThrow();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user