Compare commits
28 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 985531a986 | |||
| d4e3ab47cd | |||
| 8a8fac75e6 | |||
| ac4d098b53 | |||
| 08695a707d | |||
| e8d10b7ec0 | |||
| 92670a796a | |||
| 75efecf93f | |||
| c8dd539571 | |||
| be43911dc0 | |||
| 062bb64d41 | |||
| a67871b9b9 | |||
| 69123eaf0e | |||
| 0f126cf911 | |||
| b5236b41c8 | |||
| 2506dfb1f3 | |||
| 7d618c30d5 | |||
| 529c136199 | |||
| 7fc1f6f747 | |||
| 8b9060e0c0 | |||
| 06a400acc7 | |||
| a1fd00b046 | |||
| 057c2d55ed | |||
| cf7eb05aca | |||
| 663ae7ace1 | |||
| 5ebe3a0f37 | |||
| eb843be9c1 | |||
| f4fb6c3b52 |
@@ -4,7 +4,9 @@ name: Release
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
tags: ['v*']
|
# `v[0-9]*` (et non `v*`) : sinon ce workflow capture aussi les tags `vscode-v*` de l'extension
|
||||||
|
# — il stripperait alors `v` (→ `scode-v0.1.0`) et échouerait contre la version du daemon.
|
||||||
|
tags: ['v[0-9]*']
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
|||||||
74
.gitea/workflows/vscode-release.yml
Normal file
74
.gitea/workflows/vscode-release.yml
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
# Packaging du VSIX de l'extension VS Code, déclenché UNIQUEMENT par un tag vscode-vX.Y.Z
|
||||||
|
# (séparé de la release du daemon, qui écoute les tags v*). Le .vsix est exposé en artefact du run
|
||||||
|
# (toujours) et, en best-effort, attaché à la release Gitea correspondante.
|
||||||
|
name: VSCode Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ['vscode-v*']
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
package:
|
||||||
|
name: Package VSIX
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: npm
|
||||||
|
- run: npm ci
|
||||||
|
# Garde-fou : le tag (sans "vscode-v") doit correspondre à la version du manifeste de l'extension.
|
||||||
|
- name: Verify tag matches extension version
|
||||||
|
run: |
|
||||||
|
pkg=$(node -p "require('./packages/vscode/package.json').version")
|
||||||
|
tag="${GITHUB_REF_NAME#vscode-v}"
|
||||||
|
if [ "$pkg" != "$tag" ]; then
|
||||||
|
echo "ERREUR: tag '$tag' != version extension '$pkg'"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "OK: tag $tag == version $pkg"
|
||||||
|
# Build du shared puis bundle esbuild de l'extension (typecheck inclus), puis packaging VSIX.
|
||||||
|
# --no-dependencies : tout est bundlé dans dist/extension.js → pas de node_modules dans le VSIX.
|
||||||
|
- name: Build & package
|
||||||
|
run: |
|
||||||
|
npm run build:vscode
|
||||||
|
version=$(node -p "require('./packages/vscode/package.json').version")
|
||||||
|
cd packages/vscode
|
||||||
|
npx --yes @vscode/vsce package --no-dependencies -o "git-arboretum-${version}.vsix"
|
||||||
|
# Artefact du run : canal de distribution fiable, indépendant de l'API release.
|
||||||
|
# upload-artifact@v3 : Gitea Actions ne supporte pas @v4 (@actions/artifact v2+).
|
||||||
|
- uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
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.
|
||||||
|
- 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."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
api="${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}"
|
||||||
|
auth="Authorization: token ${RELEASE_TOKEN}"
|
||||||
|
version=$(node -p "require('./packages/vscode/package.json').version")
|
||||||
|
vsix="packages/vscode/git-arboretum-${version}.vsix"
|
||||||
|
# id de release du tag, sinon création
|
||||||
|
rid=$(curl -fsSL -H "$auth" "${api}/releases/tags/${GITHUB_REF_NAME}" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''" || true)
|
||||||
|
if [ -z "$rid" ]; then
|
||||||
|
rid=$(curl -fsSL -X POST -H "$auth" -H 'Content-Type: application/json' \
|
||||||
|
-d "{\"tag_name\":\"${GITHUB_REF_NAME}\",\"name\":\"Arboretum VSCode ${version}\"}" \
|
||||||
|
"${api}/releases" | node -p "JSON.parse(require('fs').readFileSync(0,'utf8')).id || ''")
|
||||||
|
fi
|
||||||
|
curl -fsSL -X POST -H "$auth" -F "attachment=@${vsix}" \
|
||||||
|
"${api}/releases/${rid}/assets?name=git-arboretum-${version}.vsix"
|
||||||
|
echo "VSIX attaché à la release ${GITHUB_REF_NAME}."
|
||||||
57
README.fr.md
57
README.fr.md
@@ -12,6 +12,8 @@
|
|||||||
|
|
||||||
**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.
|
**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 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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Le problème
|
## Le problème
|
||||||
@@ -30,8 +32,12 @@ Un unique daemon Node.js que vous lancez sur votre machine de dev (`npx @johanle
|
|||||||
- **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.
|
- **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).
|
- **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.
|
- **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.
|
- **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.
|
- **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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -104,6 +110,37 @@ node packages/server/dist/index.js
|
|||||||
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).
|
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
|
||||||
|
|
||||||
|
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 :
|
||||||
|
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
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 :
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
## Accès distant depuis votre téléphone
|
## 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 :
|
||||||
@@ -202,6 +239,16 @@ 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`).
|
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.
|
||||||
|
|
||||||
|
## Services git distants & clone
|
||||||
|
|
||||||
|
Arboretum peut se connecter à vos fournisseurs d'hébergement git pour parcourir et cloner des dépôts sans quitter le dashboard :
|
||||||
|
|
||||||
|
- **Fournisseurs & auth.** GitHub, GitLab et Gitea, authentifiés par un **personal access token** ou un **app password** (clés SSH et OAuth prévus). Ajoutez une connexion depuis **Réglages → Services git**, donnez-lui un libellé, et testez-la sur place — Arboretum rapporte `ok`, `auth failed`, `rate limited` ou `unreachable`.
|
||||||
|
- **Les secrets restent secrets.** Les identifiants sont **chiffrés au repos** (AES-256-GCM, `SecretBox`) et **jamais** renvoyés en clair par l'API REST — les réponses ne portent qu'un indice `…last4` et un drapeau « a un secret ».
|
||||||
|
- **Parcourir & cloner.** Listez les dépôts qu'une connexion peut voir, choisissez-en un, et clonez-le en HTTPS vers la destination de votre choix. Le clone tourne comme une opération suivie, avec **progression et phase** poussées en direct via le WebSocket, et le nouveau repo est enregistré automatiquement une fois terminé.
|
||||||
|
|
||||||
## Modèle de sécurité
|
## Modèle de sécurité
|
||||||
|
|
||||||
Un terminal web, c'est de l'exécution de code à distance *par conception*. Les garde-fous d'Arboretum sont structurants :
|
Un terminal web, c'est de l'exécution de code à distance *par conception*. Les garde-fous d'Arboretum sont structurants :
|
||||||
@@ -235,7 +282,7 @@ Arboretum enveloppe le CLI Claude Code **interactif** dans un PTY — la même c
|
|||||||
|
|
||||||
## Développement
|
## 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é) et `@arboretum/web` (la SPA Vue 3).
|
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
|
```bash
|
||||||
npm run build # build shared → server → web (l'ordre compte)
|
npm run build # build shared → server → web (l'ordre compte)
|
||||||
@@ -253,8 +300,16 @@ node packages/server/scripts/acceptance-p2.mjs # découverte & reprise de sess
|
|||||||
node packages/server/scripts/acceptance-p3.mjs # worktrees & corrélation de sessions
|
node packages/server/scripts/acceptance-p3.mjs # worktrees & corrélation de sessions
|
||||||
node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answer`
|
node packages/server/scripts/acceptance-p4.mjs # Web Push + commande WS `answer`
|
||||||
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
|
node packages/server/scripts/acceptance-p5.mjs # groupes de travail : CRUD + broadcast WS + CASCADE
|
||||||
|
node packages/server/scripts/acceptance-p7.mjs # moteur git, API fichiers & watcher FS temps réel
|
||||||
|
node packages/server/scripts/acceptance-p8.mjs # IDE workspace : changes / diff / staging / commit
|
||||||
|
node packages/server/scripts/acceptance-p9.mjs # commit/push avancé : staging sélectif, amend, fetch/pull
|
||||||
|
node packages/server/scripts/acceptance-p10.mjs # archivage automatique des sessions
|
||||||
|
node packages/server/scripts/acceptance-p11.mjs # synchronisation des réglages en temps réel
|
||||||
|
node packages/server/scripts/acceptance-p12.mjs # services git distants + clone HTTPS
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Le protocole s'est enrichi (de façon additive, sans bump de version) pour porter ces nouveautés : messages client `watch` / `unwatch` et signal ciblé `worktree_changes` (P7), plus les broadcasts `session_archived` (P10), `settings_update` (P11) et `clone_update` (P12). Côté serveur, le tout s'appuie sur `core/git.ts` (le moteur git pur), `core/fs-watcher.ts` (chokidar), `core/git-credentials.ts` + `core/clone-manager.ts` (identifiants chiffrés & clone), et les services d'archivage de sessions et de réglages.
|
||||||
|
|
||||||
## Soutenir le projet
|
## Soutenir le projet
|
||||||
|
|
||||||
Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner du temps, vous pouvez soutenir son développement :
|
Arboretum est un projet personnel libre et auto-financé. S'il vous fait gagner du temps, vous pouvez soutenir son développement :
|
||||||
|
|||||||
57
README.md
57
README.md
@@ -12,6 +12,8 @@
|
|||||||
|
|
||||||
**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.
|
**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.
|
||||||
|
|
||||||
|
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 problem
|
## The problem
|
||||||
@@ -30,8 +32,12 @@ A single Node.js daemon you run on your dev machine (`npx @johanleroy/git-arbore
|
|||||||
- **Full worktree lifecycle** — create (with per-repo post-create hooks: `npm ci`, copy `.env`…), adopt worktrees created by hand, delete with guardrails, prune orphans.
|
- **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).
|
- **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.
|
- **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.
|
- **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.
|
- **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).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -104,6 +110,37 @@ node packages/server/dist/index.js
|
|||||||
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).
|
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
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
- **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.
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
- 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.
|
||||||
|
- 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.
|
||||||
|
|
||||||
|
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
|
||||||
|
```
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
## Remote access from your phone
|
## 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:
|
||||||
@@ -202,6 +239,16 @@ Daemon options are CLI flags:
|
|||||||
|
|
||||||
State (the SQLite database) lives in `$XDG_DATA_HOME/arboretum` (default `~/.local/share/arboretum`).
|
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.
|
||||||
|
|
||||||
|
## Remote git services & clone
|
||||||
|
|
||||||
|
Arboretum can connect to your git hosting providers so you can browse and clone repositories without leaving the dashboard:
|
||||||
|
|
||||||
|
- **Providers & auth.** GitHub, GitLab and Gitea, authenticated with a **personal access token** or an **app password** (SSH keys and OAuth are planned). Add a connection from **Settings → Git services**, give it a label, and test it in place — Arboretum reports `ok`, `auth failed`, `rate limited` or `unreachable`.
|
||||||
|
- **Secrets stay secret.** Credentials are **encrypted at rest** (AES-256-GCM, `SecretBox`) and **never** returned in clear by the REST API — responses carry only a `…last4` hint and a "has secret" flag.
|
||||||
|
- **Browse & clone.** List the repositories a connection can see, pick one, and clone it over HTTPS into a destination of your choice. The clone runs as a tracked operation with live **progress and phase** pushed over the WebSocket, and the new repo is registered automatically when it completes.
|
||||||
|
|
||||||
## Security model
|
## Security model
|
||||||
|
|
||||||
A web terminal is remote code execution *by design*. Arboretum's guardrails are structural:
|
A web terminal is remote code execution *by design*. Arboretum's guardrails are structural:
|
||||||
@@ -235,7 +282,7 @@ Arboretum wraps the **interactive** Claude Code CLI in a PTY — the same thing
|
|||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Arboretum is an npm-workspaces monorepo: `@arboretum/shared` (WS/REST protocol, source of truth), `@johanleroy/git-arboretum` (the Fastify daemon, the published package), and `@arboretum/web` (the Vue 3 SPA).
|
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
|
```bash
|
||||||
npm run build # build shared → server → web (order matters)
|
npm run build # build shared → server → web (order matters)
|
||||||
@@ -253,8 +300,16 @@ node packages/server/scripts/acceptance-p2.mjs # session discovery & resume
|
|||||||
node packages/server/scripts/acceptance-p3.mjs # worktrees & session correlation
|
node packages/server/scripts/acceptance-p3.mjs # worktrees & session correlation
|
||||||
node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` command
|
node packages/server/scripts/acceptance-p4.mjs # Web Push + WS `answer` command
|
||||||
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
|
node packages/server/scripts/acceptance-p5.mjs # work groups: CRUD + WS broadcast + CASCADE
|
||||||
|
node packages/server/scripts/acceptance-p7.mjs # git engine, file API & real-time FS watcher
|
||||||
|
node packages/server/scripts/acceptance-p8.mjs # workspace IDE: changes / diff / staging / commit
|
||||||
|
node packages/server/scripts/acceptance-p9.mjs # advanced commit/push: selective staging, amend, fetch/pull
|
||||||
|
node packages/server/scripts/acceptance-p10.mjs # automatic session archival
|
||||||
|
node packages/server/scripts/acceptance-p11.mjs # real-time settings sync
|
||||||
|
node packages/server/scripts/acceptance-p12.mjs # remote git services + HTTPS clone
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The protocol grew (additively, no version bump) to carry the new surface: client `watch` / `unwatch` messages and the targeted `worktree_changes` signal (P7), plus `session_archived` (P10), `settings_update` (P11) and `clone_update` (P12) broadcasts. Server-side, the work is backed by `core/git.ts` (the pure git engine), `core/fs-watcher.ts` (chokidar), `core/git-credentials.ts` + `core/clone-manager.ts` (encrypted credentials & clone), and the session-archive and settings services.
|
||||||
|
|
||||||
## Support
|
## Support
|
||||||
|
|
||||||
Arboretum is a free, self-funded side project. If it saves you time, you can support its development:
|
Arboretum is a free, self-funded side project. If it saves you time, you can support its development:
|
||||||
|
|||||||
3524
package-lock.json
generated
3524
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -18,7 +18,9 @@
|
|||||||
"dev:web": "npm run dev -w @arboretum/web",
|
"dev:web": "npm run dev -w @arboretum/web",
|
||||||
"build:site": "npm run build -w @arboretum/site",
|
"build:site": "npm run build -w @arboretum/site",
|
||||||
"dev:site": "npm run dev -w @arboretum/site",
|
"dev:site": "npm run dev -w @arboretum/site",
|
||||||
"preview:site": "npm run preview -w @arboretum/site"
|
"preview:site": "npm run preview -w @arboretum/site",
|
||||||
|
"build:vscode": "npm run build -w @arboretum/shared -w git-arboretum",
|
||||||
|
"dev:vscode": "npm run dev -w git-arboretum"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.10.0",
|
"@types/node": "^22.10.0",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "1.7.0",
|
"version": "2.0.0",
|
||||||
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
|
"description": "Self-hosted web dashboard for git worktrees and the Claude Code sessions running on them",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -57,6 +57,7 @@
|
|||||||
"@fastify/websocket": "^11.0.0",
|
"@fastify/websocket": "^11.0.0",
|
||||||
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
|
"@homebridge/node-pty-prebuilt-multiarch": "^0.13.0",
|
||||||
"@xterm/headless": "^6.0.0",
|
"@xterm/headless": "^6.0.0",
|
||||||
|
"chokidar": "^4.0.3",
|
||||||
"fastify": "^5.0.0",
|
"fastify": "^5.0.0",
|
||||||
"web-push": "^3.6.7"
|
"web-push": "^3.6.7"
|
||||||
},
|
},
|
||||||
|
|||||||
159
packages/server/scripts/acceptance-p10.mjs
Normal file
159
packages/server/scripts/acceptance-p10.mjs
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P10 (sans navigateur, sans quota Claude) : archivage automatique des sessions terminées.
|
||||||
|
// Vrai daemon + faux binaire `claude` (echo+sleep, comme p2) + 2e connexion sqlite (WAL) pour fabriquer
|
||||||
|
// des sessions managées terminées avec un ended_at ancien. Couvre : sweep archive-now (archived_at posé,
|
||||||
|
// event WS session_archived), exclusion par défaut + inclusion via ?includeArchived, archive/unarchive
|
||||||
|
// manuels, rétention=0 (no-op), et — preuve clé « pas de perte » — resume d'une session ARCHIVÉE → 201.
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7551;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const OLD = '2020-01-01T00:00:00.000Z';
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p10-'));
|
||||||
|
const claudeHome = join(tmp, 'claude');
|
||||||
|
const workDir = join(tmp, 'work');
|
||||||
|
const fakeBin = join(tmp, 'bin');
|
||||||
|
const dbPath = join(tmp, 'a.db');
|
||||||
|
mkdirSync(join(claudeHome, 'projects'), { recursive: true });
|
||||||
|
mkdirSync(join(claudeHome, 'sessions'), { recursive: true });
|
||||||
|
mkdirSync(workDir, { recursive: true });
|
||||||
|
mkdirSync(fakeBin, { recursive: true });
|
||||||
|
writeFileSync(join(fakeBin, 'claude'), '#!/usr/bin/env bash\necho "FAKE-CLAUDE args=[$*] cwd=$(pwd)"\nsleep 30\n');
|
||||||
|
chmodSync(join(fakeBin, 'claude'), 0o755);
|
||||||
|
|
||||||
|
// Insère une session managée « claude » terminée directement en DB (2e connexion WAL).
|
||||||
|
function insertManagedDeadSession(id, claudeSid, endedAt) {
|
||||||
|
const db = new DatabaseSync(dbPath);
|
||||||
|
db.prepare(
|
||||||
|
'INSERT INTO sessions (id, cwd, command, created_at, ended_at, claude_session_id) VALUES (?, ?, ?, ?, ?, ?)',
|
||||||
|
).run(id, workDir, 'claude', OLD, endedAt, claudeSid);
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', dbPath, '--claude-home', claudeHome, '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn', PATH: `${fakeBin}:${process.env.PATH}` }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
function wsClient(cookie) {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
const state = { msgs: [] };
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
|
||||||
|
});
|
||||||
|
const waitMsg = async (pred, timeout = 6000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = state.msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
const listSessions = async (cookie, q = '') => (await (await j(`/api/v1/sessions${q}`, 'GET', cookie)).json()).sessions ?? [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
|
||||||
|
const c = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
|
||||||
|
c.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c.send({ type: 'sub', topics: ['sessions'] });
|
||||||
|
|
||||||
|
// ---- A. Auto-archivage (sweep via archive-now) ----
|
||||||
|
insertManagedDeadSession('arch-old', 'sid-old', OLD);
|
||||||
|
const before = await listSessions(cookie);
|
||||||
|
check('session terminée ancienne visible par défaut (avant archivage)', before.some((s) => s.id === 'arch-old' && !s.archived));
|
||||||
|
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const now = await (await j('/api/v1/sessions/archive-now', 'POST', cookie)).json();
|
||||||
|
check('POST /sessions/archive-now → ≥ 1 archivée', now.archived >= 1, `archived=${now.archived}`);
|
||||||
|
const evt = await c.waitMsg((m) => m.type === 'session_archived' && m.sessionId === 'arch-old');
|
||||||
|
check('event WS session_archived reçu', !!evt);
|
||||||
|
|
||||||
|
const def = await listSessions(cookie);
|
||||||
|
check('GET /sessions exclut l’archivée par défaut', !def.some((s) => s.id === 'arch-old'));
|
||||||
|
const inc = await listSessions(cookie, '?includeArchived=true');
|
||||||
|
check('GET /sessions?includeArchived=true inclut l’archivée (archived=true)', inc.some((s) => s.id === 'arch-old' && s.archived === true));
|
||||||
|
|
||||||
|
// ---- B. Preuve « pas de perte » : resume d'une session ARCHIVÉE → 201 ----
|
||||||
|
const resume = await j('/api/v1/sessions/arch-old/resume', 'POST', cookie);
|
||||||
|
const resumed = await resume.json();
|
||||||
|
check('resume d’une session archivée → 201 (PTY managé claude)', resume.status === 201 && resumed.session?.command === 'claude');
|
||||||
|
|
||||||
|
// ---- C. Archive / unarchive manuels ----
|
||||||
|
insertManagedDeadSession('manual1', 'sid-man', new Date().toISOString()); // récente → le sweep ne la touche pas
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const arch = await j('/api/v1/sessions/manual1/archive', 'POST', cookie);
|
||||||
|
check('POST /sessions/:id/archive → 200', arch.status === 200);
|
||||||
|
check('archive manuel → event session_archived', !!(await c.waitMsg((m) => m.type === 'session_archived' && m.sessionId === 'manual1')));
|
||||||
|
check('archive manuel → exclue par défaut', !(await listSessions(cookie)).some((s) => s.id === 'manual1'));
|
||||||
|
|
||||||
|
const unarch = await j('/api/v1/sessions/manual1/archive', 'DELETE', cookie);
|
||||||
|
check('DELETE /sessions/:id/archive → 200', unarch.status === 200);
|
||||||
|
check('unarchive → ré-affichée par défaut (archived=false)', (await listSessions(cookie)).some((s) => s.id === 'manual1' && !s.archived));
|
||||||
|
|
||||||
|
const missing = await j('/api/v1/sessions/does-not-exist/archive', 'POST', cookie);
|
||||||
|
check('archive d’un id inconnu → 404', missing.status === 404);
|
||||||
|
|
||||||
|
// ---- D. Rétention = 0 → archivage désactivé (no-op) ----
|
||||||
|
const patch = await j('/api/v1/settings', 'PATCH', cookie, { retentionDays: 0 });
|
||||||
|
check('PATCH retentionDays=0 → 200', patch.status === 200);
|
||||||
|
insertManagedDeadSession('arch-old2', 'sid-old2', OLD);
|
||||||
|
const now0 = await (await j('/api/v1/sessions/archive-now', 'POST', cookie)).json();
|
||||||
|
check('rétention=0 → sweep n’archive rien', now0.archived === 0);
|
||||||
|
check('session ancienne reste visible (archivage désactivé)', (await listSessions(cookie)).some((s) => s.id === 'arch-old2' && !s.archived));
|
||||||
|
|
||||||
|
c.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P10: ALL GREEN' : `\nACCEPTANCE P10: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
117
packages/server/scripts/acceptance-p11.mjs
Normal file
117
packages/server/scripts/acceptance-p11.mjs
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P11 (sans navigateur) : temps réel complet. Vrai daemon + vrai repo git tmp + client WS.
|
||||||
|
// Couvre : (1) `git checkout` en CLI sur le CHECKOUT PRINCIPAL → worktree_update (nouvelle branche)
|
||||||
|
// poussé en temps réel (< 500 ms) sans qu'aucun client n'ait `watch`é ce worktree ; (2) PATCH /settings
|
||||||
|
// → settings_update reçu par un client abonné au topic 'settings'.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7554;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p11-'));
|
||||||
|
const repo = join(tmp, 'repo');
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
function wsClient(cookie) {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
const state = { msgs: [] };
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
|
||||||
|
});
|
||||||
|
const waitMsg = async (pred, timeout = 6000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = state.msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(40);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json', Origin: ORIGIN }, body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
|
||||||
|
const c = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
|
||||||
|
c.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c.send({ type: 'sub', topics: ['worktrees', 'settings'] });
|
||||||
|
|
||||||
|
// ---- (1) checkout du PRINCIPAL en CLI → worktree_update sans watch client ----
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
check('POST /repos → 201', addRepo.status === 201);
|
||||||
|
await sleep(1000); // laisse chokidar finir le scan initial du watcher permanent du principal
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const t0 = Date.now();
|
||||||
|
git('checkout', '-b', 'feature'); // changement de branche du checkout principal, hors Arboretum
|
||||||
|
const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 5000);
|
||||||
|
const dt = branchMsg ? Date.now() - t0 : -1;
|
||||||
|
check('checkout principal en CLI → worktree_update (sans watch client)', !!branchMsg, branchMsg ? `${dt}ms` : 'timeout');
|
||||||
|
check('latence temps réel < 500 ms', branchMsg !== null && dt >= 0 && dt < 500, `${dt}ms`);
|
||||||
|
|
||||||
|
// ---- (2) PATCH /settings → settings_update reçu par l'abonné 'settings' ----
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
const patch = await j('/api/v1/settings', 'PATCH', cookie, { retentionDays: 7 });
|
||||||
|
check('PATCH /settings → 200', patch.status === 200);
|
||||||
|
const settingsMsg = await c.waitMsg((m) => m.type === 'settings_update' && m.settings?.retentionDays === 7, 3000);
|
||||||
|
check('settings_update reçu avec le nouvel état', !!settingsMsg);
|
||||||
|
|
||||||
|
c.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P11: ALL GREEN' : `\nACCEPTANCE P11: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
149
packages/server/scripts/acceptance-p12.mjs
Normal file
149
packages/server/scripts/acceptance-p12.mjs
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P12a (sans navigateur, sans réseau/quota) : services git distants + clone. Vrai daemon
|
||||||
|
// + credential factice + clone d'un dépôt bare LOCAL (chemin de fichier, pas de réseau). Couvre :
|
||||||
|
// création de credential (secret chiffré), POST /repos/clone (202) → progression WS clone_update →
|
||||||
|
// done → repo auto-enregistré, ET surtout : le secret en clair est ABSENT de l'API, de la DB et du
|
||||||
|
// .git/config du dépôt cloné (garde-fou « jamais de fuite de secret »).
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7555;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const SECRET = 'arb-secret-token-9876XYZ'; // token factice : ne doit JAMAIS fuiter en clair
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p12-'));
|
||||||
|
const work = join(tmp, 'work'); // racine de scan + destination des clones
|
||||||
|
const src = join(tmp, 'src'); // dépôt source (working)
|
||||||
|
const bare = join(tmp, 'source.git'); // remote bare local (file path)
|
||||||
|
const dbPath = join(tmp, 'a.db');
|
||||||
|
mkdirSync(work, { recursive: true });
|
||||||
|
mkdirSync(src, { recursive: true });
|
||||||
|
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' });
|
||||||
|
g(src, 'init', '-b', 'main');
|
||||||
|
g(src, 'config', 'user.email', 'test@arboretum.dev');
|
||||||
|
g(src, 'config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(src, 'README.md'), '# cloned demo\n');
|
||||||
|
g(src, 'add', '-A');
|
||||||
|
g(src, 'commit', '-m', 'init');
|
||||||
|
execFileSync('git', ['clone', '--bare', src, bare], { stdio: 'pipe' });
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', dbPath, '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
function wsClient(cookie) {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
const state = { msgs: [] };
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
|
||||||
|
});
|
||||||
|
const waitMsg = async (pred, timeout = 15000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = state.msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json', Origin: ORIGIN }, body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
|
||||||
|
// racine de scan = work (confine la destination du clone).
|
||||||
|
const patch = await j('/api/v1/settings', 'PATCH', cookie, { scanRoots: [work] });
|
||||||
|
check('PATCH scanRoots → 200', patch.status === 200);
|
||||||
|
|
||||||
|
// credential factice (secret chiffré côté serveur).
|
||||||
|
const createCred = await j('/api/v1/git-connections', 'POST', cookie, {
|
||||||
|
label: 'fake', service: 'gitea', authType: 'pat', baseUrl: 'http://localhost:9999', secret: SECRET,
|
||||||
|
});
|
||||||
|
const credBody = await createCred.json();
|
||||||
|
const credId = credBody.credential?.id;
|
||||||
|
check('POST /git-connections → 201', createCred.status === 201 && !!credId);
|
||||||
|
check('réponse de création SANS secret en clair', !JSON.stringify(credBody).includes(SECRET));
|
||||||
|
check('réponse expose secretLast4 (et hasSecret)', credBody.credential?.hasSecret === true && credBody.credential?.secretLast4 === SECRET.slice(-4));
|
||||||
|
|
||||||
|
// GET liste : pas de secret.
|
||||||
|
const listed = await (await j('/api/v1/git-connections', 'GET', cookie)).json();
|
||||||
|
check('GET /git-connections SANS secret en clair', !JSON.stringify(listed).includes(SECRET));
|
||||||
|
|
||||||
|
// WS abonné aux clones.
|
||||||
|
const c = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
|
||||||
|
c.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c.send({ type: 'sub', topics: ['clones', 'worktrees'] });
|
||||||
|
|
||||||
|
// clone du bare local → dest sous la racine de scan.
|
||||||
|
const dest = join(work, 'cloned');
|
||||||
|
const clone = await j('/api/v1/repos/clone', 'POST', cookie, { credentialId: credId, remoteUrl: bare, dest });
|
||||||
|
const cloneBody = await clone.json();
|
||||||
|
check('POST /repos/clone → 202 + operationId', clone.status === 202 && !!cloneBody.operationId);
|
||||||
|
|
||||||
|
const doneMsg = await c.waitMsg((m) => m.type === 'clone_update' && m.operation?.id === cloneBody.operationId && m.operation?.state === 'done');
|
||||||
|
check('clone_update state=done reçu via WS', !!doneMsg, doneMsg ? `repoId=${doneMsg.operation.repoId}` : 'timeout');
|
||||||
|
check('le clone a produit un repoId (auto-enregistré)', !!doneMsg?.operation?.repoId);
|
||||||
|
|
||||||
|
// repo enregistré + visible.
|
||||||
|
const repos = await (await j('/api/v1/repos', 'GET', cookie)).json();
|
||||||
|
const cloned = (repos.repos ?? []).find((r) => r.path === dest);
|
||||||
|
check('repo cloné enregistré et listé', !!cloned);
|
||||||
|
check('le dépôt cloné existe sur disque (README.md)', existsSync(join(dest, 'README.md')));
|
||||||
|
|
||||||
|
// ---- garde-fou « pas de fuite de secret » ----
|
||||||
|
const gitConfig = existsSync(join(dest, '.git', 'config')) ? readFileSync(join(dest, '.git', 'config'), 'utf8') : '';
|
||||||
|
check('secret ABSENT du .git/config du clone', !gitConfig.includes(SECRET));
|
||||||
|
const dbBytes = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]
|
||||||
|
.filter((p) => existsSync(p))
|
||||||
|
.map((p) => readFileSync(p).toString('latin1'))
|
||||||
|
.join('');
|
||||||
|
check('secret ABSENT de la base (chiffré au repos)', !dbBytes.includes(SECRET));
|
||||||
|
|
||||||
|
c.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P12: ALL GREEN' : `\nACCEPTANCE P12: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
// group_removed sur le topic 'groups', ajout/retrait de repo, et purge CASCADE de la membership
|
// group_removed sur le topic 'groups', ajout/retrait de repo, et purge CASCADE de la membership
|
||||||
// quand le repo est supprimé (PRAGMA foreign_keys = ON).
|
// quand le repo est supprimé (PRAGMA foreign_keys = ON).
|
||||||
import { spawn, execFileSync } from 'node:child_process';
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, dirname } from 'node:path';
|
import { join, dirname } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
@@ -142,6 +142,34 @@ try {
|
|||||||
const pushedSession = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === gsession.id);
|
const pushedSession = await c.waitMsg((m) => m.type === 'session_update' && m.session?.id === gsession.id);
|
||||||
check('broadcast WS session_update (session de groupe)', !!pushedSession);
|
check('broadcast WS session_update (session de groupe)', !!pushedSession);
|
||||||
|
|
||||||
|
// ---- Worktree de groupe sur une NOUVELLE branche (scénario corrigé : mode auto, plus de -b raté) ----
|
||||||
|
const wtA = await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'POST', cookie, { branch: 'feature/cross', mode: 'auto', startSession: null });
|
||||||
|
const wtABody = await wtA.json();
|
||||||
|
check('POST /repos/:id/worktrees (branche neuve) → 201 + action=created', wtA.status === 201 && wtABody.action === 'created');
|
||||||
|
const wtB = await j(`/api/v1/repos/${repo2Summary.id}/worktrees`, 'POST', cookie, { branch: 'feature/cross', mode: 'auto', startSession: null });
|
||||||
|
check('POST /repos (2e repo) worktree branche neuve → 201', wtB.status === 201);
|
||||||
|
|
||||||
|
// GET /branches : la nouvelle branche apparaît (alimente le sélecteur de base côté UI).
|
||||||
|
const branchesA = await (await j(`/api/v1/repos/${repoSummary.id}/branches`, 'GET', cookie)).json();
|
||||||
|
check('GET /repos/:id/branches : feature/cross présente', Array.isArray(branchesA.local) && branchesA.local.includes('feature/cross'));
|
||||||
|
|
||||||
|
// session de groupe SUR cette branche → résout les worktrees créés (le cas qui échouait avant).
|
||||||
|
const gsBranch = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'feature/cross' });
|
||||||
|
const gsBranchBody = await gsBranch.json();
|
||||||
|
check('POST /groups/:id/session (branche) → 201 + 2 dirs', gsBranch.status === 201 && gsBranchBody.dirs?.length === 2);
|
||||||
|
await j(`/api/v1/sessions/${gsBranchBody.session.id}`, 'DELETE', cookie);
|
||||||
|
|
||||||
|
// commit : fichier neuf dans le worktree de repo1 puis commit via l'endpoint.
|
||||||
|
writeFileSync(join(wtABody.worktree.path, 'cross.txt'), 'wip\n');
|
||||||
|
const commitRes = await j(`/api/v1/repos/${repoSummary.id}/worktrees/commit`, 'POST', cookie, { path: wtABody.worktree.path, message: 'wip cross' });
|
||||||
|
check('POST /worktrees/commit → 200 + dirty=0', commitRes.status === 200 && (await commitRes.json()).worktree?.git?.dirtyCount === 0);
|
||||||
|
|
||||||
|
// promotion « en principal » : feature/cross devient le checkout principal de repo1, worktree supprimé.
|
||||||
|
const promRes = await j(`/api/v1/repos/${repoSummary.id}/worktrees/promote`, 'POST', cookie, { path: wtABody.worktree.path });
|
||||||
|
check('POST /worktrees/promote → 200', promRes.status === 200);
|
||||||
|
const wtsAfter = await (await j(`/api/v1/repos/${repoSummary.id}/worktrees`, 'GET', cookie)).json();
|
||||||
|
check('promotion : checkout principal désormais sur feature/cross', wtsAfter.worktrees?.find((w) => w.isMain)?.branch === 'feature/cross');
|
||||||
|
|
||||||
// groupe sans worktree résolu (branche inexistante) → 400.
|
// groupe sans worktree résolu (branche inexistante) → 400.
|
||||||
const gsBad = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'no/such/branch' });
|
const gsBad = await j(`/api/v1/groups/${group.id}/session`, 'POST', cookie, { command: 'bash', branch: 'no/such/branch' });
|
||||||
check('POST /groups/:id/session branche absente → 400', gsBad.status === 400);
|
check('POST /groups/:id/session branche absente → 400', gsBad.status === 400);
|
||||||
|
|||||||
163
packages/server/scripts/acceptance-p7.mjs
Normal file
163
packages/server/scripts/acceptance-p7.mjs
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P7 (sans navigateur, sans quota Claude) : moteur git « IDE » + API fichiers + watcher
|
||||||
|
// FS temps réel. Vrai daemon + vrai repo git tmp + vrai client WS. Couvre : GET /changes & /diff,
|
||||||
|
// staging sélectif + commit(staged), API fichiers content GET/PUT (Monaco) + refus de traversal,
|
||||||
|
// abonnement ciblé watch → worktree_changes à l'édition, checkout externe → worktree_update, unwatch.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync, appendFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7547;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p7-'));
|
||||||
|
const repo = join(tmp, 'demo-repo');
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
function wsClient(cookie) {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
const state = { msgs: [] };
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
if (!isBinary) state.msgs.push(JSON.parse(String(data)));
|
||||||
|
});
|
||||||
|
const waitMsg = async (pred, timeout = 8000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = state.msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
return { ws, state, waitMsg, send: (m) => ws.send(JSON.stringify(m)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
|
||||||
|
const c = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c.ws.on('open', res), c.ws.on('error', rej)));
|
||||||
|
c.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c.send({ type: 'sub', topics: ['worktrees'] });
|
||||||
|
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoId = (await addRepo.json()).repo.id;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
|
||||||
|
const enc = encodeURIComponent(repo);
|
||||||
|
|
||||||
|
// ---- GET /changes : un fichier modifié + un untracked ----
|
||||||
|
appendFileSync(join(repo, 'README.md'), 'edited line\n');
|
||||||
|
writeFileSync(join(repo, 'untracked.txt'), 'new\n');
|
||||||
|
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
|
||||||
|
const byPath = Object.fromEntries((ch.changes ?? []).map((c2) => [c2.path, c2]));
|
||||||
|
check('GET /changes : README.md modifié non indexé', byPath['README.md']?.unstaged === true && byPath['README.md']?.staged === false);
|
||||||
|
check('GET /changes : untracked.txt détecté', byPath['untracked.txt']?.untracked === true);
|
||||||
|
|
||||||
|
// ---- GET /diff ----
|
||||||
|
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
|
||||||
|
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+edited line'));
|
||||||
|
|
||||||
|
// ---- staging sélectif + commit(staged) ----
|
||||||
|
const stage = await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['README.md'] });
|
||||||
|
const staged = await stage.json();
|
||||||
|
check('POST /stage → README.md staged', staged.worktree?.git?.stagedCount >= 1);
|
||||||
|
const commit = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'commit staged only', mode: 'staged' });
|
||||||
|
check('POST /commit (mode=staged) → 200', commit.status === 200);
|
||||||
|
const ch2 = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
|
||||||
|
const paths2 = (ch2.changes ?? []).map((c2) => c2.path);
|
||||||
|
check('après commit staged : README committé, untracked restant', !paths2.includes('README.md') && paths2.includes('untracked.txt'));
|
||||||
|
|
||||||
|
// ---- API fichiers (Monaco) : GET content + PUT + refus traversal ----
|
||||||
|
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=untracked.txt`, 'GET', cookie)).json();
|
||||||
|
check('GET /files/content : contenu lu + langage', get1.content === 'new\n');
|
||||||
|
const put = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
|
||||||
|
check('PUT /files/content (création) → 200', put.status === 200);
|
||||||
|
const get2 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
|
||||||
|
check('GET après PUT : contenu écrit + langage typescript', get2.content === 'export const x = 1\n' && get2.language === 'typescript');
|
||||||
|
const trav = await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=${encodeURIComponent('../escape.txt')}`, 'GET', cookie);
|
||||||
|
check('GET /files/content : traversal ../ refusé', trav.status === 400 || trav.status === 403);
|
||||||
|
|
||||||
|
// ---- temps réel : watch → worktree_changes à l'édition ----
|
||||||
|
c.send({ type: 'watch', repoId, path: repo });
|
||||||
|
await sleep(900); // laisse chokidar finir son scan initial
|
||||||
|
const t0 = Date.now();
|
||||||
|
writeFileSync(join(repo, 'live.txt'), 'live edit\n');
|
||||||
|
const changesMsg = await c.waitMsg((m) => m.type === 'worktree_changes' && m.path === repo, 6000);
|
||||||
|
check('watch → worktree_changes ciblé reçu', !!changesMsg, changesMsg ? `${Date.now() - t0}ms` : 'timeout');
|
||||||
|
const updMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.path === repo, 3000);
|
||||||
|
check('édition → worktree_update diffusé', !!updMsg);
|
||||||
|
|
||||||
|
// ---- checkout externe (CLI) → worktree_update avec nouvelle branche ----
|
||||||
|
c.state.msgs.length = 0; // reset pour ne capter que les nouveaux events
|
||||||
|
git('branch', 'feature');
|
||||||
|
git('checkout', 'feature');
|
||||||
|
const branchMsg = await c.waitMsg((m) => m.type === 'worktree_update' && m.worktree?.isMain && m.worktree?.branch === 'feature', 6000);
|
||||||
|
check('checkout externe → branche principale mise à jour en temps réel', !!branchMsg);
|
||||||
|
|
||||||
|
// ---- unwatch : plus de worktree_changes ----
|
||||||
|
c.send({ type: 'unwatch', repoId, path: repo });
|
||||||
|
await sleep(300);
|
||||||
|
c.state.msgs.length = 0;
|
||||||
|
writeFileSync(join(repo, 'after-unwatch.txt'), 'x\n');
|
||||||
|
const afterUnwatch = await c.waitMsg((m) => m.type === 'worktree_changes', 1500);
|
||||||
|
check('unwatch → plus de worktree_changes', !afterUnwatch);
|
||||||
|
|
||||||
|
c.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P7: ALL GREEN' : `\nACCEPTANCE P7: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
122
packages/server/scripts/acceptance-p8.mjs
Normal file
122
packages/server/scripts/acceptance-p8.mjs
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P8 (sans navigateur) : API fichiers de l'éditeur Monaco + garde-fou conflit (mtime).
|
||||||
|
// Vrai daemon + vrai repo git tmp. Couvre : GET content (+mtime), PUT avec baseMtime correct → 200,
|
||||||
|
// PUT avec baseMtime périmé → 409 STALE_FILE, PUT sans baseMtime (overwrite) → 200, diff après
|
||||||
|
// édition cohérent, fs/list?includeFiles=1 (isFile), refus de traversal.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const PORT = 7552;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p8-'));
|
||||||
|
const repo = join(tmp, 'demo-repo');
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'init');
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoId = (await addRepo.json()).repo.id;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
|
||||||
|
const enc = encodeURIComponent(repo);
|
||||||
|
|
||||||
|
// ---- GET content : contenu + mtime ----
|
||||||
|
const get1 = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=README.md`, 'GET', cookie)).json();
|
||||||
|
check('GET /files/content : contenu + mtime', get1.content === '# demo\n' && typeof get1.mtime === 'number');
|
||||||
|
const mtime0 = get1.mtime;
|
||||||
|
|
||||||
|
// ---- PUT avec baseMtime correct → 200 + nouveau mtime ----
|
||||||
|
const put1 = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
|
||||||
|
wt: repo, path: 'README.md', content: '# demo\nedited via editor\n', baseMtime: mtime0,
|
||||||
|
});
|
||||||
|
const put1Body = await put1.json();
|
||||||
|
check('PUT (baseMtime correct) → 200 + mtime', put1.status === 200 && typeof put1Body.mtime === 'number');
|
||||||
|
|
||||||
|
// ---- PUT avec baseMtime périmé (l'ancien) → 409 STALE_FILE ----
|
||||||
|
const putStale = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
|
||||||
|
wt: repo, path: 'README.md', content: 'concurrent overwrite\n', baseMtime: mtime0,
|
||||||
|
});
|
||||||
|
const staleBody = await putStale.json();
|
||||||
|
check('PUT (baseMtime périmé) → 409 STALE_FILE', putStale.status === 409 && staleBody.error?.code === 'STALE_FILE');
|
||||||
|
|
||||||
|
// ---- PUT sans baseMtime (overwrite forcé) → 200 ----
|
||||||
|
const putForce = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, {
|
||||||
|
wt: repo, path: 'README.md', content: '# demo\nforced\n',
|
||||||
|
});
|
||||||
|
check('PUT (sans baseMtime, overwrite) → 200', putForce.status === 200);
|
||||||
|
|
||||||
|
// ---- diff après édition ----
|
||||||
|
const ch = await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json();
|
||||||
|
check('GET /changes : README.md modifié', (ch.changes ?? []).some((c) => c.path === 'README.md' && c.unstaged));
|
||||||
|
const diff = await (await j(`/api/v1/repos/${repoId}/worktrees/diff?path=${enc}&file=README.md`, 'GET', cookie)).json();
|
||||||
|
check('GET /diff : contient la ligne ajoutée', typeof diff.diff === 'string' && diff.diff.includes('+forced'));
|
||||||
|
|
||||||
|
// ---- création d'un nouveau fichier + lecture du langage ----
|
||||||
|
const putNew = await j('/api/v1/repos/' + repoId + '/files/content', 'PUT', cookie, { wt: repo, path: 'src/app.ts', content: 'export const x = 1\n' });
|
||||||
|
check('PUT (création src/app.ts) → 200', putNew.status === 200);
|
||||||
|
const getNew = await (await j(`/api/v1/repos/${repoId}/files/content?wt=${enc}&path=src/app.ts`, 'GET', cookie)).json();
|
||||||
|
check('GET nouveau fichier : langage typescript', getNew.language === 'typescript');
|
||||||
|
|
||||||
|
// ---- fs/list?includeFiles=1 : remonte les fichiers (arbre IDE) ----
|
||||||
|
const fs = await (await j(`/api/v1/fs/list?path=${enc}&includeFiles=1`, 'GET', cookie)).json();
|
||||||
|
const readme = (fs.entries ?? []).find((e) => e.name === 'README.md');
|
||||||
|
check('fs/list?includeFiles=1 : README.md (isFile)', readme?.isFile === true);
|
||||||
|
|
||||||
|
// ---- refus de traversal ----
|
||||||
|
const trav = await j(`/api/v1/repos/${repoId}/files/content`, 'PUT', cookie, { wt: repo, path: '../escape.txt', content: 'x' });
|
||||||
|
check('PUT traversal ../ refusé', trav.status === 400 || trav.status === 403);
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P8: ALL GREEN' : `\nACCEPTANCE P8: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
128
packages/server/scripts/acceptance-p9.mjs
Normal file
128
packages/server/scripts/acceptance-p9.mjs
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P9 (sans navigateur) : cycle git propre depuis l'UI (primitives P7). Vrai daemon +
|
||||||
|
// vrai repo git tmp + remote bare local (file://). Couvre : staging sélectif → commit ne prend QUE
|
||||||
|
// le sélectionné ; amend d'un commit NON poussé → OK (HEAD change) ; amend d'un commit POUSSÉ → 409
|
||||||
|
// ALREADY_PUSHED ; pull --ff-only fast-forward → OK ; pull en divergence → refusé proprement.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const PORT = 7553;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? ` — ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-accept-p9-'));
|
||||||
|
const repo = join(tmp, 'repo');
|
||||||
|
const bare = join(tmp, 'bare.git');
|
||||||
|
const clone2 = join(tmp, 'clone2');
|
||||||
|
const g = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }).toString();
|
||||||
|
const cfg = (cwd) => {
|
||||||
|
g(cwd, 'config', 'user.email', 'test@arboretum.dev');
|
||||||
|
g(cwd, 'config', 'user.name', 'Test');
|
||||||
|
};
|
||||||
|
|
||||||
|
execFileSync('mkdir', ['-p', repo]);
|
||||||
|
g(repo, 'init', '-b', 'main');
|
||||||
|
cfg(repo);
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a\n');
|
||||||
|
g(repo, 'add', '-A');
|
||||||
|
g(repo, 'commit', '-m', 'init');
|
||||||
|
execFileSync('git', ['init', '--bare', bare], { stdio: 'pipe' });
|
||||||
|
g(bare, 'symbolic-ref', 'HEAD', 'refs/heads/main'); // pour que les clones se placent sur main
|
||||||
|
g(repo, 'remote', 'add', 'origin', bare);
|
||||||
|
g(repo, 'push', '-u', 'origin', 'main');
|
||||||
|
|
||||||
|
const srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
const j = (path, method, cookie, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: cookie, ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/json', Origin: ORIGIN }, body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200);
|
||||||
|
const addRepo = await j('/api/v1/repos', 'POST', cookie, { path: repo });
|
||||||
|
const repoId = (await addRepo.json()).repo.id;
|
||||||
|
check('POST /repos → 201', addRepo.status === 201 && !!repoId);
|
||||||
|
const enc = encodeURIComponent(repo);
|
||||||
|
const changes = async () => (await (await j(`/api/v1/repos/${repoId}/worktrees/changes?path=${enc}`, 'GET', cookie)).json()).changes ?? [];
|
||||||
|
|
||||||
|
// ---- staging sélectif : modifier 2 fichiers, n'indexer que a.txt, committer staged ----
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a modified\n');
|
||||||
|
writeFileSync(join(repo, 'b.txt'), 'b new\n');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', cookie, { path: repo, files: ['a.txt'] });
|
||||||
|
const commit1 = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a', mode: 'staged' });
|
||||||
|
check('commit (staged) → 200', commit1.status === 200);
|
||||||
|
const afterCommit = (await changes()).map((c) => c.path);
|
||||||
|
check('commit ne prend QUE le fichier indexé (b.txt reste, a.txt committé)', !afterCommit.includes('a.txt') && afterCommit.includes('b.txt'));
|
||||||
|
check('a.txt présent dans le dernier commit', g(repo, 'show', '--name-only', '--format=', 'HEAD').includes('a.txt'));
|
||||||
|
|
||||||
|
// ---- amend d'un commit NON poussé → OK, le sujet de HEAD change ----
|
||||||
|
const amendOk = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'only a (amended)', amend: true });
|
||||||
|
check('amend (commit non poussé) → 200', amendOk.status === 200);
|
||||||
|
check('amend modifie le sujet de HEAD', g(repo, 'log', '-1', '--format=%s').trim() === 'only a (amended)');
|
||||||
|
|
||||||
|
// ---- push, puis amend d'un commit POUSSÉ → 409 ALREADY_PUSHED ----
|
||||||
|
const push = await j(`/api/v1/repos/${repoId}/worktrees/push`, 'POST', cookie, { path: repo });
|
||||||
|
check('push → 200', push.status === 200);
|
||||||
|
const amendPushed = await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'too late', amend: true });
|
||||||
|
const amendBody = await amendPushed.json();
|
||||||
|
check('amend (commit poussé) → 409 ALREADY_PUSHED', amendPushed.status === 409 && amendBody.error?.code === 'ALREADY_PUSHED');
|
||||||
|
|
||||||
|
// ---- pull --ff-only : un commit distant en avance → fast-forward OK ----
|
||||||
|
execFileSync('git', ['clone', bare, clone2], { stdio: 'pipe' });
|
||||||
|
cfg(clone2);
|
||||||
|
writeFileSync(join(clone2, 'c.txt'), 'c\n');
|
||||||
|
g(clone2, 'add', '-A');
|
||||||
|
g(clone2, 'commit', '-m', 'remote commit');
|
||||||
|
g(clone2, 'push', 'origin', 'main');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
|
||||||
|
const pullFf = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
|
||||||
|
check('pull --ff-only (fast-forward) → 200', pullFf.status === 200);
|
||||||
|
check('le commit distant est intégré (remote commit dans l’historique)', g(repo, 'log', '--format=%s').includes('remote commit'));
|
||||||
|
|
||||||
|
// ---- divergence : commit local non poussé + commit distant → pull --ff-only refusé ----
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a local divergent\n');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/commit`, 'POST', cookie, { path: repo, message: 'local divergent', mode: 'all' });
|
||||||
|
writeFileSync(join(clone2, 'd.txt'), 'd\n');
|
||||||
|
g(clone2, 'add', '-A');
|
||||||
|
g(clone2, 'commit', '-m', 'remote divergent');
|
||||||
|
g(clone2, 'push', 'origin', 'main');
|
||||||
|
await j(`/api/v1/repos/${repoId}/worktrees/fetch`, 'POST', cookie, { path: repo });
|
||||||
|
const pullDiv = await j(`/api/v1/repos/${repoId}/worktrees/pull`, 'POST', cookie, { path: repo, mode: 'ff-only' });
|
||||||
|
check('pull --ff-only en divergence → refusé (non-200)', pullDiv.status !== 200, `status=${pullDiv.status}`);
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.signalCode === null || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P9: ALL GREEN' : `\nACCEPTANCE P9: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -10,6 +10,11 @@ import type { Db } from './db/index.js';
|
|||||||
import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.js';
|
import { AuthService, LoginRateLimiter, type AuthContext } from './auth/service.js';
|
||||||
import { PtyManager } from './core/pty-manager.js';
|
import { PtyManager } from './core/pty-manager.js';
|
||||||
import { DiscoveryService } from './core/discovery-service.js';
|
import { DiscoveryService } from './core/discovery-service.js';
|
||||||
|
import { SessionArchiveService } from './core/session-archive.js';
|
||||||
|
import { SettingsBus } from './core/settings-bus.js';
|
||||||
|
import { GitCredentialsManager } from './core/git-credentials.js';
|
||||||
|
import { CloneManager } from './core/clone-manager.js';
|
||||||
|
import { registerGitConnectionRoutes } from './routes/git-connections.js';
|
||||||
import { WorktreeManager } from './core/worktree-manager.js';
|
import { WorktreeManager } from './core/worktree-manager.js';
|
||||||
import { RepoDiscoveryService } from './core/repo-discovery.js';
|
import { RepoDiscoveryService } from './core/repo-discovery.js';
|
||||||
import { GroupManager } from './core/group-manager.js';
|
import { GroupManager } from './core/group-manager.js';
|
||||||
@@ -17,12 +22,16 @@ import { PushService } from './core/push-service.js';
|
|||||||
import { loadSecretBox } from './core/secret-box.js';
|
import { loadSecretBox } from './core/secret-box.js';
|
||||||
import { registerAuthRoutes } from './routes/auth.js';
|
import { registerAuthRoutes } from './routes/auth.js';
|
||||||
import { registerSessionRoutes } from './routes/sessions.js';
|
import { registerSessionRoutes } from './routes/sessions.js';
|
||||||
|
import { registerProjectRoutes } from './routes/projects.js';
|
||||||
import { registerRepoRoutes } from './routes/repos.js';
|
import { registerRepoRoutes } from './routes/repos.js';
|
||||||
import { registerGroupRoutes } from './routes/groups.js';
|
import { registerGroupRoutes } from './routes/groups.js';
|
||||||
import { registerWorktreeRoutes } from './routes/worktrees.js';
|
import { registerWorktreeRoutes } from './routes/worktrees.js';
|
||||||
|
import { registerGitRoutes } from './routes/git.js';
|
||||||
|
import { registerFileRoutes } from './routes/files.js';
|
||||||
import { registerPushRoutes } from './routes/push.js';
|
import { registerPushRoutes } from './routes/push.js';
|
||||||
import { registerSettingsRoutes } from './routes/settings.js';
|
import { registerSettingsRoutes } from './routes/settings.js';
|
||||||
import { registerFsRoutes } from './routes/fs.js';
|
import { registerFsRoutes } from './routes/fs.js';
|
||||||
|
import { FsWatcherService } from './core/fs-watcher.js';
|
||||||
import { registerAuditRoutes } from './routes/audit.js';
|
import { registerAuditRoutes } from './routes/audit.js';
|
||||||
import { registerDataRoutes } from './routes/data.js';
|
import { registerDataRoutes } from './routes/data.js';
|
||||||
import { registerWsGateway } from './ws/gateway.js';
|
import { registerWsGateway } from './ws/gateway.js';
|
||||||
@@ -69,10 +78,15 @@ export interface AppBundle {
|
|||||||
auth: AuthService;
|
auth: AuthService;
|
||||||
manager: PtyManager;
|
manager: PtyManager;
|
||||||
discovery: DiscoveryService;
|
discovery: DiscoveryService;
|
||||||
|
sessionArchive: SessionArchiveService;
|
||||||
repoDiscovery: RepoDiscoveryService;
|
repoDiscovery: RepoDiscoveryService;
|
||||||
worktrees: WorktreeManager;
|
worktrees: WorktreeManager;
|
||||||
groups: GroupManager;
|
groups: GroupManager;
|
||||||
push: PushService;
|
push: PushService;
|
||||||
|
fsWatcher: FsWatcherService;
|
||||||
|
settingsBus: SettingsBus;
|
||||||
|
gitCredentials: GitCredentialsManager;
|
||||||
|
clones: CloneManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildApp(config: Config, db: Db, serverVersion: string): AppBundle {
|
export function buildApp(config: Config, db: Db, serverVersion: string): AppBundle {
|
||||||
@@ -89,10 +103,20 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
projectsDir: config.claudeProjectsDir,
|
projectsDir: config.claudeProjectsDir,
|
||||||
sessionsDir: config.claudeSessionsDir,
|
sessionsDir: config.claudeSessionsDir,
|
||||||
});
|
});
|
||||||
const worktrees = new WorktreeManager(db, manager, discovery);
|
// Archivage auto des sessions terminées (P10). Démarré dans runDaemon() — jamais ici (tests).
|
||||||
|
const sessionArchive = new SessionArchiveService({ db });
|
||||||
|
// Watcher FS temps réel (P7) : armé à la demande sur les worktrees regardés via les commandes
|
||||||
|
// WS watch/unwatch. closeAll() au drain (libération des descripteurs).
|
||||||
|
const fsWatcher = new FsWatcherService();
|
||||||
|
const worktrees = new WorktreeManager(db, manager, discovery, fsWatcher);
|
||||||
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
|
// Démarré dans runDaemon() (jamais ici) → le scan ne tourne pas pendant les tests qui appellent buildApp.
|
||||||
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
|
const repoDiscovery = new RepoDiscoveryService(db, worktrees);
|
||||||
const groups = new GroupManager(db);
|
const groups = new GroupManager(db);
|
||||||
|
// P11 — bus de diffusion des réglages : PATCH /settings émet, la gateway relaie au topic 'settings'.
|
||||||
|
const settingsBus = new SettingsBus();
|
||||||
|
// P12 — services git distants : `box` (SecretBox) câblé ici pour chiffrer les secrets des credentials.
|
||||||
|
const gitCredentials = new GitCredentialsManager(db, box);
|
||||||
|
const clones = new CloneManager(db, worktrees, gitCredentials);
|
||||||
|
|
||||||
// En-têtes de sécurité sur toute réponse + no-store sur les réponses sensibles (API/WS).
|
// En-têtes de sécurité sur toute réponse + no-store sur les réponses sensibles (API/WS).
|
||||||
// onSend DOIT retourner le payload (sinon Fastify vide la réponse).
|
// onSend DOIT retourner le payload (sinon Fastify vide la réponse).
|
||||||
@@ -169,19 +193,23 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
});
|
});
|
||||||
|
|
||||||
registerAuthRoutes(app, auth, limiter, serverVersion, db);
|
registerAuthRoutes(app, auth, limiter, serverVersion, db);
|
||||||
registerSessionRoutes(app, manager, discovery, db);
|
registerSessionRoutes(app, manager, discovery, sessionArchive, db);
|
||||||
|
registerProjectRoutes(app, manager, db);
|
||||||
registerRepoRoutes(app, worktrees, db);
|
registerRepoRoutes(app, worktrees, db);
|
||||||
registerGroupRoutes(app, groups, db, worktrees, manager);
|
registerGroupRoutes(app, groups, db, worktrees, manager);
|
||||||
registerWorktreeRoutes(app, worktrees);
|
registerWorktreeRoutes(app, worktrees, db);
|
||||||
|
registerGitRoutes(app, worktrees, db);
|
||||||
|
registerFileRoutes(app, worktrees, db);
|
||||||
registerPushRoutes(app, push, db);
|
registerPushRoutes(app, push, db);
|
||||||
registerSettingsRoutes(app, db, config, serverVersion, push);
|
registerSettingsRoutes(app, db, config, serverVersion, push, settingsBus);
|
||||||
|
registerGitConnectionRoutes(app, gitCredentials, clones, db);
|
||||||
registerFsRoutes(app);
|
registerFsRoutes(app);
|
||||||
registerAuditRoutes(app, db);
|
registerAuditRoutes(app, db);
|
||||||
registerDataRoutes(app, db, auth);
|
registerDataRoutes(app, db, auth);
|
||||||
// La route websocket doit être déclarée APRÈS le chargement du plugin (contexte
|
// 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) => {
|
void app.register(async (scoped) => {
|
||||||
registerWsGateway(scoped, manager, discovery, worktrees, groups, serverVersion);
|
registerWsGateway(scoped, manager, discovery, sessionArchive, worktrees, groups, settingsBus, clones, serverVersion);
|
||||||
});
|
});
|
||||||
|
|
||||||
// SPA buildée embarquée dans le paquet npm (public/) — absente en dev (vite dev sert le front)
|
// SPA buildée embarquée dans le paquet npm (public/) — absente en dev (vite dev sert le front)
|
||||||
@@ -196,5 +224,5 @@ export function buildApp(config: Config, db: Db, serverVersion: string): AppBund
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { app, auth, manager, discovery, repoDiscovery, worktrees, groups, push };
|
return { app, auth, manager, discovery, sessionArchive, repoDiscovery, worktrees, groups, push, fsWatcher, settingsBus, gitCredentials, clones };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -122,8 +122,13 @@ function quoteIfNeeded(token: string): string {
|
|||||||
return /\s/.test(token) ? `"${token}"` : token;
|
return /\s/.test(token) ? `"${token}"` : token;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[] }): string {
|
export function renderSystemdUnit(input: { exec: string; scriptArgs: string[]; pathEnv?: string | undefined }): string {
|
||||||
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
|
const execStart = [input.exec, ...input.scriptArgs].map(quoteIfNeeded).join(' ');
|
||||||
|
// Un service systemd user démarre avec un PATH minimal (typiquement /usr/bin:/bin…) qui n'inclut
|
||||||
|
// PAS ~/.local/bin ni le bin npm/nvm où vit le CLI `claude` → resolveClaudeBin() (`which claude`)
|
||||||
|
// échouerait. On fige donc le PATH de l'environnement d'installation, où `claude` est résolvable.
|
||||||
|
// Doubles quotes systemd : tolèrent un chemin du PATH contenant des espaces.
|
||||||
|
const pathLine = input.pathEnv ? `\nEnvironment="PATH=${input.pathEnv}"` : '';
|
||||||
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
|
// KillSignal=SIGTERM + TimeoutStopSec=10 collent au drain de runDaemon (SIGTERM → drain 1s → close).
|
||||||
return `[Unit]
|
return `[Unit]
|
||||||
Description=Arboretum — git worktree & Claude Code dashboard
|
Description=Arboretum — git worktree & Claude Code dashboard
|
||||||
@@ -136,7 +141,7 @@ Restart=on-failure
|
|||||||
RestartSec=5
|
RestartSec=5
|
||||||
KillSignal=SIGTERM
|
KillSignal=SIGTERM
|
||||||
TimeoutStopSec=10
|
TimeoutStopSec=10
|
||||||
Environment=NODE_ENV=production
|
Environment=NODE_ENV=production${pathLine}
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=default.target
|
WantedBy=default.target
|
||||||
@@ -148,8 +153,14 @@ export function renderLaunchAgentPlist(input: {
|
|||||||
programArguments: string[];
|
programArguments: string[];
|
||||||
stdoutPath: string;
|
stdoutPath: string;
|
||||||
stderrPath: string;
|
stderrPath: string;
|
||||||
|
pathEnv?: string | undefined;
|
||||||
}): string {
|
}): string {
|
||||||
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
|
const args = input.programArguments.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n');
|
||||||
|
// launchd démarre un LaunchAgent avec un PATH minimal qui n'inclut pas ~/.local/bin ni le bin
|
||||||
|
// npm/nvm où vit le CLI `claude` → resolveClaudeBin() échouerait. On fige le PATH d'installation.
|
||||||
|
const pathEntry = input.pathEnv
|
||||||
|
? `\n <key>PATH</key>\n <string>${xmlEscape(input.pathEnv)}</string>`
|
||||||
|
: '';
|
||||||
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
|
// KeepAlive/SuccessfulExit=false ≈ Restart=on-failure (ne relance pas après un drain volontaire).
|
||||||
return `<?xml version="1.0" encoding="UTF-8"?>
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
@@ -175,7 +186,7 @@ ${args}
|
|||||||
<key>EnvironmentVariables</key>
|
<key>EnvironmentVariables</key>
|
||||||
<dict>
|
<dict>
|
||||||
<key>NODE_ENV</key>
|
<key>NODE_ENV</key>
|
||||||
<string>production</string>
|
<string>production</string>${pathEntry}
|
||||||
</dict>
|
</dict>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
@@ -258,9 +269,12 @@ export async function runInstall(argv: string[]): Promise<void> {
|
|||||||
const serviceArgs = buildServiceArgs(flags);
|
const serviceArgs = buildServiceArgs(flags);
|
||||||
const { exec, args: binArgs } = resolveBin(flags);
|
const { exec, args: binArgs } = resolveBin(flags);
|
||||||
const scriptArgs = [...binArgs, ...serviceArgs];
|
const scriptArgs = [...binArgs, ...serviceArgs];
|
||||||
|
// PATH de l'environnement d'installation (shell interactif où `claude` est résolvable) : on le
|
||||||
|
// fige dans l'unit/plist car systemd/launchd démarrent le service avec un PATH minimal.
|
||||||
|
const pathEnv = process.env.PATH;
|
||||||
|
|
||||||
if (platform === 'linux') {
|
if (platform === 'linux') {
|
||||||
const unit = renderSystemdUnit({ exec, scriptArgs });
|
const unit = renderSystemdUnit({ exec, scriptArgs, pathEnv });
|
||||||
const unitPath = systemdUnitPath();
|
const unitPath = systemdUnitPath();
|
||||||
if (flags.dryRun) {
|
if (flags.dryRun) {
|
||||||
console.log(`# ${unitPath}\n${unit}\n# commands:`);
|
console.log(`# ${unitPath}\n${unit}\n# commands:`);
|
||||||
@@ -295,6 +309,7 @@ export async function runInstall(argv: string[]): Promise<void> {
|
|||||||
programArguments,
|
programArguments,
|
||||||
stdoutPath: logs.out,
|
stdoutPath: logs.out,
|
||||||
stderrPath: logs.err,
|
stderrPath: logs.err,
|
||||||
|
pathEnv,
|
||||||
});
|
});
|
||||||
const plistPath = launchAgentPlistPath(flags.label);
|
const plistPath = launchAgentPlistPath(flags.label);
|
||||||
const uid = process.getuid?.() ?? 0;
|
const uid = process.getuid?.() ?? 0;
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ export interface Config {
|
|||||||
/** origins supplémentaires autorisées (ex. https://machine.tailnet.ts.net) */
|
/** origins supplémentaires autorisées (ex. https://machine.tailnet.ts.net) */
|
||||||
allowedOrigins: string[];
|
allowedOrigins: string[];
|
||||||
printToken: boolean;
|
printToken: boolean;
|
||||||
|
/** racine effective de l'install Claude (~/.claude par défaut, --claude-home, ou réglage claude_home). */
|
||||||
|
claudeHome: string;
|
||||||
|
/** true si --claude-home a été passé explicitement → a priorité sur le réglage claude_home. */
|
||||||
|
claudeHomeFromFlag: boolean;
|
||||||
/** ~/.claude/projects (transcripts JSONL) — surchargeable via --claude-home (tests). */
|
/** ~/.claude/projects (transcripts JSONL) — surchargeable via --claude-home (tests). */
|
||||||
claudeProjectsDir: string;
|
claudeProjectsDir: string;
|
||||||
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
|
/** ~/.claude/sessions (registre des sessions CLI vivantes). */
|
||||||
@@ -61,7 +65,8 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
} catch {
|
} catch {
|
||||||
/* FS sans permissions POSIX : ignoré, cf. avertissement dans db.openDb */
|
/* FS sans permissions POSIX : ignoré, cf. avertissement dans db.openDb */
|
||||||
}
|
}
|
||||||
const claudeHome = values['claude-home'] ?? join(homedir(), '.claude');
|
const claudeHomeFlag = values['claude-home'];
|
||||||
|
const claudeHome = claudeHomeFlag ?? join(homedir(), '.claude');
|
||||||
return {
|
return {
|
||||||
port: Number(values.port),
|
port: Number(values.port),
|
||||||
bind,
|
bind,
|
||||||
@@ -69,6 +74,8 @@ export function loadConfig(argv = process.argv.slice(2)): Config {
|
|||||||
dataDir,
|
dataDir,
|
||||||
allowedOrigins: values['allow-origin'] ?? [],
|
allowedOrigins: values['allow-origin'] ?? [],
|
||||||
printToken: values['print-token'] ?? false,
|
printToken: values['print-token'] ?? false,
|
||||||
|
claudeHome,
|
||||||
|
claudeHomeFromFlag: claudeHomeFlag !== undefined,
|
||||||
claudeProjectsDir: join(claudeHome, 'projects'),
|
claudeProjectsDir: join(claudeHome, 'projects'),
|
||||||
claudeSessionsDir: join(claudeHome, 'sessions'),
|
claudeSessionsDir: join(claudeHome, 'sessions'),
|
||||||
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
|
vapidContact: values['vapid-contact'] ?? 'mailto:arboretum@localhost',
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { accessSync, constants } from 'node:fs';
|
||||||
|
|
||||||
export interface SpawnSpec {
|
export interface SpawnSpec {
|
||||||
file: string;
|
file: string;
|
||||||
@@ -12,22 +13,74 @@ export interface SpawnOptions {
|
|||||||
resume?: { claudeSessionId: string; fork?: boolean };
|
resume?: { claudeSessionId: string; fork?: boolean };
|
||||||
/** répertoires supplémentaires à relier dans une seule session (P6) : `--add-dir <path>` répété. */
|
/** répertoires supplémentaires à relier dans une seule session (P6) : `--add-dir <path>` répété. */
|
||||||
addDirs?: string[];
|
addDirs?: string[];
|
||||||
|
/** chemin explicite du binaire `claude` (réglage UI) ; sinon résolution via PATH (`which`). */
|
||||||
|
claudeBinPath?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Diagnostic de résolution du binaire `claude` (exposé en lecture dans Réglages). */
|
||||||
|
export interface ClaudeBinDiagnostic {
|
||||||
|
/** chemin résolu du binaire, ou null si introuvable. */
|
||||||
|
path: string | null;
|
||||||
|
/** 'configured' = réglage explicite ; 'path' = trouvé via PATH ; null = introuvable. */
|
||||||
|
source: 'configured' | 'path' | null;
|
||||||
|
/** true si le binaire est présent et exécutable. */
|
||||||
|
ok: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
let cachedClaudeBin: string | null = null;
|
let cachedClaudeBin: string | null = null;
|
||||||
|
|
||||||
export function resolveClaudeBin(): string {
|
/** Recherche `claude` dans le PATH (sans throw). null si absent. */
|
||||||
if (cachedClaudeBin) return cachedClaudeBin;
|
function findClaudeOnPath(): string | null {
|
||||||
try {
|
try {
|
||||||
cachedClaudeBin = execFileSync('which', ['claude'], { encoding: 'utf8' }).trim();
|
return execFileSync('which', ['claude'], { encoding: 'utf8' }).trim() || null;
|
||||||
} catch {
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExecutable(path: string): boolean {
|
||||||
|
try {
|
||||||
|
accessSync(path, constants.X_OK);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout le binaire `claude`. Si `configuredPath` est fourni (réglage UI), il est utilisé tel quel
|
||||||
|
* — validé exécutable, message clair sinon — et JAMAIS mis en cache (modifiable à chaud). Sinon :
|
||||||
|
* `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`).
|
||||||
|
*/
|
||||||
|
export function resolveClaudeBin(configuredPath?: string | null): string {
|
||||||
|
if (configuredPath) {
|
||||||
|
if (!isExecutable(configuredPath)) {
|
||||||
|
throw new Error(`Configured Claude CLI path is not executable: ${configuredPath}`);
|
||||||
|
}
|
||||||
|
return configuredPath;
|
||||||
|
}
|
||||||
|
if (cachedClaudeBin) return cachedClaudeBin;
|
||||||
|
const found = findClaudeOnPath();
|
||||||
|
if (!found) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'Claude Code CLI not found in PATH. Install it first: https://code.claude.com/docs/en/quickstart',
|
'Claude Code CLI not found in PATH. Install it first: https://code.claude.com/docs/en/quickstart',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
cachedClaudeBin = found;
|
||||||
return cachedClaudeBin;
|
return cachedClaudeBin;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Diagnostic non-throwing pour l'UI (Réglages) : recalculé à chaque appel, jamais caché. */
|
||||||
|
export function diagnoseClaudeBin(configuredPath?: string | null): ClaudeBinDiagnostic {
|
||||||
|
if (configuredPath) {
|
||||||
|
return { path: configuredPath, source: 'configured', ok: isExecutable(configuredPath) };
|
||||||
|
}
|
||||||
|
const found = findClaudeOnPath();
|
||||||
|
return found ? { path: found, source: 'path', ok: true } : { path: null, source: null, ok: false };
|
||||||
|
}
|
||||||
|
|
||||||
/** Module volontairement abstrait : le plan B « BYO API key / Agent SDK » se brancherait ici. */
|
/** Module volontairement abstrait : le plan B « BYO API key / Agent SDK » se brancherait ici. */
|
||||||
export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
||||||
const env: NodeJS.ProcessEnv = {
|
const env: NodeJS.ProcessEnv = {
|
||||||
@@ -46,5 +99,5 @@ export function buildSpawnSpec(opts: SpawnOptions): SpawnSpec {
|
|||||||
}
|
}
|
||||||
// Session de groupe : relie plusieurs repos/worktrees dans une seule session (P6).
|
// Session de groupe : relie plusieurs repos/worktrees dans une seule session (P6).
|
||||||
for (const dir of opts.addDirs ?? []) args.push('--add-dir', dir);
|
for (const dir of opts.addDirs ?? []) args.push('--add-dir', dir);
|
||||||
return { file: resolveClaudeBin(), args, env };
|
return { file: resolveClaudeBin(opts.claudeBinPath), args, env };
|
||||||
}
|
}
|
||||||
|
|||||||
63
packages/server/src/core/claude-settings.ts
Normal file
63
packages/server/src/core/claude-settings.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
// Réglages liés au CLI Claude, persistés dans la table `settings` (clé/valeur), modifiables via
|
||||||
|
// l'onglet Réglages. Frontière de sécurité identique à scan-settings : clés NON sensibles, écrites
|
||||||
|
// uniquement via l'allow-list du PATCH /api/v1/settings et les validateurs ci-dessous.
|
||||||
|
//
|
||||||
|
// Motivation : un service systemd/launchd démarre avec un PATH minimal qui n'inclut pas ~/.local/bin
|
||||||
|
// (où vit le binaire `claude`) → `which claude` échoue. Plutôt que de bricoler le PATH du service,
|
||||||
|
// l'utilisateur peut pointer explicitement le binaire ici (effet : prochaine session, sans redémarrage).
|
||||||
|
import { accessSync, constants, statSync } from 'node:fs';
|
||||||
|
import { getSetting } from '../db/index.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { isSafeAbsolutePath } from './git.js';
|
||||||
|
|
||||||
|
/** Chemin explicite du binaire `claude` (override de la résolution via PATH). */
|
||||||
|
export const CLAUDE_BIN_PATH_KEY = 'claude_bin_path';
|
||||||
|
/** Override de la racine ~/.claude (transcripts + registre des sessions). */
|
||||||
|
export const CLAUDE_HOME_KEY = 'claude_home';
|
||||||
|
|
||||||
|
/** Chemin configuré du binaire `claude`, ou null si non défini (⇒ auto-détection via PATH). */
|
||||||
|
export function readClaudeBinPath(db: Db): string | null {
|
||||||
|
const raw = getSetting(db, CLAUDE_BIN_PATH_KEY)?.trim();
|
||||||
|
return raw ? raw : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Racine ~/.claude configurée, ou null si non défini (⇒ défaut/flag). */
|
||||||
|
export function readClaudeHome(db: Db): string | null {
|
||||||
|
const raw = getSetting(db, CLAUDE_HOME_KEY)?.trim();
|
||||||
|
return raw ? raw : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide un chemin de binaire `claude`. Retourne `''` pour réinitialiser (auto-détection), le chemin
|
||||||
|
* normalisé s'il est absolu ET pointe vers un fichier exécutable, ou `null` si invalide (⇒ 400).
|
||||||
|
*/
|
||||||
|
export function normalizeClaudeBinPath(raw: unknown): string | null {
|
||||||
|
if (typeof raw !== 'string') return null;
|
||||||
|
const p = raw.trim();
|
||||||
|
if (p === '') return '';
|
||||||
|
if (!isSafeAbsolutePath(p)) return null;
|
||||||
|
try {
|
||||||
|
if (!statSync(p).isFile()) return null;
|
||||||
|
accessSync(p, constants.X_OK);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide une racine ~/.claude. Retourne `''` pour réinitialiser (défaut), le chemin normalisé s'il
|
||||||
|
* est absolu ET pointe vers un répertoire existant, ou `null` si invalide (⇒ 400).
|
||||||
|
*/
|
||||||
|
export function normalizeClaudeHome(raw: unknown): string | null {
|
||||||
|
if (typeof raw !== 'string') return null;
|
||||||
|
const p = raw.trim();
|
||||||
|
if (p === '') return '';
|
||||||
|
if (!isSafeAbsolutePath(p)) return null;
|
||||||
|
try {
|
||||||
|
if (!statSync(p).isDirectory()) return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
118
packages/server/src/core/clone-manager.ts
Normal file
118
packages/server/src/core/clone-manager.ts
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
// Orchestration des clones (P12). Asynchrone : POST /repos/clone répond 202 avec un operationId,
|
||||||
|
// la progression est poussée en WS (topic 'clones') et lisible en REST (survit au refresh). À la fin,
|
||||||
|
// le repo cloné est auto-enregistré via WorktreeManager.addRepo (réutilise unicité/validation/event).
|
||||||
|
// `dest` est strictement confiné SOUS une racine de scan + non existant (mkdir implicite par git).
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { rm, stat } from 'node:fs/promises';
|
||||||
|
import { resolve, sep } from 'node:path';
|
||||||
|
import type { CloneOperation, GitService } from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { isSafeAbsolutePath, cloneRepo } from './git.js';
|
||||||
|
import { readScanRoots } from './scan-settings.js';
|
||||||
|
import { withGitAuth } from './git-auth.js';
|
||||||
|
import type { GitAuth } from './git-clients/index.js';
|
||||||
|
import type { GitCredentialsManager } from './git-credentials.js';
|
||||||
|
import type { WorktreeManager } from './worktree-manager.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
|
||||||
|
export interface CloneManagerEvents {
|
||||||
|
clone_update: [CloneOperation];
|
||||||
|
}
|
||||||
|
|
||||||
|
function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
|
||||||
|
return Object.assign(new Error(message), { statusCode, code });
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CloneManager extends EventEmitter<CloneManagerEvents> {
|
||||||
|
private readonly ops = new Map<string, CloneOperation>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly db: Db,
|
||||||
|
private readonly worktrees: WorktreeManager,
|
||||||
|
private readonly credentials: GitCredentialsManager,
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
get(id: string): CloneOperation | null {
|
||||||
|
return this.ops.get(id) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Démarre un clone (validation synchrone du dest → throw 4xx ; clone asynchrone ensuite).
|
||||||
|
* Retourne l'operationId à suivre via WS/REST. `actor` pour l'audit.
|
||||||
|
*/
|
||||||
|
async start(opts: { credentialId: string; remoteUrl: string; dest: string }, actor: string): Promise<string> {
|
||||||
|
const dest = resolve(opts.dest);
|
||||||
|
if (!isSafeAbsolutePath(dest)) throw httpError(400, 'BAD_REQUEST', 'dest must be an absolute, normalized path');
|
||||||
|
if (typeof opts.remoteUrl !== 'string' || opts.remoteUrl.trim() === '') throw httpError(400, 'BAD_REQUEST', 'remoteUrl is required');
|
||||||
|
const ctx = this.credentials.authContext(opts.credentialId);
|
||||||
|
if (!ctx) throw httpError(404, 'NOT_FOUND', 'No usable credential with this id');
|
||||||
|
|
||||||
|
// Confinement : dest DOIT être sous une racine de scan configurée (jamais d'écriture arbitraire).
|
||||||
|
const roots = readScanRoots(this.db);
|
||||||
|
if (roots.length === 0) throw httpError(400, 'NO_SCAN_ROOT', 'Configure a scan folder first (Settings → Discovery)');
|
||||||
|
const underRoot = roots.some((r) => {
|
||||||
|
const root = resolve(r);
|
||||||
|
return dest === root || dest.startsWith(root + sep);
|
||||||
|
});
|
||||||
|
if (!underRoot) throw httpError(400, 'OUTSIDE_SCAN_ROOT', 'dest must be inside a configured scan folder');
|
||||||
|
|
||||||
|
// Le parent doit exister ; le dest ne doit pas exister (git clone le crée).
|
||||||
|
const parent = dest.slice(0, dest.lastIndexOf(sep)) || sep;
|
||||||
|
try {
|
||||||
|
const st = await stat(parent);
|
||||||
|
if (!st.isDirectory()) throw httpError(400, 'BAD_DEST', 'Parent of dest is not a directory');
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as { statusCode?: number }).statusCode) throw err;
|
||||||
|
throw httpError(404, 'NOT_FOUND', `Parent directory does not exist: ${parent}`);
|
||||||
|
}
|
||||||
|
if (await stat(dest).then(() => true).catch(() => false)) throw httpError(409, 'DEST_EXISTS', `Destination already exists: ${dest}`);
|
||||||
|
|
||||||
|
const id = randomUUID();
|
||||||
|
const op: CloneOperation = { id, state: 'pending', progress: null, phase: null, error: null, repoId: null, dest };
|
||||||
|
this.ops.set(id, op);
|
||||||
|
recordAudit(this.db, { actor, action: 'repo.clone', resourceId: id, details: { service: ctx.service, dest } });
|
||||||
|
// Lancement asynchrone (ne bloque pas la réponse 202).
|
||||||
|
void this.run(op, opts.remoteUrl, opts.credentialId, ctx);
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private update(op: CloneOperation, patch: Partial<CloneOperation>): void {
|
||||||
|
Object.assign(op, patch);
|
||||||
|
this.emit('clone_update', { ...op });
|
||||||
|
}
|
||||||
|
|
||||||
|
private async run(
|
||||||
|
op: CloneOperation,
|
||||||
|
remoteUrl: string,
|
||||||
|
credentialId: string,
|
||||||
|
ctx: { service: GitService; baseUrl: string | null; auth: GitAuth },
|
||||||
|
): Promise<void> {
|
||||||
|
this.update(op, { state: 'running' });
|
||||||
|
let lastPct = -10;
|
||||||
|
const onProgress = (p: { phase: string; percent: number | null }): void => {
|
||||||
|
// throttle : on ne pousse que sur changement de phase ou +3% pour éviter le flood WS.
|
||||||
|
if (p.percent == null || p.percent - lastPct >= 3 || p.phase !== op.phase) {
|
||||||
|
lastPct = p.percent ?? lastPct;
|
||||||
|
this.update(op, { phase: p.phase, progress: p.percent });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
await withGitAuth(ctx.service, ctx.auth, (env) =>
|
||||||
|
cloneRepo({ url: remoteUrl, dest: op.dest, env, onProgress }),
|
||||||
|
);
|
||||||
|
// auto-enregistrement du repo cloné + métadonnées de provenance.
|
||||||
|
const repo = await this.worktrees.addRepo({ path: op.dest });
|
||||||
|
this.db
|
||||||
|
.prepare('UPDATE repos SET remote_url = ?, git_service = ?, credential_id = ? WHERE id = ?')
|
||||||
|
.run(remoteUrl, ctx.service, credentialId, repo.id);
|
||||||
|
this.update(op, { state: 'done', progress: 100, repoId: repo.id });
|
||||||
|
} catch (err) {
|
||||||
|
// nettoyage du clone partiel (best-effort).
|
||||||
|
await rm(op.dest, { recursive: true, force: true }).catch(() => {});
|
||||||
|
this.update(op, { state: 'error', error: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
199
packages/server/src/core/fs-watcher.ts
Normal file
199
packages/server/src/core/fs-watcher.ts
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
// Watcher FS des worktrees ACTIFS (regardés par un client OU portant une session vivante).
|
||||||
|
// Émet un signal débouncé `worktree_fs_change` que le WorktreeManager traduit en recalcul du
|
||||||
|
// statut git + broadcast WS. Pool LRU borné + refcount pour ne jamais épuiser les descripteurs :
|
||||||
|
// un worktree n'est watché que tant qu'il est observé/épinglé, et la taille totale est plafonnée.
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { resolve, sep, join } from 'node:path';
|
||||||
|
import chokidar, { type FSWatcher } from 'chokidar';
|
||||||
|
import { resolveGitDir } from './git.js';
|
||||||
|
|
||||||
|
const DEFAULT_MAX_WATCHERS = 32;
|
||||||
|
const DEBOUNCE_MS = 200;
|
||||||
|
|
||||||
|
export interface FsWatcherEvents {
|
||||||
|
/** le contenu d'un worktree surveillé a changé (édition, staging, checkout externe…). */
|
||||||
|
worktree_fs_change: [{ repoId: string; path: string }];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface WatchEntry {
|
||||||
|
repoId: string;
|
||||||
|
path: string;
|
||||||
|
watcher: FSWatcher;
|
||||||
|
/** nombre de clients qui « regardent » ce worktree. */
|
||||||
|
refCount: number;
|
||||||
|
/** nombre de sessions vivantes épinglant ce worktree. */
|
||||||
|
sessionPins: number;
|
||||||
|
/** épingle « permanente » (checkout principal d'un repo enregistré) — jamais évincée (P11). */
|
||||||
|
repoPins: number;
|
||||||
|
lastUsed: number;
|
||||||
|
debounce: NodeJS.Timeout | null;
|
||||||
|
/** résolue quand chokidar a fini son scan initial (les events deviennent fiables). */
|
||||||
|
ready: Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ignore tout sous `.git/` SAUF `HEAD` et `index` (⇒ on détecte le `git checkout` externe et le
|
||||||
|
* staging) ainsi que `node_modules`. chokidar n'ignore pas le dossier `.git` lui-même afin de
|
||||||
|
* pouvoir descendre jusqu'à `HEAD`/`index`, mais saute ses sous-dossiers volumineux (objects…).
|
||||||
|
*/
|
||||||
|
export function isIgnoredPath(p: string): boolean {
|
||||||
|
if (p.includes(`${sep}node_modules${sep}`) || p.endsWith(`${sep}node_modules`)) return true;
|
||||||
|
if (p.includes(`${sep}.git${sep}`)) {
|
||||||
|
return !(p.endsWith(`${sep}HEAD`) || p.endsWith(`${sep}index`));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FsWatcherOptions {
|
||||||
|
maxWatchers?: number;
|
||||||
|
debounceMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class FsWatcherService extends EventEmitter<FsWatcherEvents> {
|
||||||
|
private readonly entries = new Map<string, WatchEntry>();
|
||||||
|
private readonly maxWatchers: number;
|
||||||
|
private readonly debounceMs: number;
|
||||||
|
|
||||||
|
constructor(opts: FsWatcherOptions = {}) {
|
||||||
|
super();
|
||||||
|
this.maxWatchers = opts.maxWatchers ?? DEFAULT_MAX_WATCHERS;
|
||||||
|
this.debounceMs = opts.debounceMs ?? DEBOUNCE_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private key(repoId: string, path: string): string {
|
||||||
|
return `${repoId}\0${resolve(path)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un client commence à observer un worktree (vue IDE ouverte). */
|
||||||
|
watch(repoId: string, path: string): void {
|
||||||
|
const e = this.ensure(repoId, path);
|
||||||
|
e.refCount++;
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Un client cesse d'observer ; le watcher reste (idle) jusqu'à éviction LRU. */
|
||||||
|
unwatch(repoId: string, path: string): void {
|
||||||
|
const e = this.entries.get(this.key(repoId, path));
|
||||||
|
if (!e) return;
|
||||||
|
e.refCount = Math.max(0, e.refCount - 1);
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Épingle un worktree tant qu'une session y est vivante (jamais évincé). */
|
||||||
|
pinSession(repoId: string, path: string): void {
|
||||||
|
const e = this.ensure(repoId, path);
|
||||||
|
e.sessionPins++;
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
unpinSession(repoId: string, path: string): void {
|
||||||
|
const e = this.entries.get(this.key(repoId, path));
|
||||||
|
if (!e) return;
|
||||||
|
e.sessionPins = Math.max(0, e.sessionPins - 1);
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Épingle en PERMANENCE le checkout principal d'un repo enregistré (P11) : ainsi un `git checkout`
|
||||||
|
* en CLI sur le principal est détecté et rediffusé sans qu'aucun client n'ait « regardé » ce
|
||||||
|
* worktree. Idempotent (un seul pin par repo+path conservé). Jamais évincé par la LRU.
|
||||||
|
*/
|
||||||
|
pinRepo(repoId: string, path: string): void {
|
||||||
|
const e = this.ensure(repoId, path);
|
||||||
|
e.repoPins = 1; // idempotent : on ne cumule pas (un seul checkout principal par repo)
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
unpinRepo(repoId: string, path: string): void {
|
||||||
|
const e = this.entries.get(this.key(repoId, path));
|
||||||
|
if (!e) return;
|
||||||
|
e.repoPins = 0;
|
||||||
|
e.lastUsed = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de watchers actifs (test/diagnostic). */
|
||||||
|
size(): number {
|
||||||
|
return this.entries.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
isWatching(repoId: string, path: string): boolean {
|
||||||
|
return this.entries.has(this.key(repoId, path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Résout quand le watcher de ce worktree a fini son scan initial (utile aux tests). */
|
||||||
|
whenReady(repoId: string, path: string): Promise<void> {
|
||||||
|
return this.entries.get(this.key(repoId, path))?.ready ?? Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensure(repoId: string, path: string): WatchEntry {
|
||||||
|
const key = this.key(repoId, path);
|
||||||
|
const existing = this.entries.get(key);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
const abs = resolve(path);
|
||||||
|
const watcher = chokidar.watch(abs, {
|
||||||
|
ignored: (p: string) => isIgnoredPath(p),
|
||||||
|
ignoreInitial: true,
|
||||||
|
// coalesce les écritures rapides (build, génération) avant d'émettre.
|
||||||
|
awaitWriteFinish: { stabilityThreshold: 120, pollInterval: 40 },
|
||||||
|
});
|
||||||
|
let resolveReady: () => void = () => {};
|
||||||
|
const ready = new Promise<void>((r) => (resolveReady = r));
|
||||||
|
watcher.once('ready', () => resolveReady());
|
||||||
|
const entry: WatchEntry = { repoId, path: abs, watcher, refCount: 0, sessionPins: 0, repoPins: 0, lastUsed: Date.now(), debounce: null, ready };
|
||||||
|
const onChange = (): void => this.schedule(entry);
|
||||||
|
watcher.on('add', onChange).on('change', onChange).on('unlink', onChange).on('addDir', onChange).on('unlinkDir', onChange);
|
||||||
|
this.entries.set(key, entry);
|
||||||
|
|
||||||
|
// Worktree LIÉ : HEAD/index vivent hors du worktree (dans .git/worktrees/<n>). On les ajoute
|
||||||
|
// explicitement pour capter un changement de branche externe (git checkout en CLI).
|
||||||
|
void resolveGitDir(abs).then((gitDir) => {
|
||||||
|
if (!gitDir || !this.entries.has(key)) return;
|
||||||
|
if (gitDir === join(abs, '.git') || gitDir.startsWith(abs + sep)) return; // déjà couvert
|
||||||
|
watcher.add([join(gitDir, 'HEAD'), join(gitDir, 'index')]);
|
||||||
|
}).catch(() => {});
|
||||||
|
|
||||||
|
this.evictIfNeeded();
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
private schedule(entry: WatchEntry): void {
|
||||||
|
if (entry.debounce) clearTimeout(entry.debounce);
|
||||||
|
entry.debounce = setTimeout(() => {
|
||||||
|
entry.debounce = null;
|
||||||
|
entry.lastUsed = Date.now();
|
||||||
|
this.emit('worktree_fs_change', { repoId: entry.repoId, path: entry.path });
|
||||||
|
}, this.debounceMs);
|
||||||
|
entry.debounce.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ferme les watchers idle (refCount===0 && sessionPins===0) les moins récents au-delà du plafond. */
|
||||||
|
private evictIfNeeded(): void {
|
||||||
|
if (this.entries.size <= this.maxWatchers) return;
|
||||||
|
const idle = [...this.entries.entries()]
|
||||||
|
.filter(([, e]) => e.refCount === 0 && e.sessionPins === 0 && e.repoPins === 0)
|
||||||
|
.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
|
||||||
|
for (const [key, e] of idle) {
|
||||||
|
if (this.entries.size <= this.maxWatchers) break;
|
||||||
|
this.close(key, e);
|
||||||
|
}
|
||||||
|
// Si tout est actif (reffé/épinglé), on dépasse le plafond volontairement : un worktree
|
||||||
|
// explicitement observé ne doit jamais perdre son temps réel.
|
||||||
|
}
|
||||||
|
|
||||||
|
private close(key: string, e: WatchEntry): void {
|
||||||
|
if (e.debounce) clearTimeout(e.debounce);
|
||||||
|
void e.watcher.close().catch(() => {});
|
||||||
|
this.entries.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Libère tous les descripteurs (drain SIGTERM/SIGINT). */
|
||||||
|
async closeAll(): Promise<void> {
|
||||||
|
const all = [...this.entries.entries()];
|
||||||
|
this.entries.clear();
|
||||||
|
await Promise.all(all.map(([, e]) => {
|
||||||
|
if (e.debounce) clearTimeout(e.debounce);
|
||||||
|
return e.watcher.close().catch(() => {});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
40
packages/server/src/core/git-auth.ts
Normal file
40
packages/server/src/core/git-auth.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
// Préparation d'un environnement d'authentification git ÉPHÉMÈRE (P12). HTTPS (pat/app_password) :
|
||||||
|
// les identifiants sont fournis via GIT_ASKPASS (script 0o700 lisant deux variables d'env), JAMAIS
|
||||||
|
// dans l'URL ni dans `.git/config`. GIT_TERMINAL_PROMPT=0 (pas d'invite bloquante). Le script est
|
||||||
|
// supprimé en `finally` ; le secret ne transite que par l'env du process enfant (jamais loggé).
|
||||||
|
import { mkdtemp, writeFile, rm, chmod } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import type { GitService } from '@arboretum/shared';
|
||||||
|
import type { GitAuth } from './git-clients/index.js';
|
||||||
|
|
||||||
|
// Identité HTTPS par défaut quand l'utilisateur n'a pas fourni de username (token-as-password).
|
||||||
|
const SERVICE_DEFAULT_USER: Record<GitService, string> = { github: 'x-access-token', gitlab: 'oauth2', gitea: 'oauth2' };
|
||||||
|
|
||||||
|
export async function withGitAuth<T>(
|
||||||
|
service: GitService,
|
||||||
|
auth: GitAuth,
|
||||||
|
fn: (env: NodeJS.ProcessEnv) => Promise<T>,
|
||||||
|
): Promise<T> {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), 'arb-gitauth-'));
|
||||||
|
const askpass = join(dir, 'askpass.sh');
|
||||||
|
const user = auth.username || SERVICE_DEFAULT_USER[service];
|
||||||
|
await writeFile(
|
||||||
|
askpass,
|
||||||
|
"#!/bin/sh\ncase \"$1\" in\n Username*) printf '%s' \"$ARB_GIT_USER\" ;;\n *) printf '%s' \"$ARB_GIT_PASS\" ;;\nesac\n",
|
||||||
|
{ mode: 0o700 },
|
||||||
|
);
|
||||||
|
await chmod(askpass, 0o700);
|
||||||
|
const env: NodeJS.ProcessEnv = {
|
||||||
|
...process.env,
|
||||||
|
GIT_ASKPASS: askpass,
|
||||||
|
GIT_TERMINAL_PROMPT: '0',
|
||||||
|
ARB_GIT_USER: user,
|
||||||
|
ARB_GIT_PASS: auth.secret,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
return await fn(env);
|
||||||
|
} finally {
|
||||||
|
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
156
packages/server/src/core/git-clients/index.ts
Normal file
156
packages/server/src/core/git-clients/index.ts
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
// Clients des services git distants (Gitea / GitLab / GitHub) — P12. Uniquement `fetch` global
|
||||||
|
// (Node ≥ 22), AUCUNE dépendance (pas d'octokit/gitbeaker). Chaque client expose verify() (test de
|
||||||
|
// connectivité/auth) et listRepos() (paginé). Erreurs typées : AUTH_FAILED / RATE_LIMITED / UNREACHABLE.
|
||||||
|
import type { GitAuthType, GitService, RemoteRepoSummary } from '@arboretum/shared';
|
||||||
|
|
||||||
|
const REQUEST_TIMEOUT_MS = 12_000;
|
||||||
|
const PER_PAGE = 30;
|
||||||
|
|
||||||
|
export interface GitAuth {
|
||||||
|
authType: GitAuthType;
|
||||||
|
username: string | null;
|
||||||
|
secret: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GitServiceError extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly errorCode: string,
|
||||||
|
message?: string,
|
||||||
|
) {
|
||||||
|
super(message ?? errorCode);
|
||||||
|
this.name = 'GitServiceError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GitClient {
|
||||||
|
verify(auth: GitAuth): Promise<{ login: string }>;
|
||||||
|
listRepos(auth: GitAuth, page: number, search?: string): Promise<{ repos: RemoteRepoSummary[]; nextPage: number | null }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** En-têtes d'auth selon le type. app_password → Basic (username:secret) ; pat → en-tête propre au service. */
|
||||||
|
function authHeaders(service: GitService, auth: GitAuth): Record<string, string> {
|
||||||
|
if (auth.authType === 'app_password') {
|
||||||
|
const basic = Buffer.from(`${auth.username ?? ''}:${auth.secret}`).toString('base64');
|
||||||
|
return { Authorization: `Basic ${basic}` };
|
||||||
|
}
|
||||||
|
// pat
|
||||||
|
if (service === 'gitlab') return { 'PRIVATE-TOKEN': auth.secret };
|
||||||
|
if (service === 'gitea') return { Authorization: `token ${auth.secret}` };
|
||||||
|
return { Authorization: `Bearer ${auth.secret}` }; // github
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Refuse une base self-hosted non http(s) (anti-SSRF schéma) ; renvoie l'origine normalisée sans `/` final. */
|
||||||
|
function normalizeBase(baseUrl: string): string {
|
||||||
|
let u: URL;
|
||||||
|
try {
|
||||||
|
u = new URL(baseUrl);
|
||||||
|
} catch {
|
||||||
|
throw new GitServiceError('BAD_BASE_URL', 'base_url must be a valid http(s) URL');
|
||||||
|
}
|
||||||
|
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw new GitServiceError('BAD_BASE_URL', 'base_url must be http(s)');
|
||||||
|
return `${u.origin}${u.pathname}`.replace(/\/+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchJson(url: string, headers: Record<string, string>): Promise<{ json: unknown; headers: Headers }> {
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, { headers: { Accept: 'application/json', ...headers }, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||||
|
} catch {
|
||||||
|
throw new GitServiceError('UNREACHABLE', 'Could not reach the git service');
|
||||||
|
}
|
||||||
|
if (res.status === 429) throw new GitServiceError('RATE_LIMITED', 'Rate limited by the git service');
|
||||||
|
if (res.status === 401 || res.status === 403) {
|
||||||
|
// 403 + quota épuisé = rate limit (GitHub) ; sinon échec d'auth.
|
||||||
|
if (res.headers.get('x-ratelimit-remaining') === '0') throw new GitServiceError('RATE_LIMITED', 'Rate limited by the git service');
|
||||||
|
throw new GitServiceError('AUTH_FAILED', 'Authentication failed');
|
||||||
|
}
|
||||||
|
if (!res.ok) throw new GitServiceError(`HTTP_${res.status}`, `Unexpected response ${res.status}`);
|
||||||
|
return { json: await res.json().catch(() => null), headers: res.headers };
|
||||||
|
}
|
||||||
|
|
||||||
|
function githubBase(baseUrl: string | null): string {
|
||||||
|
return baseUrl ? normalizeBase(baseUrl) : 'https://api.github.com';
|
||||||
|
}
|
||||||
|
function gitlabBase(baseUrl: string | null): string {
|
||||||
|
return `${baseUrl ? normalizeBase(baseUrl) : 'https://gitlab.com'}/api/v4`;
|
||||||
|
}
|
||||||
|
function giteaBase(baseUrl: string | null): string {
|
||||||
|
if (!baseUrl) throw new GitServiceError('BAD_BASE_URL', 'Gitea requires a base_url (self-hosted instance)');
|
||||||
|
return `${normalizeBase(baseUrl)}/api/v1`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const githubClient = (baseUrl: string | null): GitClient => {
|
||||||
|
const base = githubBase(baseUrl);
|
||||||
|
return {
|
||||||
|
async verify(auth) {
|
||||||
|
const { json } = await fetchJson(`${base}/user`, authHeaders('github', auth));
|
||||||
|
return { login: String((json as { login?: string })?.login ?? '') };
|
||||||
|
},
|
||||||
|
async listRepos(auth, page) {
|
||||||
|
const { json } = await fetchJson(`${base}/user/repos?per_page=${PER_PAGE}&page=${page}&sort=updated`, authHeaders('github', auth));
|
||||||
|
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
|
||||||
|
const repos = arr.map((r): RemoteRepoSummary => ({
|
||||||
|
fullName: String(r.full_name ?? ''),
|
||||||
|
cloneUrl: String(r.clone_url ?? ''),
|
||||||
|
private: Boolean(r.private),
|
||||||
|
description: (r.description as string | null) ?? null,
|
||||||
|
defaultBranch: (r.default_branch as string | null) ?? null,
|
||||||
|
}));
|
||||||
|
return { repos, nextPage: arr.length === PER_PAGE ? page + 1 : null };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const gitlabClient = (baseUrl: string | null): GitClient => {
|
||||||
|
const base = gitlabBase(baseUrl);
|
||||||
|
return {
|
||||||
|
async verify(auth) {
|
||||||
|
const { json } = await fetchJson(`${base}/user`, authHeaders('gitlab', auth));
|
||||||
|
return { login: String((json as { username?: string })?.username ?? '') };
|
||||||
|
},
|
||||||
|
async listRepos(auth, page) {
|
||||||
|
const { json, headers } = await fetchJson(
|
||||||
|
`${base}/projects?membership=true&per_page=${PER_PAGE}&page=${page}&order_by=last_activity_at`,
|
||||||
|
authHeaders('gitlab', auth),
|
||||||
|
);
|
||||||
|
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
|
||||||
|
const repos = arr.map((r): RemoteRepoSummary => ({
|
||||||
|
fullName: String(r.path_with_namespace ?? ''),
|
||||||
|
cloneUrl: String(r.http_url_to_repo ?? ''),
|
||||||
|
private: r.visibility !== 'public',
|
||||||
|
description: (r.description as string | null) ?? null,
|
||||||
|
defaultBranch: (r.default_branch as string | null) ?? null,
|
||||||
|
}));
|
||||||
|
const next = headers.get('x-next-page');
|
||||||
|
return { repos, nextPage: next ? Number(next) : null };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const giteaClient = (baseUrl: string | null): GitClient => {
|
||||||
|
const base = giteaBase(baseUrl);
|
||||||
|
return {
|
||||||
|
async verify(auth) {
|
||||||
|
const { json } = await fetchJson(`${base}/user`, authHeaders('gitea', auth));
|
||||||
|
return { login: String((json as { login?: string })?.login ?? '') };
|
||||||
|
},
|
||||||
|
async listRepos(auth, page) {
|
||||||
|
const { json } = await fetchJson(`${base}/user/repos?page=${page}&limit=${PER_PAGE}`, authHeaders('gitea', auth));
|
||||||
|
const arr = Array.isArray(json) ? (json as Array<Record<string, unknown>>) : [];
|
||||||
|
const repos = arr.map((r): RemoteRepoSummary => ({
|
||||||
|
fullName: String(r.full_name ?? ''),
|
||||||
|
cloneUrl: String(r.clone_url ?? ''),
|
||||||
|
private: Boolean(r.private),
|
||||||
|
description: (r.description as string | null) ?? null,
|
||||||
|
defaultBranch: (r.default_branch as string | null) ?? null,
|
||||||
|
}));
|
||||||
|
return { repos, nextPage: arr.length === PER_PAGE ? page + 1 : null };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getGitClient(service: GitService, baseUrl: string | null): GitClient {
|
||||||
|
if (service === 'github') return githubClient(baseUrl);
|
||||||
|
if (service === 'gitlab') return gitlabClient(baseUrl);
|
||||||
|
return giteaClient(baseUrl);
|
||||||
|
}
|
||||||
180
packages/server/src/core/git-credentials.ts
Normal file
180
packages/server/src/core/git-credentials.ts
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
// Gestion des credentials des services git distants (P12). Les secrets (PAT/app password) sont
|
||||||
|
// chiffrés par SecretBox AVANT insertion et ne ressortent JAMAIS via l'API (résumés sans secret).
|
||||||
|
// getSecret()/authFor() sont INTERNES (clone, listRepos, test) — jamais routés.
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import type {
|
||||||
|
CreateGitCredentialRequest,
|
||||||
|
GitCredentialSummary,
|
||||||
|
GitService,
|
||||||
|
TestCredentialResponse,
|
||||||
|
UpdateGitCredentialRequest,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { SecretBox } from './secret-box.js';
|
||||||
|
import { getGitClient, GitServiceError, type GitAuth } from './git-clients/index.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
|
||||||
|
interface GitCredentialRow {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
service: GitService;
|
||||||
|
base_url: string | null;
|
||||||
|
auth_type: GitCredentialSummary['authType'];
|
||||||
|
username: string | null;
|
||||||
|
secret_encrypted: string | null;
|
||||||
|
ssh_key_path: string | null;
|
||||||
|
oauth_access_encrypted: string | null;
|
||||||
|
oauth_refresh_encrypted: string | null;
|
||||||
|
oauth_expires_at: string | null;
|
||||||
|
created_at: string;
|
||||||
|
last_tested_at: string | null;
|
||||||
|
test_result: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function httpError(statusCode: number, code: string, message: string): Error & { statusCode: number; code: string } {
|
||||||
|
return Object.assign(new Error(message), { statusCode, code });
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GitCredentialsManager {
|
||||||
|
constructor(
|
||||||
|
private readonly db: Db,
|
||||||
|
private readonly box: SecretBox,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
private getRow(id: string): GitCredentialRow | null {
|
||||||
|
return (this.db.prepare('SELECT * FROM git_credentials WHERE id = ?').get(id) as unknown as GitCredentialRow | undefined) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toSummary(row: GitCredentialRow): GitCredentialSummary {
|
||||||
|
let secretLast4: string | null = null;
|
||||||
|
if (row.secret_encrypted) {
|
||||||
|
try {
|
||||||
|
const s = this.box.decrypt(row.secret_encrypted);
|
||||||
|
secretLast4 = s.length >= 4 ? s.slice(-4) : '••••';
|
||||||
|
} catch {
|
||||||
|
secretLast4 = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
label: row.label,
|
||||||
|
service: row.service,
|
||||||
|
baseUrl: row.base_url,
|
||||||
|
authType: row.auth_type,
|
||||||
|
username: row.username,
|
||||||
|
hasSecret: row.secret_encrypted != null,
|
||||||
|
secretLast4,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
lastTestedAt: row.last_tested_at,
|
||||||
|
testResult: row.test_result,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
list(): GitCredentialSummary[] {
|
||||||
|
const rows = this.db.prepare('SELECT * FROM git_credentials ORDER BY created_at ASC').all() as unknown as GitCredentialRow[];
|
||||||
|
return rows.map((r) => this.toSummary(r));
|
||||||
|
}
|
||||||
|
|
||||||
|
get(id: string): GitCredentialSummary | null {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
return row ? this.toSummary(row) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
create(opts: CreateGitCredentialRequest): GitCredentialSummary {
|
||||||
|
// P12a : seules les méthodes HTTPS (pat / app_password) sont supportées pour l'instant.
|
||||||
|
if (opts.authType !== 'pat' && opts.authType !== 'app_password') {
|
||||||
|
throw httpError(400, 'UNSUPPORTED_AUTH', 'Only pat and app_password are supported for now (SSH/OAuth: later phases)');
|
||||||
|
}
|
||||||
|
if (!opts.label?.trim()) throw httpError(400, 'BAD_REQUEST', 'label is required');
|
||||||
|
if (opts.service !== 'gitea' && opts.service !== 'gitlab' && opts.service !== 'github') {
|
||||||
|
throw httpError(400, 'BAD_REQUEST', 'service must be gitea, gitlab or github');
|
||||||
|
}
|
||||||
|
if (opts.service === 'gitea' && !opts.baseUrl) throw httpError(400, 'BAD_REQUEST', 'Gitea requires a base_url');
|
||||||
|
if (!opts.secret) throw httpError(400, 'BAD_REQUEST', 'secret (token) is required');
|
||||||
|
const row: GitCredentialRow = {
|
||||||
|
id: randomUUID(),
|
||||||
|
label: opts.label.trim(),
|
||||||
|
service: opts.service,
|
||||||
|
base_url: opts.baseUrl?.trim() || null,
|
||||||
|
auth_type: opts.authType,
|
||||||
|
username: opts.username?.trim() || null,
|
||||||
|
secret_encrypted: this.box.encrypt(opts.secret),
|
||||||
|
ssh_key_path: null,
|
||||||
|
oauth_access_encrypted: null,
|
||||||
|
oauth_refresh_encrypted: null,
|
||||||
|
oauth_expires_at: null,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
last_tested_at: null,
|
||||||
|
test_result: null,
|
||||||
|
};
|
||||||
|
this.db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO git_credentials (id, label, service, base_url, auth_type, username, secret_encrypted, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
|
)
|
||||||
|
.run(row.id, row.label, row.service, row.base_url, row.auth_type, row.username, row.secret_encrypted, row.created_at);
|
||||||
|
return this.toSummary(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
update(id: string, patch: UpdateGitCredentialRequest): GitCredentialSummary {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
|
||||||
|
if (patch.label !== undefined) row.label = patch.label.trim() || row.label;
|
||||||
|
if (patch.baseUrl !== undefined) row.base_url = patch.baseUrl.trim() || null;
|
||||||
|
if (patch.username !== undefined) row.username = patch.username.trim() || null;
|
||||||
|
if (patch.secret) row.secret_encrypted = this.box.encrypt(patch.secret);
|
||||||
|
this.db
|
||||||
|
.prepare('UPDATE git_credentials SET label = ?, base_url = ?, username = ?, secret_encrypted = ? WHERE id = ?')
|
||||||
|
.run(row.label, row.base_url, row.username, row.secret_encrypted, id);
|
||||||
|
return this.toSummary(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Supprime un credential et NULLifie repos.credential_id (pas de FK). */
|
||||||
|
remove(id: string): boolean {
|
||||||
|
const res = this.db.prepare('DELETE FROM git_credentials WHERE id = ?').run(id);
|
||||||
|
if (res.changes === 0) return false;
|
||||||
|
this.db.prepare('UPDATE repos SET credential_id = NULL WHERE credential_id = ?').run(id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Secret déchiffré — INTERNE (clone/listRepos/test). Jamais exposé par une route. */
|
||||||
|
getSecret(id: string): string | null {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
if (!row?.secret_encrypted) return null;
|
||||||
|
try {
|
||||||
|
return this.box.decrypt(row.secret_encrypted);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Contexte d'auth (service, base, secret déchiffré) pour le client API / le clone. */
|
||||||
|
authContext(id: string): { service: GitService; baseUrl: string | null; auth: GitAuth } | null {
|
||||||
|
const row = this.getRow(id);
|
||||||
|
if (!row) return null;
|
||||||
|
const secret = this.getSecret(id);
|
||||||
|
if (secret == null) return null;
|
||||||
|
return { service: row.service, baseUrl: row.base_url, auth: { authType: row.auth_type, username: row.username, secret } };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Teste la connectivité/auth (GET /user) et mémorise le diagnostic. */
|
||||||
|
async test(id: string): Promise<TestCredentialResponse> {
|
||||||
|
const ctx = this.authContext(id);
|
||||||
|
if (!ctx) throw httpError(404, 'NOT_FOUND', 'No credential with this id');
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
try {
|
||||||
|
const { login } = await getGitClient(ctx.service, ctx.baseUrl).verify(ctx.auth);
|
||||||
|
this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, 'ok', id);
|
||||||
|
return { ok: true, user: login };
|
||||||
|
} catch (err) {
|
||||||
|
const code = err instanceof GitServiceError ? err.errorCode : 'UNREACHABLE';
|
||||||
|
this.db.prepare('UPDATE git_credentials SET last_tested_at = ?, test_result = ? WHERE id = ?').run(now, code, id);
|
||||||
|
return { ok: false, error: code };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Helper d'audit partagé (jamais de secret dans details). */
|
||||||
|
export function auditCredential(db: Db, actor: string, action: string, id: string | null): void {
|
||||||
|
recordAudit(db, { actor, action, resourceId: id });
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
// Couche git sûre : tout passe par execFile (JAMAIS de shell), arguments en tableau, `--` avant
|
// Couche git sûre : tout passe par execFile (JAMAIS de shell), arguments en tableau, `--` avant
|
||||||
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
|
// les chemins/refs utilisateur. Fonctions pures sans état, prenant un cwd déjà validé par l'appelant.
|
||||||
import { execFile } from 'node:child_process';
|
import { execFile, spawn } from 'node:child_process';
|
||||||
import { resolve, sep } from 'node:path';
|
import { resolve, sep } from 'node:path';
|
||||||
import type { WorktreeGitStatus } from '@arboretum/shared';
|
import type { WorktreeGitStatus, WorktreeBranchAction, WorktreeBranchMode, FileChange } from '@arboretum/shared';
|
||||||
|
|
||||||
const GIT_TIMEOUT_MS = 10_000;
|
const GIT_TIMEOUT_MS = 10_000;
|
||||||
|
// `push` peut dialoguer avec un remote (réseau) : on lui laisse une marge bien plus large.
|
||||||
|
const GIT_PUSH_TIMEOUT_MS = 120_000;
|
||||||
const GIT_MAX_BUFFER = 8 * 1024 * 1024;
|
const GIT_MAX_BUFFER = 8 * 1024 * 1024;
|
||||||
|
|
||||||
interface GitError extends Error {
|
interface GitError extends Error {
|
||||||
@@ -12,14 +14,14 @@ interface GitError extends Error {
|
|||||||
code?: number | string;
|
code?: number | string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function git(cwd: string, args: string[]): Promise<string> {
|
function git(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): Promise<string> {
|
||||||
return new Promise((resolveP, reject) => {
|
return new Promise((resolveP, reject) => {
|
||||||
execFile(
|
execFile(
|
||||||
'git',
|
'git',
|
||||||
args,
|
args,
|
||||||
{
|
{
|
||||||
cwd,
|
cwd,
|
||||||
timeout: GIT_TIMEOUT_MS,
|
timeout: timeoutMs,
|
||||||
maxBuffer: GIT_MAX_BUFFER,
|
maxBuffer: GIT_MAX_BUFFER,
|
||||||
// GIT_OPTIONAL_LOCKS=0 : pas de prise de verrou par `status` (perf + concurrence avec une
|
// GIT_OPTIONAL_LOCKS=0 : pas de prise de verrou par `status` (perf + concurrence avec une
|
||||||
// session claude active) ; LC_ALL=C : sortie stable pour le parsing.
|
// session claude active) ; LC_ALL=C : sortie stable pour le parsing.
|
||||||
@@ -37,6 +39,24 @@ function git(cwd: string, args: string[]): Promise<string> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Variante tolérante : résout `{ stdout, code }` au lieu de rejeter sur code de sortie non nul.
|
||||||
|
* Utile pour `git diff --no-index` (code 1 = « les fichiers diffèrent », pas une erreur).
|
||||||
|
*/
|
||||||
|
function gitRaw(cwd: string, args: string[], timeoutMs: number = GIT_TIMEOUT_MS): Promise<{ stdout: string; code: number }> {
|
||||||
|
return new Promise((resolveP) => {
|
||||||
|
execFile(
|
||||||
|
'git',
|
||||||
|
args,
|
||||||
|
{ cwd, timeout: timeoutMs, maxBuffer: GIT_MAX_BUFFER, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', LC_ALL: 'C' } },
|
||||||
|
(err, stdout) => {
|
||||||
|
const code = err ? ((err as GitError).code as number) ?? 1 : 0;
|
||||||
|
resolveP({ stdout: stdout.toString(), code: typeof code === 'number' ? code : 1 });
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export interface ParsedWorktree {
|
export interface ParsedWorktree {
|
||||||
path: string;
|
path: string;
|
||||||
head: string | null;
|
head: string | null;
|
||||||
@@ -120,6 +140,21 @@ export function isSafeAbsolutePath(p: string): boolean {
|
|||||||
return p.startsWith('/') && resolve(p) === p && !p.split(sep).includes('..');
|
return p.startsWith('/') && resolve(p) === p && !p.split(sep).includes('..');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pathspec relatif sûr passé à git (`git add/restore/diff -- <p>`) : non vide, non absolu, sans
|
||||||
|
* segment `..`, ne commençant pas par `-` (anti-flag). Le `--` avant le pathspec reste obligatoire.
|
||||||
|
*/
|
||||||
|
export function isSafeRelativePath(p: string): boolean {
|
||||||
|
if (p.length === 0 || p.startsWith('/') || p.startsWith('-')) return false;
|
||||||
|
const parts = p.split(/[\\/]/);
|
||||||
|
return !parts.includes('..') && !parts.includes('.git');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Initialise un dépôt git dans `dir` (déjà créé et validé par l'appelant). `git init` est idempotent. */
|
||||||
|
export async function gitInit(dir: string): Promise<void> {
|
||||||
|
await git(dir, ['init']);
|
||||||
|
}
|
||||||
|
|
||||||
/** true si `path` est la racine d'un dépôt git (main worktree) accessible. */
|
/** true si `path` est la racine d'un dépôt git (main worktree) accessible. */
|
||||||
export async function isRepo(path: string): Promise<boolean> {
|
export async function isRepo(path: string): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
@@ -140,6 +175,52 @@ export async function defaultBranch(repoPath: string): Promise<string | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Branche courante (nom court) du checkout en `repoPath`, ou null si HEAD détaché. */
|
||||||
|
export async function currentBranch(repoPath: string): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const b = (await git(repoPath, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
|
||||||
|
return b === 'HEAD' ? null : b;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Existence d'une branche, en local (`refs/heads`) et/ou suivie du remote (`refs/remotes/origin`). */
|
||||||
|
export async function branchExists(repoPath: string, branch: string): Promise<{ local: boolean; remote: boolean }> {
|
||||||
|
const verify = async (ref: string): Promise<boolean> => {
|
||||||
|
try {
|
||||||
|
await git(repoPath, ['rev-parse', '--verify', '--quiet', ref]);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const [local, remote] = await Promise.all([verify(`refs/heads/${branch}`), verify(`refs/remotes/origin/${branch}`)]);
|
||||||
|
return { local, remote };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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[] = [];
|
||||||
|
try {
|
||||||
|
const out = await git(repoPath, ['for-each-ref', '--format=%(refname:short)', 'refs/heads', 'refs/remotes/origin']);
|
||||||
|
for (const line of out.split('\n')) {
|
||||||
|
const name = line.trim();
|
||||||
|
if (!name) continue;
|
||||||
|
if (name.startsWith('origin/')) {
|
||||||
|
const short = name.slice('origin/'.length);
|
||||||
|
if (short && short !== 'HEAD') remote.push(short);
|
||||||
|
} else {
|
||||||
|
local.push(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* dépôt sans refs encore (premier commit absent) → listes vides */
|
||||||
|
}
|
||||||
|
return { local, remote, default: await defaultBranch(repoPath) };
|
||||||
|
}
|
||||||
|
|
||||||
export async function listWorktrees(repoPath: string): Promise<ParsedWorktree[]> {
|
export async function listWorktrees(repoPath: string): Promise<ParsedWorktree[]> {
|
||||||
return parseWorktreePorcelain(await git(repoPath, ['worktree', 'list', '--porcelain']));
|
return parseWorktreePorcelain(await git(repoPath, ['worktree', 'list', '--porcelain']));
|
||||||
}
|
}
|
||||||
@@ -166,28 +247,339 @@ export async function worktreeStatus(worktreePath: string): Promise<WorktreeGitS
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let dirtyCount = 0;
|
let dirtyCount = 0;
|
||||||
|
let stagedCount = 0;
|
||||||
|
let unstagedCount = 0;
|
||||||
|
let conflictCount = 0;
|
||||||
try {
|
try {
|
||||||
const status = await git(worktreePath, ['status', '--porcelain=v1', '--untracked-files=all']);
|
// Un SEUL passage porcelain v2 -z : dirtyCount + compteurs fins (staged/unstaged/conflit).
|
||||||
dirtyCount = status.split('\n').filter((l) => l.trim() !== '').length;
|
const out = await git(worktreePath, ['status', '--porcelain=v2', '-z', '--untracked-files=all']);
|
||||||
|
const entries = parsePorcelainV2(out);
|
||||||
|
dirtyCount = entries.length;
|
||||||
|
for (const e of entries) {
|
||||||
|
if (e.conflicted) conflictCount++;
|
||||||
|
if (e.staged) stagedCount++;
|
||||||
|
if (e.unstaged) unstagedCount++;
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
return { ahead, behind, dirtyCount, upstream };
|
let lastCommitHash: string | null = null;
|
||||||
|
let lastCommitSubject: string | null = null;
|
||||||
|
try {
|
||||||
|
const lc = await lastCommit(worktreePath);
|
||||||
|
if (lc) {
|
||||||
|
lastCommitHash = lc.hash;
|
||||||
|
lastCommitSubject = lc.subject;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* repo sans commit : on laisse null */
|
||||||
|
}
|
||||||
|
return { ahead, behind, dirtyCount, upstream, stagedCount, unstagedCount, conflictCount, lastCommitHash, lastCommitSubject };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- P7 : statut détaillé / diff / staging / commit sélectif / fetch-pull (IDE worktree) ----
|
||||||
|
|
||||||
|
/** Entrée brute de `git status --porcelain=v2` (avant enrichissement numstat). */
|
||||||
|
export interface PorcelainV2Entry {
|
||||||
|
path: string;
|
||||||
|
indexStatus: string;
|
||||||
|
worktreeStatus: string;
|
||||||
|
staged: boolean;
|
||||||
|
unstaged: boolean;
|
||||||
|
untracked: boolean;
|
||||||
|
conflicted: boolean;
|
||||||
|
renamedFrom?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse `git status --porcelain=v2 -z --untracked-files=all` (testable sans repo réel). Format -z :
|
||||||
|
* champs séparés par NUL ; une entrée de renommage (type `2`) consomme un champ supplémentaire
|
||||||
|
* (l'ancien chemin). Les chemins ne sont jamais entre guillemets en mode -z (pas d'échappement).
|
||||||
|
*/
|
||||||
|
export function parsePorcelainV2(stdout: string): PorcelainV2Entry[] {
|
||||||
|
const fields = stdout.split('\0');
|
||||||
|
if (fields.length && fields[fields.length - 1] === '') fields.pop();
|
||||||
|
const out: PorcelainV2Entry[] = [];
|
||||||
|
for (let i = 0; i < fields.length; i++) {
|
||||||
|
const f = fields[i];
|
||||||
|
if (!f) continue;
|
||||||
|
const kind = f[0];
|
||||||
|
if (kind === '1') {
|
||||||
|
const t = f.split(' ');
|
||||||
|
const xy = t[1] ?? '..';
|
||||||
|
out.push(entryFromXy(t.slice(8).join(' '), xy, { conflicted: false }));
|
||||||
|
} else if (kind === '2') {
|
||||||
|
const t = f.split(' ');
|
||||||
|
const xy = t[1] ?? '..';
|
||||||
|
const path = t.slice(9).join(' ');
|
||||||
|
const renamedFrom = fields[++i]; // l'ancien chemin suit dans le champ NUL suivant
|
||||||
|
out.push(entryFromXy(path, xy, { conflicted: false, ...(renamedFrom ? { renamedFrom } : {}) }));
|
||||||
|
} else if (kind === 'u') {
|
||||||
|
const t = f.split(' ');
|
||||||
|
const xy = t[1] ?? '..';
|
||||||
|
out.push(entryFromXy(t.slice(10).join(' '), xy, { conflicted: true }));
|
||||||
|
} else if (kind === '?') {
|
||||||
|
out.push({ path: f.slice(2), indexStatus: '?', worktreeStatus: '?', staged: false, unstaged: true, untracked: true, conflicted: false });
|
||||||
|
}
|
||||||
|
// '!' (ignored) : exclu de la liste des changements.
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function entryFromXy(path: string, xy: string, opts: { conflicted: boolean; renamedFrom?: string }): PorcelainV2Entry {
|
||||||
|
const indexStatus = xy[0] ?? '.';
|
||||||
|
const worktreeStatus = xy[1] ?? '.';
|
||||||
|
return {
|
||||||
|
path,
|
||||||
|
indexStatus,
|
||||||
|
worktreeStatus,
|
||||||
|
staged: !opts.conflicted && indexStatus !== '.',
|
||||||
|
unstaged: opts.conflicted || worktreeStatus !== '.',
|
||||||
|
untracked: false,
|
||||||
|
conflicted: opts.conflicted,
|
||||||
|
...(opts.renamedFrom ? { renamedFrom: opts.renamedFrom } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse `git diff --numstat -z` → map chemin → {insertions, deletions, binary}. Les fichiers
|
||||||
|
* binaires sont marqués `'-'` par git. Les renommages ont un champ chemin vide suivi de
|
||||||
|
* deux champs NUL (ancien, nouveau) ; on indexe par le nouveau chemin.
|
||||||
|
*/
|
||||||
|
export function parseNumstatZ(stdout: string): Map<string, { insertions: number | null; deletions: number | null; binary: boolean }> {
|
||||||
|
const fields = stdout.split('\0');
|
||||||
|
if (fields.length && fields[fields.length - 1] === '') fields.pop();
|
||||||
|
const map = new Map<string, { insertions: number | null; deletions: number | null; binary: boolean }>();
|
||||||
|
for (let i = 0; i < fields.length; i++) {
|
||||||
|
const f = fields[i];
|
||||||
|
if (!f) continue;
|
||||||
|
const parts = f.split('\t');
|
||||||
|
if (parts.length < 3) continue;
|
||||||
|
const addRaw = parts[0] ?? '';
|
||||||
|
const delRaw = parts[1] ?? '';
|
||||||
|
let path = parts[2] ?? '';
|
||||||
|
if (path === '') {
|
||||||
|
// renommage : ancien chemin = champ suivant, nouveau chemin = champ d'après.
|
||||||
|
i++; // saute l'ancien chemin
|
||||||
|
path = fields[++i] ?? '';
|
||||||
|
if (path === '') continue;
|
||||||
|
}
|
||||||
|
const binary = addRaw === '-' || delRaw === '-';
|
||||||
|
map.set(path, {
|
||||||
|
insertions: binary ? null : Number(addRaw) || 0,
|
||||||
|
deletions: binary ? null : Number(delRaw) || 0,
|
||||||
|
binary,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_CHANGES = 5000;
|
||||||
|
|
||||||
|
/** Liste les fichiers modifiés d'un worktree (statut porcelain v2 enrichi des stats numstat). */
|
||||||
|
export async function listChanges(worktreePath: string): Promise<{ changes: FileChange[]; truncated: boolean }> {
|
||||||
|
const [statusOut, unstagedOut, stagedOut] = await Promise.all([
|
||||||
|
git(worktreePath, ['status', '--porcelain=v2', '-z', '--untracked-files=all']),
|
||||||
|
git(worktreePath, ['diff', '--numstat', '-z']),
|
||||||
|
git(worktreePath, ['diff', '--numstat', '-z', '--cached']),
|
||||||
|
]);
|
||||||
|
const entries = parsePorcelainV2(statusOut);
|
||||||
|
const unstaged = parseNumstatZ(unstagedOut);
|
||||||
|
const staged = parseNumstatZ(stagedOut);
|
||||||
|
const truncated = entries.length > MAX_CHANGES;
|
||||||
|
const slice = truncated ? entries.slice(0, MAX_CHANGES) : entries;
|
||||||
|
const changes: FileChange[] = slice.map((e) => {
|
||||||
|
const ns = unstaged.get(e.path) ?? staged.get(e.path);
|
||||||
|
const binary = ns?.binary ?? false;
|
||||||
|
// insertions/deletions = somme staged+unstaged quand disponible ; null pour binaire/untracked.
|
||||||
|
const u = unstaged.get(e.path);
|
||||||
|
const s = staged.get(e.path);
|
||||||
|
const sum = (a: number | null | undefined, b: number | null | undefined): number | null => {
|
||||||
|
if (a == null && b == null) return null;
|
||||||
|
return (a ?? 0) + (b ?? 0);
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
path: e.path,
|
||||||
|
indexStatus: e.indexStatus,
|
||||||
|
worktreeStatus: e.worktreeStatus,
|
||||||
|
staged: e.staged,
|
||||||
|
unstaged: e.unstaged,
|
||||||
|
untracked: e.untracked,
|
||||||
|
conflicted: e.conflicted,
|
||||||
|
insertions: binary ? null : sum(u?.insertions, s?.insertions),
|
||||||
|
deletions: binary ? null : sum(u?.deletions, s?.deletions),
|
||||||
|
binary,
|
||||||
|
...(e.renamedFrom ? { renamedFrom: e.renamedFrom } : {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return { changes, truncated };
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_DIFF_BYTES = 512 * 1024;
|
||||||
|
|
||||||
|
/** Diff unifié d'un fichier. `staged` → diff de l'index ; `untracked` → diff vs /dev/null. */
|
||||||
|
export async function fileDiff(
|
||||||
|
worktreePath: string,
|
||||||
|
file: string,
|
||||||
|
opts: { staged?: boolean; untracked?: boolean } = {},
|
||||||
|
): Promise<{ diff: string; binary: boolean; tooLarge: boolean }> {
|
||||||
|
let raw: string;
|
||||||
|
if (opts.untracked) {
|
||||||
|
// --no-index sort en code 1 quand les fichiers diffèrent : on tolère via gitRaw.
|
||||||
|
const r = await gitRaw(worktreePath, ['diff', '--no-index', '--no-color', '--', '/dev/null', file]);
|
||||||
|
raw = r.stdout;
|
||||||
|
} else {
|
||||||
|
raw = await git(worktreePath, ['diff', '--no-color', ...(opts.staged ? ['--cached'] : []), '--', file]);
|
||||||
|
}
|
||||||
|
const binary = /^Binary files .* differ$/m.test(raw) || raw.includes('GIT binary patch');
|
||||||
|
if (binary) return { diff: '', binary: true, tooLarge: false };
|
||||||
|
if (raw.length > MAX_DIFF_BYTES) return { diff: raw.slice(0, MAX_DIFF_BYTES), binary: false, tooLarge: true };
|
||||||
|
return { diff: raw, binary: false, tooLarge: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Indexe des fichiers (`git add -- <files>`). Chaque chemin validé par l'appelant (isSafeRelativePath). */
|
||||||
|
export async function stageFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['add', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Désindexe des fichiers (`git restore --staged -- <files>`). */
|
||||||
|
export async function unstageFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['restore', '--staged', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Annule les modifications de l'arbre de travail de fichiers SUIVIS (`git restore -- <files>`). */
|
||||||
|
export async function restoreFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['restore', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Supprime des fichiers NON SUIVIS (`git clean -f -- <files>`). Destructif : opt-in côté appelant. */
|
||||||
|
export async function cleanFiles(worktreePath: string, files: string[]): Promise<void> {
|
||||||
|
if (files.length === 0) return;
|
||||||
|
await git(worktreePath, ['clean', '-f', '--', ...files]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Commit de l'index uniquement (contraste avec `commitAll` = `git add -A` + commit). */
|
||||||
|
export async function commitStaged(worktreePath: string, message: string): Promise<void> {
|
||||||
|
await git(worktreePath, ['commit', '-m', message]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Réécrit le dernier commit. L'appelant garantit qu'il n'est pas déjà poussé. */
|
||||||
|
export async function amendCommit(worktreePath: string, message?: string): Promise<void> {
|
||||||
|
await git(worktreePath, message ? ['commit', '--amend', '-m', message] : ['commit', '--amend', '--no-edit']);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git fetch --all --prune` (réseau → timeout élargi). */
|
||||||
|
export async function fetchRemote(worktreePath: string): Promise<void> {
|
||||||
|
await git(worktreePath, ['fetch', '--all', '--prune'], GIT_PUSH_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git pull` — `ff-only` par défaut (jamais de merge surprise) ; `rebase` optionnel. */
|
||||||
|
export async function pull(worktreePath: string, mode: 'ff-only' | 'rebase' = 'ff-only'): Promise<void> {
|
||||||
|
const args = mode === 'rebase' ? ['-c', 'rebase.autoStash=false', 'pull', '--rebase'] : ['pull', '--ff-only'];
|
||||||
|
await git(worktreePath, args, GIT_PUSH_TIMEOUT_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Répertoire git absolu d'un worktree (`git rev-parse --absolute-git-dir`). Pour le checkout
|
||||||
|
* principal : `<path>/.git` ; pour un worktree LIÉ : `<repo>/.git/worktrees/<n>` (le `.git` du
|
||||||
|
* worktree est un fichier pointeur). Sert au watcher FS pour surveiller le bon `HEAD`/`index`.
|
||||||
|
*/
|
||||||
|
export async function resolveGitDir(worktreePath: string): Promise<string | null> {
|
||||||
|
const r = await gitRaw(worktreePath, ['rev-parse', '--absolute-git-dir']);
|
||||||
|
if (r.code !== 0) return null;
|
||||||
|
return r.stdout.trim() || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dernier commit (HEAD) : hash court + sujet. null si le dépôt n'a aucun commit. */
|
||||||
|
export async function lastCommit(worktreePath: string): Promise<{ hash: string; subject: string } | null> {
|
||||||
|
const r = await gitRaw(worktreePath, ['log', '-1', '--format=%h%x00%s']);
|
||||||
|
if (r.code !== 0) return null;
|
||||||
|
const idx = r.stdout.indexOf('\0');
|
||||||
|
if (idx === -1) return null;
|
||||||
|
return { hash: r.stdout.slice(0, idx), subject: r.stdout.slice(idx + 1).replace(/\n$/, '') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** true si le HEAD courant n'est pas encore poussé (amend autorisé). Sans upstream → true. */
|
||||||
|
export async function isUnpushed(worktreePath: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await git(worktreePath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
||||||
|
} catch {
|
||||||
|
return true; // pas d'upstream → rien n'est « partagé »
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const out = (await git(worktreePath, ['rev-list', '--count', '@{u}..HEAD'])).trim();
|
||||||
|
return (Number(out) || 0) > 0;
|
||||||
|
} catch {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Point de départ d'une branche créée : `baseRef` explicite, sinon la branche par défaut du dépôt
|
||||||
|
* (locale ou suivie de `origin`), sinon undefined (git part alors du HEAD courant). */
|
||||||
|
async function resolveStartPoint(repoPath: string, baseRef?: string): Promise<string | undefined> {
|
||||||
|
if (baseRef) return baseRef;
|
||||||
|
const def = await defaultBranch(repoPath);
|
||||||
|
if (!def) return undefined;
|
||||||
|
const { local, remote } = await branchExists(repoPath, def);
|
||||||
|
if (local) return def;
|
||||||
|
if (remote) return `origin/${def}`;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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).
|
||||||
|
*/
|
||||||
export async function addWorktree(
|
export async function addWorktree(
|
||||||
repoPath: string,
|
repoPath: string,
|
||||||
opts: { path: string; branch: string; newBranch: boolean; baseRef?: string },
|
opts: { path: string; branch: string; mode: WorktreeBranchMode; baseRef?: string },
|
||||||
): Promise<void> {
|
): Promise<WorktreeBranchAction> {
|
||||||
|
const { local, remote } = await branchExists(repoPath, opts.branch);
|
||||||
|
let action: WorktreeBranchAction;
|
||||||
|
if (opts.mode === 'create') action = 'created';
|
||||||
|
else if (opts.mode === 'checkout') action = local ? 'reused' : 'tracked';
|
||||||
|
else action = local ? 'reused' : remote ? 'tracked' : 'created'; // auto
|
||||||
|
|
||||||
const args = ['worktree', 'add'];
|
const args = ['worktree', 'add'];
|
||||||
if (opts.newBranch) args.push('-b', opts.branch);
|
if (action === 'reused') {
|
||||||
args.push('--', opts.path);
|
args.push('--', opts.path, opts.branch);
|
||||||
if (opts.newBranch) {
|
} else if (action === 'tracked') {
|
||||||
if (opts.baseRef) args.push(opts.baseRef);
|
args.push('--track', '-b', opts.branch, '--', opts.path, `origin/${opts.branch}`);
|
||||||
} else {
|
} else {
|
||||||
args.push(opts.branch);
|
const start = await resolveStartPoint(repoPath, opts.baseRef);
|
||||||
|
args.push('-b', opts.branch, '--', opts.path);
|
||||||
|
if (start) args.push(start);
|
||||||
}
|
}
|
||||||
await git(repoPath, args);
|
await git(repoPath, args);
|
||||||
|
return action;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git add -A` puis commit. L'appelant garantit qu'il y a quelque chose à committer. */
|
||||||
|
export async function commitAll(repoPath: string, message: string): Promise<void> {
|
||||||
|
await git(repoPath, ['add', '-A']);
|
||||||
|
await git(repoPath, ['commit', '-m', message]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pousse la branche courante. Si aucun upstream n'est configuré : `git push -u origin <branche>`. */
|
||||||
|
export async function push(repoPath: string): Promise<void> {
|
||||||
|
let hasUpstream = false;
|
||||||
|
try {
|
||||||
|
await git(repoPath, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']);
|
||||||
|
hasUpstream = true;
|
||||||
|
} catch {
|
||||||
|
hasUpstream = false;
|
||||||
|
}
|
||||||
|
if (hasUpstream) {
|
||||||
|
await git(repoPath, ['push'], GIT_PUSH_TIMEOUT_MS);
|
||||||
|
} else {
|
||||||
|
const branch = await currentBranch(repoPath);
|
||||||
|
if (!branch) throw new Error('cannot push a detached HEAD');
|
||||||
|
await git(repoPath, ['push', '-u', 'origin', branch], GIT_PUSH_TIMEOUT_MS);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -213,3 +605,50 @@ export function isDirtyWorktreeError(err: unknown): boolean {
|
|||||||
const msg = `${(err as GitError)?.stderr ?? ''} ${(err as Error)?.message ?? ''}`;
|
const msg = `${(err as GitError)?.stderr ?? ''} ${(err as Error)?.message ?? ''}`;
|
||||||
return /contains modified or untracked files|is dirty|use --force/i.test(msg);
|
return /contains modified or untracked files|is dirty|use --force/i.test(msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const GIT_CLONE_TIMEOUT_MS = 10 * 60_000; // 10 min : un clone réseau peut être long.
|
||||||
|
|
||||||
|
export interface CloneProgress {
|
||||||
|
phase: string;
|
||||||
|
/** pourcentage 0–100 si git le rapporte, sinon null. */
|
||||||
|
percent: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clone un dépôt via `git clone --progress` (P12). `spawn` (et non execFile) pour streamer la
|
||||||
|
* progression depuis stderr. `env` éphémère (cf. withGitAuth) porte l'auth — JAMAIS dans l'URL.
|
||||||
|
* `--` sépare l'URL/dest des options. L'appelant valide `dest` (sous scanRoots, non existant).
|
||||||
|
*/
|
||||||
|
export function cloneRepo(opts: {
|
||||||
|
url: string;
|
||||||
|
dest: string;
|
||||||
|
env?: NodeJS.ProcessEnv;
|
||||||
|
branch?: string;
|
||||||
|
onProgress?: (p: CloneProgress) => void;
|
||||||
|
signal?: AbortSignal;
|
||||||
|
}): Promise<void> {
|
||||||
|
return new Promise((resolveP, reject) => {
|
||||||
|
const args = ['clone', '--progress'];
|
||||||
|
if (opts.branch) args.push('--branch', opts.branch);
|
||||||
|
args.push('--', opts.url, opts.dest);
|
||||||
|
const child = spawn('git', args, {
|
||||||
|
env: { ...(opts.env ?? process.env), GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
|
||||||
|
stdio: ['ignore', 'ignore', 'pipe'],
|
||||||
|
timeout: GIT_CLONE_TIMEOUT_MS,
|
||||||
|
...(opts.signal ? { signal: opts.signal } : {}),
|
||||||
|
});
|
||||||
|
let stderr = '';
|
||||||
|
child.stderr.on('data', (d: Buffer) => {
|
||||||
|
const s = d.toString();
|
||||||
|
stderr += s;
|
||||||
|
if (stderr.length > 64 * 1024) stderr = stderr.slice(-64 * 1024); // borne mémoire
|
||||||
|
const m = /([A-Za-z][A-Za-z ]+):\s+(\d+)%/.exec(s);
|
||||||
|
if (m && m[1] && m[2] && opts.onProgress) opts.onProgress({ phase: m[1].trim(), percent: Number(m[2]) });
|
||||||
|
});
|
||||||
|
child.on('error', (err) => reject(err));
|
||||||
|
child.on('close', (code) => {
|
||||||
|
if (code === 0) resolveP();
|
||||||
|
else reject(new Error(stderr.trim().split('\n').pop() || `git clone exited with code ${code}`));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
33
packages/server/src/core/project.ts
Normal file
33
packages/server/src/core/project.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// Création d'un nouveau projet : un dossier `<root>/<name>` créé sous une racine existante, dans
|
||||||
|
// lequel on lance ensuite une session. Couche PURE (testable sans fs) — la création réelle du
|
||||||
|
// dossier, le `git init` et le spawn vivent dans `routes/projects.ts`.
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { isSafeAbsolutePath } from './git.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide un nom de projet : UN SEUL segment de dossier. Anti-traversal de base — refuse les noms
|
||||||
|
* vides, trop longs, `.`/`..`, et tout caractère de séparation (`/`, `\`) ou NUL. La résolution du
|
||||||
|
* chemin complet (et sa re-validation) est faite par {@link resolveProjectDir}.
|
||||||
|
*/
|
||||||
|
export function isSafeProjectName(name: string): boolean {
|
||||||
|
const n = name.trim();
|
||||||
|
if (n.length === 0 || n.length > 255) return false;
|
||||||
|
if (n === '.' || n === '..') return false;
|
||||||
|
return !/[/\\\0]/.test(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résout le dossier de projet `<root>/<name>`. Suppose `root` déjà validé absolu et existant par
|
||||||
|
* l'appelant ; re-valide le chemin final via {@link isSafeAbsolutePath} (défense en profondeur).
|
||||||
|
* Lève si `name` est invalide ou si le chemin résultant échappe l'arborescence.
|
||||||
|
*/
|
||||||
|
export function resolveProjectDir(root: string, name: string): string {
|
||||||
|
if (!isSafeProjectName(name)) {
|
||||||
|
throw Object.assign(new Error(`Invalid project name: ${name}`), { statusCode: 400 });
|
||||||
|
}
|
||||||
|
const dir = join(root, name.trim());
|
||||||
|
if (!isSafeAbsolutePath(dir)) {
|
||||||
|
throw Object.assign(new Error(`Unsafe project path: ${dir}`), { statusCode: 400 });
|
||||||
|
}
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
@@ -7,12 +7,15 @@ import pty from '@homebridge/node-pty-prebuilt-multiarch';
|
|||||||
import { FLOW, REPLAY_TAIL_BYTES, type SessionActivity, type SessionSummary } from '@arboretum/shared';
|
import { FLOW, REPLAY_TAIL_BYTES, type SessionActivity, type SessionSummary } from '@arboretum/shared';
|
||||||
import { RingBuffer } from './ring-buffer.js';
|
import { RingBuffer } from './ring-buffer.js';
|
||||||
import { buildSpawnSpec } from './claude-launcher.js';
|
import { buildSpawnSpec } from './claude-launcher.js';
|
||||||
|
import { readClaudeBinPath } from './claude-settings.js';
|
||||||
import { findByPid } from './session-registry.js';
|
import { findByPid } from './session-registry.js';
|
||||||
import { SessionActivityTracker } from './claude-adapter.js';
|
import { SessionActivityTracker } from './claude-adapter.js';
|
||||||
import type { PushService } from './push-service.js';
|
import type { PushService } from './push-service.js';
|
||||||
import type { Db } from '../db/index.js';
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
const RING_CAPACITY = 2 * 1024 * 1024;
|
// 4 Mo : conserve assez d'historique pour que le replay (REPLAY_TAIL_BYTES = 1 Mo) reste largement
|
||||||
|
// dans le ring et qu'on puisse remonter une conversation Claude après ré-attache.
|
||||||
|
const RING_CAPACITY = 4 * 1024 * 1024;
|
||||||
const KILL_GRACE_MS = 5000;
|
const KILL_GRACE_MS = 5000;
|
||||||
/** Délai avant envoi d'une notif push sur passage en `waiting` : annulé si la session repart (faux positif). */
|
/** Délai avant envoi d'une notif push sur passage en `waiting` : annulé si la session repart (faux positif). */
|
||||||
const NOTIFY_DEBOUNCE_MS = 1500;
|
const NOTIFY_DEBOUNCE_MS = 1500;
|
||||||
@@ -20,6 +23,25 @@ const NOTIFY_DEBOUNCE_MS = 1500;
|
|||||||
const CLAUDE_ID_POLL_MS = 400;
|
const CLAUDE_ID_POLL_MS = 400;
|
||||||
const CLAUDE_ID_TIMEOUT_MS = 60_000;
|
const CLAUDE_ID_TIMEOUT_MS = 60_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ligne `sessions` telle que lue pour construire un SessionSummary historique (session terminée).
|
||||||
|
* `type` (et non `interface`) pour que TS infère l'index signature implicite → cast direct depuis
|
||||||
|
* le `Record<string, SQLOutputValue>` de node:sqlite.
|
||||||
|
*/
|
||||||
|
type HistoricalRow = {
|
||||||
|
id: string;
|
||||||
|
cwd: string;
|
||||||
|
command: string;
|
||||||
|
title: string | null;
|
||||||
|
created_at: string;
|
||||||
|
ended_at: string | null;
|
||||||
|
exit_code: number | null;
|
||||||
|
claude_session_id: string | null;
|
||||||
|
added_dirs: string | null;
|
||||||
|
group_id: string | null;
|
||||||
|
archived_at: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
/** Parse la colonne `added_dirs` (JSON array de chemins) de façon défensive ; [] si NULL/invalide. */
|
/** Parse la colonne `added_dirs` (JSON array de chemins) de façon défensive ; [] si NULL/invalide. */
|
||||||
function parseAddedDirs(raw: string | null): string[] {
|
function parseAddedDirs(raw: string | null): string[] {
|
||||||
if (!raw) return [];
|
if (!raw) return [];
|
||||||
@@ -109,8 +131,11 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
}
|
}
|
||||||
// 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');
|
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;
|
||||||
const spec = buildSpawnSpec({
|
const spec = buildSpawnSpec({
|
||||||
command,
|
command,
|
||||||
|
...(claudeBinPath ? { claudeBinPath } : {}),
|
||||||
...(opts.resume ? { resume: opts.resume } : {}),
|
...(opts.resume ? { resume: opts.resume } : {}),
|
||||||
...(addedDirs.length ? { addDirs: addedDirs } : {}),
|
...(addedDirs.length ? { addDirs: addedDirs } : {}),
|
||||||
});
|
});
|
||||||
@@ -240,41 +265,61 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
return set;
|
return set;
|
||||||
}
|
}
|
||||||
|
|
||||||
list(): SessionSummary[] {
|
list(opts?: { includeArchived?: boolean }): SessionSummary[] {
|
||||||
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
|
const liveSummaries = [...this.live.values()].map((s) => this.summarize(s));
|
||||||
const liveIds = new Set(this.live.keys());
|
const liveIds = new Set(this.live.keys());
|
||||||
const rows = this.db
|
const rows = this.db
|
||||||
.prepare('SELECT id, cwd, command, title, created_at, ended_at, exit_code, claude_session_id, added_dirs, group_id 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 FROM sessions ORDER BY created_at DESC LIMIT 100')
|
||||||
.all() as Array<{ id: string; cwd: string; command: string; title: string | null; created_at: string; ended_at: string | null; exit_code: number | null; claude_session_id: string | null; added_dirs: string | null; group_id: string | null }>;
|
.all() as HistoricalRow[];
|
||||||
const historical: SessionSummary[] = rows
|
const historical: SessionSummary[] = rows
|
||||||
.filter((r) => !liveIds.has(r.id))
|
.filter((r) => !liveIds.has(r.id))
|
||||||
.map((r) => {
|
// Sessions auto-archivées exclues par défaut (filtre indépendant et cumulable avec hidden).
|
||||||
const addedDirs = parseAddedDirs(r.added_dirs);
|
.filter((r) => (opts?.includeArchived ? true : r.archived_at == null))
|
||||||
return {
|
.map((r) => this.historicalSummary(r));
|
||||||
id: r.id,
|
|
||||||
cwd: r.cwd,
|
|
||||||
command: r.command,
|
|
||||||
title: r.title,
|
|
||||||
status: 'exited' as const,
|
|
||||||
live: false,
|
|
||||||
createdAt: r.created_at,
|
|
||||||
endedAt: r.ended_at,
|
|
||||||
exitCode: r.exit_code,
|
|
||||||
clients: 0,
|
|
||||||
source: 'managed' as const,
|
|
||||||
claudeSessionId: r.claude_session_id,
|
|
||||||
pid: null,
|
|
||||||
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
|
||||||
resumable: r.command === 'claude' && r.claude_session_id != null,
|
|
||||||
attachable: false,
|
|
||||||
registryStatus: null,
|
|
||||||
...(addedDirs.length ? { addedDirs } : {}),
|
|
||||||
groupId: r.group_id,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
return [...liveSummaries, ...historical];
|
return [...liveSummaries, ...historical];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Construit le SessionSummary d'une ligne historique (session managée terminée). */
|
||||||
|
private historicalSummary(r: HistoricalRow): SessionSummary {
|
||||||
|
const addedDirs = parseAddedDirs(r.added_dirs);
|
||||||
|
return {
|
||||||
|
id: r.id,
|
||||||
|
cwd: r.cwd,
|
||||||
|
command: r.command,
|
||||||
|
title: r.title,
|
||||||
|
status: 'exited' as const,
|
||||||
|
live: false,
|
||||||
|
createdAt: r.created_at,
|
||||||
|
endedAt: r.ended_at,
|
||||||
|
exitCode: r.exit_code,
|
||||||
|
clients: 0,
|
||||||
|
source: 'managed' as const,
|
||||||
|
claudeSessionId: r.claude_session_id,
|
||||||
|
pid: null,
|
||||||
|
// une session claude morte avec un claudeSessionId connu est reprenable (--resume direct).
|
||||||
|
resumable: r.command === 'claude' && r.claude_session_id != null,
|
||||||
|
attachable: false,
|
||||||
|
registryStatus: null,
|
||||||
|
...(addedDirs.length ? { addedDirs } : {}),
|
||||||
|
groupId: r.group_id,
|
||||||
|
archived: r.archived_at != null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 = ?')
|
||||||
|
.get(id) as HistoricalRow | undefined;
|
||||||
|
if (!r) return;
|
||||||
|
this.emit('session_update', this.historicalSummary(r));
|
||||||
|
}
|
||||||
|
|
||||||
get(id: string): SessionSummary | null {
|
get(id: string): SessionSummary | null {
|
||||||
const s = this.live.get(id);
|
const s = this.live.get(id);
|
||||||
return s ? this.summarize(s) : null;
|
return s ? this.summarize(s) : null;
|
||||||
@@ -401,30 +446,35 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
// ---- interne ----
|
// ---- interne ----
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Push P4-B : notifie sur le FRONT MONTANT vers `waiting` uniquement (le tracker réémet
|
* Push P4-B : notifie sur le FRONT MONTANT vers un état qui requiert l'attention — `waiting`
|
||||||
* souvent le même état), avec un debounce annulable — un `waiting` ultra-bref (Claude répond
|
* (un dialogue bloque) ou `idle` atteint depuis `busy` (Claude a terminé sa réponse, la session
|
||||||
* tout seul) ne déclenche pas de notif. Cible tous les abonnements (un seul utilisateur).
|
* 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 —
|
||||||
|
* à 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 {
|
private maybeNotify(s: ManagedSession, next: SessionActivity | null): void {
|
||||||
const prev = s.prevActivity;
|
const prev = s.prevActivity;
|
||||||
s.prevActivity = next;
|
s.prevActivity = next;
|
||||||
if (!this.push) return;
|
if (!this.push) return;
|
||||||
if (next === 'waiting' && prev !== 'waiting') {
|
const notifiable =
|
||||||
|
(next === 'waiting' && prev !== 'waiting') || (next === 'idle' && prev === 'busy');
|
||||||
|
if (notifiable) {
|
||||||
|
const target = next; // 'waiting' | 'idle'
|
||||||
if (s.notifyTimer) clearTimeout(s.notifyTimer);
|
if (s.notifyTimer) clearTimeout(s.notifyTimer);
|
||||||
s.notifyTimer = setTimeout(() => {
|
s.notifyTimer = setTimeout(() => {
|
||||||
s.notifyTimer = null;
|
s.notifyTimer = null;
|
||||||
const act = s.tracker?.snapshot();
|
const act = s.tracker?.snapshot();
|
||||||
if (s.exited || act?.activity !== 'waiting') return; // faux positif : annulé
|
if (s.exited || act?.activity !== target) return; // faux positif : l'état a déjà changé
|
||||||
void this.push?.notify({
|
const base = { sessionId: s.id, title: basename(s.cwd) || s.cwd, url: `/sessions/${s.id}` };
|
||||||
sessionId: s.id,
|
void this.push?.notify(
|
||||||
title: basename(s.cwd) || s.cwd,
|
target === 'idle'
|
||||||
body: act.dialog?.waitingFor ?? act.waitingFor ?? 'waiting for your input',
|
? { ...base, body: 'available for new instructions', kind: null }
|
||||||
kind: act.dialog?.kind ?? null,
|
: { ...base, body: act.dialog?.waitingFor ?? act.waitingFor ?? 'waiting for your input', kind: act.dialog?.kind ?? null },
|
||||||
url: `/sessions/${s.id}`,
|
);
|
||||||
});
|
|
||||||
}, NOTIFY_DEBOUNCE_MS);
|
}, NOTIFY_DEBOUNCE_MS);
|
||||||
s.notifyTimer.unref();
|
s.notifyTimer.unref();
|
||||||
} else if (next !== 'waiting' && s.notifyTimer) {
|
} else if (s.notifyTimer && next !== 'waiting' && next !== 'idle') {
|
||||||
|
// On quitte un état notifiable avant l'échéance (ex. Claude repart en busy) → annule.
|
||||||
clearTimeout(s.notifyTimer);
|
clearTimeout(s.notifyTimer);
|
||||||
s.notifyTimer = null;
|
s.notifyTimer = null;
|
||||||
}
|
}
|
||||||
|
|||||||
48
packages/server/src/core/retention-settings.ts
Normal file
48
packages/server/src/core/retention-settings.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
// Réglages de rétention des sessions terminées (archivage auto), persistés dans `settings`.
|
||||||
|
// Frontière de sécurité : clés NON sensibles, n'entrent dans l'allow-list du PATCH /api/v1/settings
|
||||||
|
// que via les validateurs ci-dessous. Calqué sur scan-settings.ts.
|
||||||
|
import { getSetting } from '../db/index.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
|
export const RETENTION_DAYS_KEY = 'session_retention_days';
|
||||||
|
export const PURGE_DAYS_KEY = 'session_purge_days';
|
||||||
|
|
||||||
|
/** Au-delà de N jours après la fin, une session managée est auto-archivée. 0 = jamais. */
|
||||||
|
export const DEFAULT_RETENTION_DAYS = 30;
|
||||||
|
/** Purge définitive (DELETE) après N jours. 0 = désactivée (conçue mais OFF par défaut). */
|
||||||
|
export const DEFAULT_PURGE_DAYS = 0;
|
||||||
|
export const MIN_RETENTION_DAYS = 1;
|
||||||
|
export const MAX_RETENTION_DAYS = 3650;
|
||||||
|
|
||||||
|
/** Rétention en jours (0 = jamais archiver). Défaut DEFAULT_RETENTION_DAYS. Lecture tolérante. */
|
||||||
|
export function readRetentionDays(db: Db): number {
|
||||||
|
return readDaysSetting(db, RETENTION_DAYS_KEY, DEFAULT_RETENTION_DAYS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Purge définitive en jours (0 = désactivée). Défaut DEFAULT_PURGE_DAYS. Lecture tolérante. */
|
||||||
|
export function readPurgeDays(db: Db): number {
|
||||||
|
return readDaysSetting(db, PURGE_DAYS_KEY, DEFAULT_PURGE_DAYS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readDaysSetting(db: Db, key: string, fallback: number): number {
|
||||||
|
const raw = getSetting(db, key);
|
||||||
|
if (raw === null) return fallback;
|
||||||
|
const n = Number(raw);
|
||||||
|
return isValidDays(n) ? n : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide un nombre de jours : entier `0` (= désactivé) OU dans [MIN, MAX]. Retourne null si invalide
|
||||||
|
* (⇒ 400). Le même validateur sert pour la rétention et la purge (mêmes bornes, même sémantique de 0).
|
||||||
|
*/
|
||||||
|
export function normalizeRetentionDays(raw: unknown): number | null {
|
||||||
|
return typeof raw === 'number' && isValidDays(raw) ? raw : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Alias sémantique pour la purge (mêmes règles). */
|
||||||
|
export const normalizePurgeDays = normalizeRetentionDays;
|
||||||
|
|
||||||
|
function isValidDays(n: number): boolean {
|
||||||
|
if (!Number.isInteger(n)) return false;
|
||||||
|
return n === 0 || (n >= MIN_RETENTION_DAYS && n <= MAX_RETENTION_DAYS);
|
||||||
|
}
|
||||||
75
packages/server/src/core/session-archive.ts
Normal file
75
packages/server/src/core/session-archive.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
// Archivage automatique des sessions terminées (P10). Scheduler calqué sur DiscoveryService :
|
||||||
|
// start()/stop() + setInterval().unref(). Soft-archive uniquement (jamais de DELETE dans cette
|
||||||
|
// itération ; la purge définitive est conçue mais désactivée par défaut, cf. retention-settings).
|
||||||
|
// Démarré dans runDaemon (jamais dans buildApp → ne tourne pas pendant les tests unitaires).
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import { archiveExpiredSessions, type Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from './audit-log.js';
|
||||||
|
import { readRetentionDays } from './retention-settings.js';
|
||||||
|
|
||||||
|
/** Balayage toutes les 6 h : la rétention se compte en jours, pas besoin de plus fréquent. */
|
||||||
|
const DEFAULT_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
||||||
|
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
export interface SessionArchiveEvents {
|
||||||
|
/** une session vient d'être archivée (relayée en `session_archived` par la gateway). */
|
||||||
|
session_archived: [{ id: string; archivedAt: string }];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionArchiveOptions {
|
||||||
|
db: Db;
|
||||||
|
intervalMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SessionArchiveService extends EventEmitter<SessionArchiveEvents> {
|
||||||
|
private readonly db: Db;
|
||||||
|
private readonly intervalMs: number;
|
||||||
|
private timer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
constructor(opts: SessionArchiveOptions) {
|
||||||
|
super();
|
||||||
|
this.db = opts.db;
|
||||||
|
this.intervalMs = opts.intervalMs ?? DEFAULT_SWEEP_INTERVAL_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
start(): void {
|
||||||
|
if (this.timer) return;
|
||||||
|
this.sweep(); // passage immédiat au boot (synchrone, bon marché : un seul UPDATE borné)
|
||||||
|
this.timer = setInterval(() => this.sweep(), this.intervalMs);
|
||||||
|
this.timer.unref(); // ne maintient pas le process en vie
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
if (this.timer) {
|
||||||
|
clearInterval(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Archive les sessions terminées plus anciennes que la rétention configurée. Retourne le nombre
|
||||||
|
* archivé. Tolérant : ne lève jamais (une erreur ne doit pas tuer le scheduler). `0 jour` = OFF.
|
||||||
|
*/
|
||||||
|
sweep(): number {
|
||||||
|
try {
|
||||||
|
const days = readRetentionDays(this.db);
|
||||||
|
if (days <= 0) return 0; // rétention désactivée
|
||||||
|
const now = new Date();
|
||||||
|
const archivedAt = now.toISOString();
|
||||||
|
const cutoffIso = new Date(now.getTime() - days * MS_PER_DAY).toISOString();
|
||||||
|
const ids = archiveExpiredSessions(this.db, archivedAt, cutoffIso);
|
||||||
|
for (const id of ids) {
|
||||||
|
this.emit('session_archived', { id, archivedAt });
|
||||||
|
recordAudit(this.db, { actor: 'system', action: 'session.autoArchive', resourceId: id });
|
||||||
|
}
|
||||||
|
return ids.length;
|
||||||
|
} catch {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
11
packages/server/src/core/settings-bus.ts
Normal file
11
packages/server/src/core/settings-bus.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
// Bus d'événements des réglages (P11) : la route PATCH /settings émet le snapshot non sensible
|
||||||
|
// après une mise à jour réussie ; la gateway WS le relaie aux abonnés du topic 'settings'. Découple
|
||||||
|
// les routes de la gateway (pas de dépendance directe), comme les EventEmitter des managers.
|
||||||
|
import { EventEmitter } from 'node:events';
|
||||||
|
import type { SettingsBroadcast } from '@arboretum/shared';
|
||||||
|
|
||||||
|
export interface SettingsBusEvents {
|
||||||
|
settings_update: [SettingsBroadcast];
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SettingsBus extends EventEmitter<SettingsBusEvents> {}
|
||||||
@@ -4,14 +4,16 @@
|
|||||||
import { EventEmitter } from 'node:events';
|
import { EventEmitter } from 'node:events';
|
||||||
import { execFile } from 'node:child_process';
|
import { execFile } from 'node:child_process';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { basename, dirname, join, resolve } from 'node:path';
|
import { basename, dirname, join, resolve, sep } from 'node:path';
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync, realpathSync } from 'node:fs';
|
||||||
import type {
|
import type {
|
||||||
DiscoverReposResponse,
|
DiscoverReposResponse,
|
||||||
HookRunResult,
|
HookRunResult,
|
||||||
PostCreateHook,
|
PostCreateHook,
|
||||||
RepoSummary,
|
RepoSummary,
|
||||||
SessionSummary,
|
SessionSummary,
|
||||||
|
WorktreeBranchAction,
|
||||||
|
WorktreeBranchMode,
|
||||||
WorktreeGitStatus,
|
WorktreeGitStatus,
|
||||||
WorktreeSummary,
|
WorktreeSummary,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
@@ -22,18 +24,35 @@ import { scanForRepos } from './repo-scanner.js';
|
|||||||
import { preTrustProject } from './claude-trust.js';
|
import { preTrustProject } from './claude-trust.js';
|
||||||
import {
|
import {
|
||||||
addWorktree,
|
addWorktree,
|
||||||
|
amendCommit,
|
||||||
|
cleanFiles,
|
||||||
|
commitAll,
|
||||||
|
commitStaged,
|
||||||
defaultBranch,
|
defaultBranch,
|
||||||
|
fetchRemote,
|
||||||
|
fileDiff,
|
||||||
isDirtyWorktreeError,
|
isDirtyWorktreeError,
|
||||||
isRepo,
|
isRepo,
|
||||||
isSafeAbsolutePath,
|
isSafeAbsolutePath,
|
||||||
|
isSafeRelativePath,
|
||||||
|
isUnpushed,
|
||||||
isValidBranchName,
|
isValidBranchName,
|
||||||
|
listBranches,
|
||||||
|
listChanges,
|
||||||
listWorktrees,
|
listWorktrees,
|
||||||
pruneWorktrees,
|
pruneWorktrees,
|
||||||
|
pull,
|
||||||
|
push,
|
||||||
removeWorktree,
|
removeWorktree,
|
||||||
|
restoreFiles,
|
||||||
|
stageFiles,
|
||||||
switchBranch,
|
switchBranch,
|
||||||
|
unstageFiles,
|
||||||
worktreeStatus,
|
worktreeStatus,
|
||||||
type ParsedWorktree,
|
type ParsedWorktree,
|
||||||
} from './git.js';
|
} from './git.js';
|
||||||
|
import type { FsWatcherService } from './fs-watcher.js';
|
||||||
|
import type { FileChange, FileDiffResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
const FACTS_TTL_MS = 2500;
|
const FACTS_TTL_MS = 2500;
|
||||||
const HOOK_TIMEOUT_MS = 5 * 60_000;
|
const HOOK_TIMEOUT_MS = 5 * 60_000;
|
||||||
@@ -59,6 +78,9 @@ export interface WorktreeManagerEvents {
|
|||||||
repo_removed: [string];
|
repo_removed: [string];
|
||||||
worktree_update: [{ repoId: string; worktree: WorktreeSummary }];
|
worktree_update: [{ repoId: string; worktree: WorktreeSummary }];
|
||||||
worktree_removed: [{ repoId: string; path: string }];
|
worktree_removed: [{ repoId: string; path: string }];
|
||||||
|
/** 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 }];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes. */
|
/** Erreur portant un statusCode + code pour mapping HTTP direct par les routes. */
|
||||||
@@ -111,8 +133,18 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
private readonly db: Db,
|
private readonly db: Db,
|
||||||
private readonly ptyManager: PtyManager,
|
private readonly ptyManager: PtyManager,
|
||||||
private readonly discovery: DiscoveryService,
|
private readonly discovery: DiscoveryService,
|
||||||
|
private readonly fsWatcher?: FsWatcherService,
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
|
// 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 }) => {
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (row) void this.emitWorktree(row, path).catch(() => {});
|
||||||
|
this.emit('worktree_changes', { repoId, path });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- repos ----
|
// ---- repos ----
|
||||||
@@ -170,9 +202,24 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
}
|
}
|
||||||
const summary = await this.rowToSummary(row);
|
const summary = await this.rowToSummary(row);
|
||||||
this.emit('repo_update', summary);
|
this.emit('repo_update', summary);
|
||||||
|
this.armRepoWatcher(row); // P11 : temps réel du checkout principal dès l'enregistrement
|
||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* P11 — arme un watcher PERMANENT sur le checkout principal de chaque repo visible : un
|
||||||
|
* `git checkout`/`switch` en CLI sur le principal est ainsi rediffusé en temps réel sans qu'un
|
||||||
|
* client ne l'ait « regardé ». Appelé depuis runDaemon (jamais buildApp → pas d'effet en tests purs).
|
||||||
|
*/
|
||||||
|
armMainCheckoutWatchers(): void {
|
||||||
|
const rows = this.db.prepare('SELECT id, path FROM repos WHERE hidden = 0').all() as Array<{ id: string; path: string }>;
|
||||||
|
for (const r of rows) this.armRepoWatcher(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
private armRepoWatcher(row: { id: string; path: string }): void {
|
||||||
|
this.fsWatcher?.pinRepo(row.id, resolve(row.path));
|
||||||
|
}
|
||||||
|
|
||||||
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
|
async updateRepo(id: string, patch: { label?: string; postCreateHooks?: PostCreateHook[]; preTrust?: boolean; hidden?: boolean }): Promise<RepoSummary> {
|
||||||
const row = this.getRepoRow(id);
|
const row = this.getRepoRow(id);
|
||||||
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
@@ -185,12 +232,19 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
|
.run(row.label, row.post_create_hooks, row.pre_trust, row.hidden, id);
|
||||||
const summary = await this.rowToSummary(row);
|
const summary = await this.rowToSummary(row);
|
||||||
this.emit('repo_update', summary);
|
this.emit('repo_update', summary);
|
||||||
|
// P11 : masqué → on libère le watcher permanent du principal ; ré-affiché → on le réarme.
|
||||||
|
if (patch.hidden !== undefined) {
|
||||||
|
if (row.hidden === 1) this.fsWatcher?.unpinRepo(id, resolve(row.path));
|
||||||
|
else this.armRepoWatcher(row);
|
||||||
|
}
|
||||||
return summary;
|
return summary;
|
||||||
}
|
}
|
||||||
|
|
||||||
removeRepo(id: string): boolean {
|
removeRepo(id: string): boolean {
|
||||||
|
const row = this.getRepoRow(id);
|
||||||
const res = this.db.prepare('DELETE FROM repos WHERE id = ?').run(id);
|
const res = this.db.prepare('DELETE FROM repos WHERE id = ?').run(id);
|
||||||
if (res.changes === 0) return false;
|
if (res.changes === 0) return false;
|
||||||
|
if (row) this.fsWatcher?.unpinRepo(id, resolve(row.path)); // P11 : libère le watcher permanent
|
||||||
this.factsCache.delete(id);
|
this.factsCache.delete(id);
|
||||||
this.emit('repo_removed', id);
|
this.emit('repo_removed', id);
|
||||||
return true;
|
return true;
|
||||||
@@ -238,6 +292,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (res.changes === 1) {
|
if (res.changes === 1) {
|
||||||
added++;
|
added++;
|
||||||
this.emit('repo_update', await this.rowToSummary(row)); // nouveaux uniquement
|
this.emit('repo_update', await this.rowToSummary(row)); // nouveaux uniquement
|
||||||
|
this.armRepoWatcher(row); // P11 : temps réel du checkout principal du repo découvert
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { scanned: paths.length, added, durationMs: Date.now() - t0, truncated };
|
return { scanned: paths.length, added, durationMs: Date.now() - t0, truncated };
|
||||||
@@ -245,10 +300,18 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
|
|
||||||
// ---- worktrees ----
|
// ---- worktrees ----
|
||||||
|
|
||||||
/** Sessions (managées + découvertes) dont le cwd correspond à ce chemin de worktree. */
|
/**
|
||||||
private sessionsForCwd(path: string): SessionSummary[] {
|
* 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`
|
||||||
|
* (sans quoi le masquage était ignoré dans les fiches worktree). Le tri managées/externes est laissé
|
||||||
|
* au client (interrupteur « afficher les externes »), qui dispose du champ `source`. La garde de
|
||||||
|
* suppression réclame en revanche TOUTES les sessions vivantes (`includeHidden`) pour rester sûre.
|
||||||
|
*/
|
||||||
|
private sessionsForCwd(path: string, opts?: { includeHidden?: boolean }): SessionSummary[] {
|
||||||
const rp = resolve(path);
|
const rp = resolve(path);
|
||||||
return mergeSessions(this.ptyManager.list(), this.discovery.list()).filter((s) => resolve(s.cwd) === rp);
|
return mergeSessions(this.ptyManager.list(), this.discovery.list())
|
||||||
|
.filter((s) => resolve(s.cwd) === rp)
|
||||||
|
.filter((s) => opts?.includeHidden || !s.hidden);
|
||||||
}
|
}
|
||||||
|
|
||||||
private toSummary(repoId: string, repoPath: string, w: ParsedWorktree, status: WorktreeGitStatus): WorktreeSummary {
|
private toSummary(repoId: string, repoPath: string, w: ParsedWorktree, status: WorktreeGitStatus): WorktreeSummary {
|
||||||
@@ -322,8 +385,8 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
|
|
||||||
async createWorktree(
|
async createWorktree(
|
||||||
repoId: string,
|
repoId: string,
|
||||||
req: { branch: string; newBranch: boolean; baseRef?: string; path?: string; runHooks?: boolean; preTrust?: boolean; startSession?: 'claude' | 'bash' | null },
|
req: { branch: string; mode?: WorktreeBranchMode; baseRef?: string; path?: string; runHooks?: boolean; preTrust?: boolean; startSession?: 'claude' | 'bash' | null },
|
||||||
): Promise<{ worktree: WorktreeSummary; hookResults: HookRunResult[]; session: SessionSummary | null }> {
|
): Promise<{ worktree: WorktreeSummary; hookResults: HookRunResult[]; session: SessionSummary | null; action: WorktreeBranchAction }> {
|
||||||
const row = this.getRepoRow(repoId);
|
const row = this.getRepoRow(repoId);
|
||||||
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
if (!isValidBranchName(req.branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${req.branch}`);
|
if (!isValidBranchName(req.branch)) throw httpError(400, 'BAD_BRANCH', `Invalid branch name: ${req.branch}`);
|
||||||
@@ -332,8 +395,9 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (existsSync(path)) throw httpError(409, 'PATH_EXISTS', `Path already exists: ${path}`);
|
if (existsSync(path)) throw httpError(409, 'PATH_EXISTS', `Path already exists: ${path}`);
|
||||||
|
|
||||||
return this.withLock(repoId, async () => {
|
return this.withLock(repoId, async () => {
|
||||||
|
let action: WorktreeBranchAction;
|
||||||
try {
|
try {
|
||||||
await addWorktree(row.path, { path, branch: req.branch, newBranch: req.newBranch, ...(req.baseRef ? { baseRef: req.baseRef } : {}) });
|
action = await addWorktree(row.path, { path, branch: req.branch, mode: req.mode ?? 'auto', ...(req.baseRef ? { baseRef: req.baseRef } : {}) });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw httpError(400, 'WORKTREE_ADD_FAILED', (err as Error).message);
|
throw httpError(400, 'WORKTREE_ADD_FAILED', (err as Error).message);
|
||||||
}
|
}
|
||||||
@@ -352,7 +416,258 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (req.startSession) session = this.ptyManager.spawn({ cwd: path, command: req.startSession });
|
if (req.startSession) session = this.ptyManager.spawn({ cwd: path, command: req.startSession });
|
||||||
|
|
||||||
const worktree = (await this.emitWorktree(row, path)) ?? this.toSummary(row.id, row.path, { path, head: null, branch: req.branch, detached: false, locked: false, prunable: false, bare: false }, { ahead: 0, behind: 0, dirtyCount: 0, upstream: null });
|
const worktree = (await this.emitWorktree(row, path)) ?? this.toSummary(row.id, row.path, { path, head: null, branch: req.branch, detached: false, locked: false, prunable: false, bare: false }, { ahead: 0, behind: 0, dirtyCount: 0, upstream: null });
|
||||||
return { worktree, hookResults, session };
|
return { worktree, hookResults, session, action };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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');
|
||||||
|
return listBranches(row.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commit dans le worktree visé. `mode='all'` (défaut, rétrocompat) = `git add -A` + commit ;
|
||||||
|
* `mode='staged'` = commit de l'index uniquement (staging sélectif préalable) ; `amend` réécrit
|
||||||
|
* le dernier commit (refusé s'il est déjà poussé). Le checkout principal est un worktree valide ici.
|
||||||
|
*/
|
||||||
|
async commitWorktree(
|
||||||
|
repoId: string,
|
||||||
|
path: string,
|
||||||
|
opts: { message: string; mode?: 'all' | 'staged'; amend?: boolean },
|
||||||
|
): Promise<WorktreeSummary> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
if (mode === 'staged' && (st.stagedCount ?? 0) === 0) {
|
||||||
|
throw httpError(409, 'NOTHING_STAGED', 'Nothing staged — stage files first');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (mode === 'all' && !opts.amend) await commitAll(w.path, opts.message);
|
||||||
|
else if (opts.amend) await amendCommit(w.path, opts.message);
|
||||||
|
else await commitStaged(w.path, opts.message);
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'COMMIT_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- P7 : changes / diff / staging / fetch-pull / contenu fichier / watch ----
|
||||||
|
|
||||||
|
/** Résout et valide un worktree enregistré ; lève 404 si le repo/worktree n'existe pas. */
|
||||||
|
private async requireWorktree(repoId: string, path: string): Promise<{ row: RepoRow; w: ParsedWorktree }> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
return { row, w };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Liste des fichiers modifiés d'un worktree (lecture, hors lock). */
|
||||||
|
async getWorktreeChanges(repoId: string, path: string): Promise<{ changes: FileChange[]; truncated: boolean }> {
|
||||||
|
const { w } = await this.requireWorktree(repoId, path);
|
||||||
|
return listChanges(w.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Diff unifié d'un fichier (détecte untracked → `git diff --no-index`). Lecture, hors lock. */
|
||||||
|
async getFileDiff(repoId: string, path: string, file: string, staged: boolean): Promise<FileDiffResponse> {
|
||||||
|
const { w } = await this.requireWorktree(repoId, path);
|
||||||
|
if (!isSafeRelativePath(file)) throw httpError(400, 'BAD_PATH', 'Invalid file path');
|
||||||
|
const { changes } = await listChanges(w.path);
|
||||||
|
const rec = changes.find((c) => c.path === file);
|
||||||
|
const untracked = !staged && (rec?.untracked ?? false);
|
||||||
|
const d = await fileDiff(w.path, file, { staged, untracked });
|
||||||
|
return { path: w.path, file, staged, binary: d.binary, tooLarge: d.tooLarge, diff: d.diff };
|
||||||
|
}
|
||||||
|
|
||||||
|
private validateFiles(files: string[]): void {
|
||||||
|
if (!Array.isArray(files) || files.length === 0) throw httpError(400, 'BAD_REQUEST', 'files (non-empty array) is required');
|
||||||
|
for (const f of files) {
|
||||||
|
if (typeof f !== 'string' || !isSafeRelativePath(f)) throw httpError(400, 'BAD_PATH', `Invalid file path: ${String(f)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Indexe des fichiers, puis rediffuse le statut. */
|
||||||
|
async stage(repoId: string, path: string, files: string[]): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
this.validateFiles(files);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await stageFiles(w.path, files).catch((err) => { throw httpError(400, 'STAGE_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Désindexe des fichiers, puis rediffuse le statut. */
|
||||||
|
async unstage(repoId: string, path: string, files: string[]): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
this.validateFiles(files);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await unstageFiles(w.path, files).catch((err) => { throw httpError(400, 'UNSTAGE_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Annule les changements locaux. Les fichiers SUIVIS sont restaurés (`git restore`) ; les fichiers
|
||||||
|
* NON SUIVIS ne sont supprimés (`git clean`) QUE si `includeUntracked` (destructif, opt-in).
|
||||||
|
*/
|
||||||
|
async discard(repoId: string, path: string, files: string[], includeUntracked: boolean): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
this.validateFiles(files);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
const { changes } = await listChanges(w.path);
|
||||||
|
const set = new Set(files);
|
||||||
|
const untracked = changes.filter((c) => set.has(c.path) && c.untracked).map((c) => c.path);
|
||||||
|
const tracked = files.filter((f) => !untracked.includes(f));
|
||||||
|
try {
|
||||||
|
await restoreFiles(w.path, tracked);
|
||||||
|
if (includeUntracked && untracked.length > 0) await cleanFiles(w.path, untracked);
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'DISCARD_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git fetch --all --prune` puis rediffuse le statut (ahead/behind à jour). */
|
||||||
|
async fetch(repoId: string, path: string): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await fetchRemote(w.path).catch((err) => { throw httpError(400, 'FETCH_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `git pull` (ff-only par défaut). */
|
||||||
|
async pull(repoId: string, path: string, mode: 'ff-only' | 'rebase' = 'ff-only'): Promise<WorktreeSummary> {
|
||||||
|
const { row, w } = await this.requireWorktree(repoId, path);
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
await pull(w.path, mode).catch((err) => { throw httpError(409, 'PULL_FAILED', (err as Error).message); });
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide qu'un chemin relatif désigne bien un fichier DANS un worktree enregistré et renvoie son
|
||||||
|
* chemin absolu résolu. Défense en profondeur (anti `..`, anti symlink sortant), même si un
|
||||||
|
* terminal web est déjà du RCE par conception. Utilisé par l'API fichiers (lecture/écriture Monaco).
|
||||||
|
*/
|
||||||
|
async assertPathInWorktree(repoId: string, worktreeAbsPath: string, relPath: string): Promise<string> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
if (!isSafeAbsolutePath(worktreeAbsPath)) throw httpError(400, 'BAD_PATH', 'Worktree path must be absolute and normalized');
|
||||||
|
const w = await this.findWorktree(row, worktreeAbsPath);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
if (!isSafeRelativePath(relPath)) throw httpError(400, 'BAD_PATH', 'Invalid file path');
|
||||||
|
const base = resolve(w.path);
|
||||||
|
const abs = resolve(join(base, relPath));
|
||||||
|
if (abs !== base && !abs.startsWith(base + sep)) throw httpError(403, 'PATH_OUTSIDE_WORKTREE', 'Path escapes the worktree');
|
||||||
|
// Anti symlink-escape : pour un fichier existant, le realpath doit rester sous le worktree.
|
||||||
|
if (existsSync(abs)) {
|
||||||
|
let real: string;
|
||||||
|
try {
|
||||||
|
real = realpathSync(abs);
|
||||||
|
} catch {
|
||||||
|
throw httpError(400, 'BAD_PATH', 'Cannot resolve path');
|
||||||
|
}
|
||||||
|
const realBase = realpathSync(base);
|
||||||
|
if (real !== realBase && !real.startsWith(realBase + sep)) throw httpError(403, 'PATH_OUTSIDE_WORKTREE', 'Path 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;
|
||||||
|
await this.requireWorktree(repoId, path);
|
||||||
|
this.fsWatcher.watch(repoId, resolve(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
unwatch(repoId: string, path: string): void {
|
||||||
|
this.fsWatcher?.unwatch(repoId, resolve(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pousse la branche du worktree visé (upstream auto si absent). */
|
||||||
|
async pushWorktree(repoId: string, path: string): Promise<WorktreeSummary> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
return this.withLock(repoId, async () => {
|
||||||
|
try {
|
||||||
|
await push(w.path);
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(400, 'PUSH_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* « Passer en principal » : la branche du worktree devient le checkout principal du dépôt. Une branche
|
||||||
|
* ne pouvant être extraite qu'à un seul endroit, on retire d'abord le worktree (libère la branche) puis
|
||||||
|
* on bascule le checkout principal dessus. Sans merge ni conflit possible. L'ancienne branche principale
|
||||||
|
* est conservée (jamais supprimée). Garde-fous d'arbre sale outrepassables par `force`.
|
||||||
|
*/
|
||||||
|
async promoteWorktree(repoId: string, path: string, force = false): Promise<WorktreeSummary | null> {
|
||||||
|
const row = this.getRepoRow(repoId);
|
||||||
|
if (!row) throw httpError(404, 'NOT_FOUND', 'No repo with this id');
|
||||||
|
const w = await this.findWorktree(row, path);
|
||||||
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
|
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'This is already the main checkout');
|
||||||
|
if (!w.branch || w.detached) throw httpError(400, 'DETACHED_WORKTREE', 'Worktree has no branch to promote (detached HEAD)');
|
||||||
|
const branch = w.branch;
|
||||||
|
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');
|
||||||
|
}
|
||||||
|
if ((await worktreeStatus(row.path)).dirtyCount > 0) {
|
||||||
|
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(500, 'WORKTREE_REMOVE_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await switchBranch(row.path, { branch, create: false });
|
||||||
|
} catch (err) {
|
||||||
|
throw httpError(500, 'SWITCH_FAILED', (err as Error).message);
|
||||||
|
}
|
||||||
|
this.factsCache.delete(repoId);
|
||||||
|
this.emit('worktree_removed', { repoId, path: w.path });
|
||||||
|
return this.emitWorktree(row, row.path); // le checkout principal est désormais sur `branch`
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -415,7 +730,7 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
if (!w) throw httpError(404, 'NOT_FOUND', 'No such worktree under this repo');
|
||||||
if (resolve(w.path) === resolve(row.path)) throw httpError(400, 'IS_MAIN_WORKTREE', 'Cannot remove the main worktree');
|
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.
|
// garde-fou : une session vivante tourne dans ce worktree → exiger une confirmation explicite.
|
||||||
if (!force && this.sessionsForCwd(w.path).some((s) => s.live)) {
|
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 () => {
|
return this.withLock(repoId, async () => {
|
||||||
|
|||||||
@@ -142,6 +142,55 @@ const MIGRATIONS: Array<{ id: number; sql: string }> = [
|
|||||||
);
|
);
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// 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
|
||||||
|
// s'applique qu'aux sessions managées en DB. Les deux filtres sont indépendants et cumulables.
|
||||||
|
id: 10,
|
||||||
|
sql: `
|
||||||
|
ALTER TABLE sessions ADD COLUMN archived_at TEXT;
|
||||||
|
CREATE INDEX idx_sessions_archived_at ON sessions(archived_at);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 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.
|
||||||
|
id: 11,
|
||||||
|
sql: `
|
||||||
|
CREATE TABLE git_credentials (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
service TEXT NOT NULL CHECK (service IN ('gitea','gitlab','github')),
|
||||||
|
base_url TEXT,
|
||||||
|
auth_type TEXT NOT NULL CHECK (auth_type IN ('pat','app_password','ssh_key','oauth')),
|
||||||
|
username TEXT,
|
||||||
|
secret_encrypted TEXT,
|
||||||
|
ssh_key_path TEXT,
|
||||||
|
oauth_access_encrypted TEXT,
|
||||||
|
oauth_refresh_encrypted TEXT,
|
||||||
|
oauth_expires_at TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
last_tested_at TEXT,
|
||||||
|
test_result TEXT
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_git_credentials_service ON git_credentials(service);
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// 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,
|
||||||
|
sql: `
|
||||||
|
ALTER TABLE repos ADD COLUMN remote_url TEXT;
|
||||||
|
ALTER TABLE repos ADD COLUMN git_service TEXT;
|
||||||
|
ALTER TABLE repos ADD COLUMN credential_id TEXT;
|
||||||
|
`,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export type Db = DatabaseSync;
|
export type Db = DatabaseSync;
|
||||||
@@ -218,3 +267,48 @@ export function hideSession(db: Db, claudeSessionId: string): void {
|
|||||||
export function unhideSession(db: Db, claudeSessionId: string): void {
|
export function unhideSession(db: Db, claudeSessionId: string): void {
|
||||||
db.prepare('DELETE FROM hidden_sessions WHERE claude_session_id = ?').run(claudeSessionId);
|
db.prepare('DELETE FROM hidden_sessions WHERE claude_session_id = ?').run(claudeSessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- 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 {
|
||||||
|
db.prepare('UPDATE sessions SET archived_at = ? WHERE id = ? AND archived_at IS NULL').run(archivedAt, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dés-archive une session (idempotent). La session reste reprenable/forkable (inchangé). */
|
||||||
|
export function unarchiveSession(db: Db, id: string): void {
|
||||||
|
db.prepare('UPDATE sessions SET archived_at = NULL WHERE id = ?').run(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** true si une session managée avec cet id existe en DB. */
|
||||||
|
export function sessionExists(db: Db, id: string): boolean {
|
||||||
|
return db.prepare('SELECT 1 FROM sessions WHERE id = ?').get(id) != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** true si la session existe en DB et est archivée. */
|
||||||
|
export function isSessionArchived(db: Db, id: string): boolean {
|
||||||
|
const row = db.prepare('SELECT archived_at FROM sessions WHERE id = ?').get(id) as { archived_at: string | null } | undefined;
|
||||||
|
return row != null && row.archived_at != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Archive en masse les sessions terminées plus anciennes que `cutoffIso` (comparaison lexicographique
|
||||||
|
* sur ended_at, format ISO UTC). Retourne les `id` archivés (pour émettre les events + auditer).
|
||||||
|
* SELECT puis UPDATE dans une transaction → la liste retournée correspond exactement aux lignes mutées.
|
||||||
|
* Les sessions vivantes (ended_at NULL) et déjà archivées sont exclues.
|
||||||
|
*/
|
||||||
|
export function archiveExpiredSessions(db: Db, archivedAt: string, cutoffIso: string): string[] {
|
||||||
|
db.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
const rows = db
|
||||||
|
.prepare('SELECT id FROM sessions WHERE ended_at IS NOT NULL AND ended_at < ? AND archived_at IS NULL')
|
||||||
|
.all(cutoffIso) as Array<{ id: string }>;
|
||||||
|
const stmt = db.prepare('UPDATE sessions SET archived_at = ? WHERE id = ?');
|
||||||
|
for (const r of rows) stmt.run(archivedAt, r.id);
|
||||||
|
db.exec('COMMIT');
|
||||||
|
return rows.map((r) => r.id);
|
||||||
|
} catch (err) {
|
||||||
|
db.exec('ROLLBACK');
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,22 +3,40 @@ import { readFileSync } from 'node:fs';
|
|||||||
import { join, dirname } from 'node:path';
|
import { join, dirname } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { loadConfig, type Config } from './config.js';
|
import { loadConfig, type Config } from './config.js';
|
||||||
import { openDb } from './db/index.js';
|
import { openDb, type Db } from './db/index.js';
|
||||||
import { buildApp } from './app.js';
|
import { buildApp } from './app.js';
|
||||||
|
import { readClaudeHome } from './core/claude-settings.js';
|
||||||
import { runInstall, runUninstall, runStatus, printUsage, printTokenBanner } from './cli/install.js';
|
import { runInstall, runUninstall, runStatus, printUsage, printTokenBanner } from './cli/install.js';
|
||||||
|
|
||||||
const pkg = JSON.parse(
|
const pkg = JSON.parse(
|
||||||
readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
|
readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf8'),
|
||||||
) as { version: string };
|
) as { version: string };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applique l'override `claude_home` (réglage UI) sur la config runtime, sauf si --claude-home a été
|
||||||
|
* passé explicitement (le flag gagne). Lu une seule fois au démarrage → un changement via l'UI prend
|
||||||
|
* effet au redémarrage du daemon (comme l'intervalle de scan). Mute `config`.
|
||||||
|
*/
|
||||||
|
function applyClaudeHomeOverride(config: Config, db: Db): void {
|
||||||
|
if (config.claudeHomeFromFlag) return;
|
||||||
|
const override = readClaudeHome(db);
|
||||||
|
if (!override) return;
|
||||||
|
config.claudeHome = override;
|
||||||
|
config.claudeProjectsDir = join(override, 'projects');
|
||||||
|
config.claudeSessionsDir = join(override, 'sessions');
|
||||||
|
}
|
||||||
|
|
||||||
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
/** Démarre le daemon : écoute HTTP, scan des sessions, drain propre au SIGTERM/SIGINT. */
|
||||||
export async function runDaemon(config: Config): Promise<void> {
|
export async function runDaemon(config: Config): Promise<void> {
|
||||||
const db = openDb(config.dbPath);
|
const db = openDb(config.dbPath);
|
||||||
const { app, auth, manager, discovery, repoDiscovery } = buildApp(config, db, pkg.version);
|
applyClaudeHomeOverride(config, db); // override claude_home (réglage UI) avant de câbler les services
|
||||||
|
const { app, auth, manager, discovery, sessionArchive, repoDiscovery, worktrees, fsWatcher } = buildApp(config, db, pkg.version);
|
||||||
|
|
||||||
const bootstrapToken = auth.ensureBootstrapToken();
|
const bootstrapToken = auth.ensureBootstrapToken();
|
||||||
await app.listen({ port: config.port, host: config.bind });
|
await app.listen({ port: config.port, host: config.bind });
|
||||||
discovery.start(); // scan initial + rafraîchissement périodique des sessions découvertes
|
discovery.start(); // scan initial + rafraîchissement périodique des sessions découvertes
|
||||||
|
sessionArchive.start(); // archivage auto des sessions terminées (rétention configurable)
|
||||||
|
worktrees.armMainCheckoutWatchers(); // P11 : temps réel du checkout principal de chaque repo
|
||||||
if (config.autoDiscover) repoDiscovery.start(); // découverte auto des repos : scan au boot + re-scan périodique
|
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}`;
|
const url = `http://${config.bind === '0.0.0.0' ? '127.0.0.1' : config.bind}:${config.port}`;
|
||||||
@@ -36,7 +54,9 @@ export async function runDaemon(config: Config): Promise<void> {
|
|||||||
shuttingDown = true;
|
shuttingDown = true;
|
||||||
app.log.info(`${signal} received — draining sessions then exiting`);
|
app.log.info(`${signal} received — draining sessions then exiting`);
|
||||||
discovery.stop();
|
discovery.stop();
|
||||||
|
sessionArchive.stop();
|
||||||
repoDiscovery.stop();
|
repoDiscovery.stop();
|
||||||
|
void fsWatcher.closeAll(); // libère les descripteurs des watchers FS
|
||||||
manager.shutdown();
|
manager.shutdown();
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
void app.close().then(() => process.exit(0));
|
void app.close().then(() => process.exit(0));
|
||||||
|
|||||||
96
packages/server/src/routes/files.ts
Normal file
96
packages/server/src/routes/files.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
// API fichiers (P7) pour l'éditeur Monaco : lecture/écriture du contenu d'un fichier, strictement
|
||||||
|
// bornées à un worktree ENREGISTRÉ (WorktreeManager.assertPathInWorktree : anti `..`, anti symlink
|
||||||
|
// sortant). Authentifiée par le hook preValidation global. Un terminal web est déjà du RCE par
|
||||||
|
// conception, mais on borne quand même (défense en profondeur + moindre étonnement).
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import { readFile, writeFile, stat, mkdir } from 'node:fs/promises';
|
||||||
|
import { dirname, extname } from 'node:path';
|
||||||
|
import type { FileContentResponse, WriteFileRequest, WriteFileResponse } from '@arboretum/shared';
|
||||||
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
|
const FILE_MAX_BYTES = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
/** Langage Monaco déduit de l'extension (sous-ensemble courant ; Monaco a un fallback 'plaintext'). */
|
||||||
|
const LANG_BY_EXT: Record<string, string> = {
|
||||||
|
'.ts': 'typescript', '.tsx': 'typescript', '.js': 'javascript', '.jsx': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript',
|
||||||
|
'.json': 'json', '.vue': 'vue', '.css': 'css', '.scss': 'scss', '.less': 'less', '.html': 'html', '.md': 'markdown',
|
||||||
|
'.py': 'python', '.rb': 'ruby', '.go': 'go', '.rs': 'rust', '.java': 'java', '.c': 'c', '.h': 'c', '.cpp': 'cpp', '.cc': 'cpp',
|
||||||
|
'.cs': 'csharp', '.php': 'php', '.sh': 'shell', '.bash': 'shell', '.zsh': 'shell', '.yml': 'yaml', '.yaml': 'yaml',
|
||||||
|
'.toml': 'toml', '.xml': 'xml', '.sql': 'sql', '.swift': 'swift', '.kt': 'kotlin', '.dart': 'dart', '.lua': 'lua',
|
||||||
|
};
|
||||||
|
|
||||||
|
function languageFor(path: string): string | undefined {
|
||||||
|
return LANG_BY_EXT[extname(path).toLowerCase()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Détecte un fichier binaire par présence d'un octet NUL dans le buffer. */
|
||||||
|
function looksBinary(buf: Buffer): boolean {
|
||||||
|
const n = Math.min(buf.length, 8192);
|
||||||
|
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerFileRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
|
// Lecture du contenu d'un fichier (UTF-8) d'un worktree.
|
||||||
|
app.get('/api/v1/repos/:id/files/content', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { wt?: string; path?: string };
|
||||||
|
if (typeof q.wt !== 'string' || q.wt === '' || typeof q.path !== 'string' || q.path === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'wt and path are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const abs = await wt.assertPathInWorktree(id, q.wt, q.path);
|
||||||
|
const st = await stat(abs).catch(() => null);
|
||||||
|
if (!st || !st.isFile()) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No such file' } });
|
||||||
|
if (st.size > FILE_MAX_BYTES) return reply.status(413).send({ error: { code: 'FILE_TOO_LARGE', message: `File exceeds ${FILE_MAX_BYTES} bytes` } });
|
||||||
|
const buf = await readFile(abs);
|
||||||
|
if (looksBinary(buf)) return reply.status(415).send({ error: { code: 'BINARY_FILE', message: 'Binary files are not editable' } });
|
||||||
|
const lang = languageFor(q.path);
|
||||||
|
const res: FileContentResponse = {
|
||||||
|
path: q.path,
|
||||||
|
content: buf.toString('utf-8'),
|
||||||
|
encoding: 'utf-8',
|
||||||
|
size: st.size,
|
||||||
|
mtime: st.mtimeMs,
|
||||||
|
...(lang ? { language: lang } : {}),
|
||||||
|
};
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Écriture (création/modification) du contenu d'un fichier d'un worktree.
|
||||||
|
app.put('/api/v1/repos/:id/files/content', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<WriteFileRequest> | null;
|
||||||
|
if (!body || typeof body.wt !== 'string' || typeof body.path !== 'string' || typeof body.content !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'wt, path and content are required' } });
|
||||||
|
}
|
||||||
|
if (Buffer.byteLength(body.content, 'utf-8') > FILE_MAX_BYTES) {
|
||||||
|
return reply.status(413).send({ error: { code: 'FILE_TOO_LARGE', message: `Content exceeds ${FILE_MAX_BYTES} bytes` } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const abs = await wt.assertPathInWorktree(id, body.wt, body.path);
|
||||||
|
// Garde-fou conflit (P8) : si le client a chargé le fichier (baseMtime) et qu'il a changé
|
||||||
|
// depuis (ex. Claude a écrit en parallèle), on refuse pour ne pas écraser silencieusement.
|
||||||
|
if (typeof body.baseMtime === 'number') {
|
||||||
|
const cur = await stat(abs).catch(() => null);
|
||||||
|
if (cur && cur.isFile() && cur.mtimeMs !== body.baseMtime) {
|
||||||
|
return reply.status(409).send({ error: { code: 'STALE_FILE', message: 'File changed on disk since it was loaded' } });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await mkdir(dirname(abs), { recursive: true }); // dirname reste sous le worktree (abs validé)
|
||||||
|
await writeFile(abs, body.content, 'utf-8');
|
||||||
|
const after = await stat(abs);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'file.write', resourceId: id, details: { path: body.path } });
|
||||||
|
const res: WriteFileResponse = { ok: true, size: Buffer.byteLength(body.content, 'utf-8'), mtime: after.mtimeMs };
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ import type { FsEntry, FsListResponse } from '@arboretum/shared';
|
|||||||
*/
|
*/
|
||||||
export function registerFsRoutes(app: FastifyInstance): void {
|
export function registerFsRoutes(app: FastifyInstance): void {
|
||||||
app.get('/api/v1/fs/list', async (req, reply) => {
|
app.get('/api/v1/fs/list', async (req, reply) => {
|
||||||
const q = req.query as { path?: string; markRepos?: string; showHidden?: string };
|
const q = req.query as { path?: string; markRepos?: string; showHidden?: string; includeFiles?: string };
|
||||||
const raw = q.path && q.path.length > 0 ? q.path : homedir();
|
const raw = q.path && q.path.length > 0 ? q.path : homedir();
|
||||||
if (!raw.startsWith('/')) {
|
if (!raw.startsWith('/')) {
|
||||||
return reply.status(400).send({ error: { code: 'BAD_PATH', message: 'path must be absolute' } });
|
return reply.status(400).send({ error: { code: 'BAD_PATH', message: 'path must be absolute' } });
|
||||||
@@ -41,6 +41,7 @@ export function registerFsRoutes(app: FastifyInstance): void {
|
|||||||
|
|
||||||
const markRepos = q.markRepos === '1' || q.markRepos === 'true';
|
const markRepos = q.markRepos === '1' || q.markRepos === 'true';
|
||||||
const showHidden = q.showHidden === '1' || q.showHidden === 'true';
|
const showHidden = q.showHidden === '1' || q.showHidden === 'true';
|
||||||
|
const includeFiles = q.includeFiles === '1' || q.includeFiles === 'true';
|
||||||
|
|
||||||
let dirents;
|
let dirents;
|
||||||
try {
|
try {
|
||||||
@@ -63,13 +64,24 @@ export function registerFsRoutes(app: FastifyInstance): void {
|
|||||||
isDir = false;
|
isDir = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!isDir) continue;
|
|
||||||
const full = join(abs, d.name);
|
const full = join(abs, d.name);
|
||||||
|
if (!isDir) {
|
||||||
|
// En mode includeFiles, on remonte aussi les fichiers (arbre de l'IDE worktree).
|
||||||
|
if (!includeFiles) continue;
|
||||||
|
entries.push({ name: d.name, path: full, isFile: true });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const entry: FsEntry = { name: d.name, path: full };
|
const entry: FsEntry = { name: d.name, path: full };
|
||||||
if (markRepos && existsSync(join(full, '.git'))) entry.isRepo = true;
|
if (markRepos && existsSync(join(full, '.git'))) entry.isRepo = true;
|
||||||
entries.push(entry);
|
entries.push(entry);
|
||||||
}
|
}
|
||||||
entries.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
|
// Dossiers d'abord, puis fichiers ; tri insensible à la casse dans chaque groupe.
|
||||||
|
entries.sort((a, b) => {
|
||||||
|
const af = a.isFile ? 1 : 0;
|
||||||
|
const bf = b.isFile ? 1 : 0;
|
||||||
|
if (af !== bf) return af - bf;
|
||||||
|
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
|
||||||
|
});
|
||||||
|
|
||||||
const res: FsListResponse = {
|
const res: FsListResponse = {
|
||||||
path: abs,
|
path: abs,
|
||||||
|
|||||||
119
packages/server/src/routes/git-connections.ts
Normal file
119
packages/server/src/routes/git-connections.ts
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
// Routes des services git distants (P12) : CRUD des credentials (secrets JAMAIS renvoyés), test de
|
||||||
|
// connexion, listing des dépôts distants, et lancement/suivi d'un clone. Authentifiées par le hook
|
||||||
|
// preValidation global. Les secrets sont chiffrés par SecretBox dans le manager.
|
||||||
|
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||||
|
import type {
|
||||||
|
CloneRequest,
|
||||||
|
CloneStartResponse,
|
||||||
|
CloneStatusResponse,
|
||||||
|
CreateGitCredentialRequest,
|
||||||
|
GitCredentialResponse,
|
||||||
|
GitCredentialsListResponse,
|
||||||
|
RemoteReposResponse,
|
||||||
|
UpdateGitCredentialRequest,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import type { GitCredentialsManager } from '../core/git-credentials.js';
|
||||||
|
import type { CloneManager } from '../core/clone-manager.js';
|
||||||
|
import { getGitClient, GitServiceError } from '../core/git-clients/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
|
function sendError(reply: FastifyReply, err: unknown): FastifyReply {
|
||||||
|
const e = err as { statusCode?: number; code?: string; message?: string };
|
||||||
|
const status = typeof e.statusCode === 'number' ? e.statusCode : 500;
|
||||||
|
return reply.status(status).send({ error: { code: e.code ?? 'INTERNAL', message: e.message ?? 'Internal error' } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const GIT_SERVICE_ERROR_STATUS: Record<string, number> = { AUTH_FAILED: 401, RATE_LIMITED: 429, UNREACHABLE: 502, BAD_BASE_URL: 400 };
|
||||||
|
|
||||||
|
export function registerGitConnectionRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
credentials: GitCredentialsManager,
|
||||||
|
clones: CloneManager,
|
||||||
|
db: Db,
|
||||||
|
): void {
|
||||||
|
const actor = (req: { authContext?: { tokenId: string } | null }): string => req.authContext?.tokenId ?? 'unknown';
|
||||||
|
|
||||||
|
app.get('/api/v1/git-connections', async (): Promise<GitCredentialsListResponse> => ({ credentials: credentials.list() }));
|
||||||
|
|
||||||
|
app.post('/api/v1/git-connections', async (req, reply) => {
|
||||||
|
try {
|
||||||
|
const cred = credentials.create((req.body ?? {}) as CreateGitCredentialRequest);
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.create', resourceId: cred.id, details: { service: cred.service, authType: cred.authType } });
|
||||||
|
const res: GitCredentialResponse = { credential: cred };
|
||||||
|
return reply.status(201).send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.patch('/api/v1/git-connections/:id', async (req, reply) => {
|
||||||
|
try {
|
||||||
|
const cred = credentials.update((req.params as { id: string }).id, (req.body ?? {}) as UpdateGitCredentialRequest);
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.update', resourceId: cred.id });
|
||||||
|
const res: GitCredentialResponse = { credential: cred };
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/v1/git-connections/:id', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!credentials.remove(id)) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No credential with this id' } });
|
||||||
|
}
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.delete', resourceId: id });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/v1/git-connections/:id/test', async (req, reply) => {
|
||||||
|
try {
|
||||||
|
const result = await credentials.test((req.params as { id: string }).id);
|
||||||
|
recordAudit(db, { actor: actor(req), action: 'git_credential.test', resourceId: (req.params as { id: string }).id, details: { ok: result.ok } });
|
||||||
|
return reply.send(result);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/git-connections/:id/repos', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { page?: string; search?: string };
|
||||||
|
const ctx = credentials.authContext(id);
|
||||||
|
if (!ctx) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No usable credential with this id' } });
|
||||||
|
const page = Math.max(1, Number(q.page) || 1);
|
||||||
|
try {
|
||||||
|
const { repos, nextPage } = await getGitClient(ctx.service, ctx.baseUrl).listRepos(ctx.auth, page, q.search);
|
||||||
|
const res: RemoteReposResponse = { repos, nextPage };
|
||||||
|
return reply.send(res);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof GitServiceError) {
|
||||||
|
return reply.status(GIT_SERVICE_ERROR_STATUS[err.errorCode] ?? 502).send({ error: { code: err.errorCode, message: err.message } });
|
||||||
|
}
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- Clone (asynchrone : 202 + suivi WS/REST) ----
|
||||||
|
app.post('/api/v1/repos/clone', async (req, reply) => {
|
||||||
|
const body = (req.body ?? {}) as Partial<CloneRequest>;
|
||||||
|
if (typeof body.credentialId !== 'string' || typeof body.remoteUrl !== 'string' || typeof body.dest !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'credentialId, remoteUrl and dest are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const operationId = await clones.start({ credentialId: body.credentialId, remoteUrl: body.remoteUrl, dest: body.dest }, actor(req));
|
||||||
|
const res: CloneStartResponse = { operationId };
|
||||||
|
return reply.status(202).send(res);
|
||||||
|
} catch (err) {
|
||||||
|
return sendError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/repos/clone/:id', async (req, reply) => {
|
||||||
|
const op = clones.get((req.params as { id: string }).id);
|
||||||
|
if (!op) return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No clone operation with this id' } });
|
||||||
|
const res: CloneStatusResponse = { operation: op };
|
||||||
|
return reply.send(res);
|
||||||
|
});
|
||||||
|
}
|
||||||
132
packages/server/src/routes/git.ts
Normal file
132
packages/server/src/routes/git.ts
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
// Routes git « IDE » (P7) : diff par fichier, statut détaillé, staging sélectif, discard, fetch, pull.
|
||||||
|
// Toutes authentifiées par le hook preValidation global (/api/**), validées strictement et auditées.
|
||||||
|
// Le commit (sélectif/amend) reste sur POST /worktrees/commit (routes/worktrees.ts) pour ne pas
|
||||||
|
// dupliquer la sémantique.
|
||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import type {
|
||||||
|
WorktreeChangesResponse,
|
||||||
|
FileDiffResponse,
|
||||||
|
WorktreeFilesRequest,
|
||||||
|
DiscardFilesRequest,
|
||||||
|
FetchWorktreeRequest,
|
||||||
|
PullWorktreeRequest,
|
||||||
|
WorktreeResponse,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
|
export function registerGitRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
|
// Liste des fichiers modifiés d'un worktree (statut détaillé + stats +/-).
|
||||||
|
app.get('/api/v1/repos/:id/worktrees/changes', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { path?: string };
|
||||||
|
if (typeof q.path !== 'string' || q.path === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { changes, truncated } = await wt.getWorktreeChanges(id, q.path);
|
||||||
|
return reply.send({ repoId: id, path: q.path, changes, truncated } satisfies WorktreeChangesResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Diff unifié d'un fichier (staged ou non ; untracked détecté côté manager).
|
||||||
|
app.get('/api/v1/repos/:id/worktrees/diff', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const q = req.query as { path?: string; file?: string; staged?: string };
|
||||||
|
if (typeof q.path !== 'string' || q.path === '' || typeof q.file !== 'string' || q.file === '') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and file are required' } });
|
||||||
|
}
|
||||||
|
const staged = q.staged === '1' || q.staged === 'true';
|
||||||
|
try {
|
||||||
|
const res = await wt.getFileDiff(id, q.path, q.file, staged);
|
||||||
|
return reply.send(res satisfies FileDiffResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Staging sélectif.
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/stage', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<WorktreeFilesRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.stage(id, body.path, body.files);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.stage', resourceId: id, details: { path: body.path, count: body.files.length } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Désindexation sélective.
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/unstage', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<WorktreeFilesRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.unstage(id, body.path, body.files);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.unstage', resourceId: id, details: { path: body.path, count: body.files.length } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Annulation des changements locaux (restore ; clean des untracked uniquement si includeUntracked).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/discard', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<DiscardFilesRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string' || !Array.isArray(body.files)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path and files are required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.discard(id, body.path, body.files, body.includeUntracked === true);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.discard', resourceId: id, details: { path: body.path, count: body.files.length, includeUntracked: body.includeUntracked === true } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fetch (--all --prune) : actualise ahead/behind.
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/fetch', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<FetchWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.fetch(id, body.path);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.fetch', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pull (ff-only par défaut, rebase optionnel).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/pull', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<PullWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
const mode = body.mode === 'rebase' ? 'rebase' : 'ff-only';
|
||||||
|
try {
|
||||||
|
const worktree = await wt.pull(id, body.path, mode);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'git.pull', resourceId: id, details: { path: body.path, mode } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -139,7 +139,8 @@ export function registerGroupRoutes(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (dirs.length === 0) {
|
if (dirs.length === 0) {
|
||||||
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'no directory to span (group has no resolvable worktree)' } });
|
const detail = branch ? `no repo has a worktree on branch "${branch}" (create it first)` : 'no repo has a resolvable main checkout';
|
||||||
|
return reply.status(400).send({ error: { code: 'NO_RESOLVABLE_WORKTREE', message: `Cannot start group session: ${detail}` } });
|
||||||
}
|
}
|
||||||
// cwd = parent commun des repos couverts, chacun relié en --add-dir (P6). Voir resolveGroupCwd.
|
// cwd = parent commun des repos couverts, chacun relié en --add-dir (P6). Voir resolveGroupCwd.
|
||||||
const { cwd, addDirs } = resolveGroupCwd(dirs);
|
const { cwd, addDirs } = resolveGroupCwd(dirs);
|
||||||
|
|||||||
89
packages/server/src/routes/projects.ts
Normal file
89
packages/server/src/routes/projects.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
import { mkdir, stat } from 'node:fs/promises';
|
||||||
|
import type { CreateProjectRequest, CreateProjectResponse } from '@arboretum/shared';
|
||||||
|
import type { PtyManager } from '../core/pty-manager.js';
|
||||||
|
import { gitInit, isSafeAbsolutePath } from '../core/git.js';
|
||||||
|
import { resolveProjectDir } from '../core/project.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Création d'un nouveau projet : crée le dossier `<root>/<name>` (la SEULE écriture fs autorisée
|
||||||
|
* côté serveur en dehors du dataDir) puis lance une session dedans. `git init` optionnel.
|
||||||
|
* Cohérent avec le modèle de sécurité : un client authentifié dispose déjà d'un terminal (RCE par
|
||||||
|
* conception). On valide tout de même strictement `name` (anti-traversal) et on exige une racine
|
||||||
|
* EXISTANTE (mkdir non récursif → pas de création d'arborescence arbitraire).
|
||||||
|
*
|
||||||
|
* POST /api/v1/projects { root, name, gitInit?, command? } → 201 { session, path, gitInitialized }
|
||||||
|
*/
|
||||||
|
export function registerProjectRoutes(app: FastifyInstance, manager: PtyManager, db: Db): void {
|
||||||
|
app.post('/api/v1/projects', async (req, reply) => {
|
||||||
|
const body = req.body as Partial<CreateProjectRequest> | null;
|
||||||
|
if (!body || typeof body.root !== 'string' || !isSafeAbsolutePath(body.root)) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'root (absolute path) is required' } });
|
||||||
|
}
|
||||||
|
if (typeof body.name !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'name is required' } });
|
||||||
|
}
|
||||||
|
if (body.command !== undefined && body.command !== 'claude' && body.command !== 'bash') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'command must be claude or bash' } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// La racine doit exister et être un répertoire (mkdir non récursif derrière).
|
||||||
|
try {
|
||||||
|
const st = await stat(body.root);
|
||||||
|
if (!st.isDirectory()) {
|
||||||
|
return reply.status(400).send({ error: { code: 'NOT_A_DIRECTORY', message: `Not a directory: ${body.root}` } });
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const code = (err as NodeJS.ErrnoException).code;
|
||||||
|
if (code === 'ENOENT') return reply.status(404).send({ error: { code: 'NOT_FOUND', message: `No such directory: ${body.root}` } });
|
||||||
|
if (code === 'EACCES') return reply.status(403).send({ error: { code: 'FORBIDDEN', message: `Permission denied: ${body.root}` } });
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_PATH', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
try {
|
||||||
|
dir = resolveProjectDir(body.root, body.name);
|
||||||
|
} catch (err) {
|
||||||
|
return reply.status((err as { statusCode?: number }).statusCode ?? 400).send({ error: { code: 'BAD_REQUEST', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// mkdir non récursif : EEXIST → 409 (on n'écrase jamais un dossier existant).
|
||||||
|
try {
|
||||||
|
await mkdir(dir);
|
||||||
|
} catch (err) {
|
||||||
|
const code = (err as NodeJS.ErrnoException).code;
|
||||||
|
if (code === 'EEXIST') return reply.status(409).send({ error: { code: 'PROJECT_EXISTS', message: `Already exists: ${dir}` } });
|
||||||
|
if (code === 'EACCES') return reply.status(403).send({ error: { code: 'FORBIDDEN', message: `Permission denied: ${dir}` } });
|
||||||
|
return reply.status(400).send({ error: { code: 'MKDIR_FAILED', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const wantsGitInit = body.gitInit === true;
|
||||||
|
let gitInitialized = false;
|
||||||
|
if (wantsGitInit) {
|
||||||
|
try {
|
||||||
|
await gitInit(dir);
|
||||||
|
gitInitialized = true;
|
||||||
|
} catch {
|
||||||
|
// Le dossier est créé et la session démarrera quand même : un échec git n'annule pas le projet.
|
||||||
|
gitInitialized = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = manager.spawn({ cwd: dir, ...(body.command ? { command: body.command } : {}) });
|
||||||
|
recordAudit(db, {
|
||||||
|
actor: req.authContext?.tokenId ?? 'unknown',
|
||||||
|
action: 'project.create',
|
||||||
|
resourceId: dir,
|
||||||
|
details: { gitInit: gitInitialized },
|
||||||
|
});
|
||||||
|
const res: CreateProjectResponse = { session, path: dir, gitInitialized };
|
||||||
|
return reply.status(201).send(res);
|
||||||
|
} catch (err) {
|
||||||
|
const statusCode = (err as { statusCode?: number }).statusCode ?? 500;
|
||||||
|
return reply.status(statusCode).send({ error: { code: 'SPAWN_FAILED', message: (err as Error).message } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -2,13 +2,24 @@ import type { FastifyInstance } from 'fastify';
|
|||||||
import type { CreateSessionRequest, HideDiscoveredResponse, SessionResponse, SessionsListResponse } from '@arboretum/shared';
|
import type { CreateSessionRequest, HideDiscoveredResponse, SessionResponse, SessionsListResponse } from '@arboretum/shared';
|
||||||
import type { PtyManager } from '../core/pty-manager.js';
|
import type { PtyManager } from '../core/pty-manager.js';
|
||||||
import { mergeSessions, type DiscoveryService } from '../core/discovery-service.js';
|
import { mergeSessions, type DiscoveryService } from '../core/discovery-service.js';
|
||||||
import { hideSession, unhideSession, type Db } from '../db/index.js';
|
import type { SessionArchiveService } from '../core/session-archive.js';
|
||||||
|
import { archiveSession, hideSession, sessionExists, unarchiveSession, unhideSession, type Db } from '../db/index.js';
|
||||||
import { recordAudit } from '../core/audit-log.js';
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
|
||||||
export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager, discovery: DiscoveryService, db: Db): void {
|
export function registerSessionRoutes(
|
||||||
|
app: FastifyInstance,
|
||||||
|
manager: PtyManager,
|
||||||
|
discovery: DiscoveryService,
|
||||||
|
sessionArchive: SessionArchiveService,
|
||||||
|
db: Db,
|
||||||
|
): void {
|
||||||
app.get('/api/v1/sessions', async (req): Promise<SessionsListResponse> => {
|
app.get('/api/v1/sessions', async (req): Promise<SessionsListResponse> => {
|
||||||
const includeHidden = (req.query as { includeHidden?: string }).includeHidden === 'true';
|
const q = req.query as { includeHidden?: string; includeArchived?: string };
|
||||||
const all = mergeSessions(manager.list(), discovery.list());
|
const includeHidden = q.includeHidden === 'true';
|
||||||
|
const includeArchived = q.includeArchived === 'true';
|
||||||
|
// `includeArchived` ne concerne QUE les sessions managées (manager.list) ; les découvertes
|
||||||
|
// n'ont pas de notion d'archivage. `hidden` est filtré ensuite, indépendamment.
|
||||||
|
const all = mergeSessions(manager.list({ includeArchived }), discovery.list());
|
||||||
return { sessions: includeHidden ? all : all.filter((s) => !s.hidden) };
|
return { sessions: includeHidden ? all : all.filter((s) => !s.hidden) };
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -135,6 +146,40 @@ export function registerSessionRoutes(app: FastifyInstance, manager: PtyManager,
|
|||||||
return reply.send(res);
|
return reply.send(res);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Archive manuellement une session managée terminée (soft-archive). Exclue de la liste par défaut,
|
||||||
|
// reste reprenable/forkable. 404 si l'id n'est pas une session managée connue en DB.
|
||||||
|
app.post('/api/v1/sessions/:id/archive', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!sessionExists(db, id)) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No managed session with this id to archive' } });
|
||||||
|
}
|
||||||
|
const archivedAt = new Date().toISOString();
|
||||||
|
archiveSession(db, id, archivedAt);
|
||||||
|
sessionArchive.emitArchived(id, archivedAt); // diffuse aux clients abonnés (session_archived)
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.archive', resourceId: id });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Dés-archive une session : ré-émet un session_update pour que tous les clients ré-affichent le row.
|
||||||
|
app.delete('/api/v1/sessions/:id/archive', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
if (!sessionExists(db, id)) {
|
||||||
|
return reply.status(404).send({ error: { code: 'NOT_FOUND', message: 'No managed session with this id to unarchive' } });
|
||||||
|
}
|
||||||
|
unarchiveSession(db, id);
|
||||||
|
manager.emitHistoricalUpdate(id);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.unarchive', resourceId: id });
|
||||||
|
return reply.send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Déclenche un balayage d'archivage immédiat (rétention configurée). Renvoie le nombre archivé.
|
||||||
|
// Pratique pour l'UX et pour une acceptance déterministe (sans attendre le scheduler ~6 h).
|
||||||
|
app.post('/api/v1/sessions/archive-now', async (req, reply) => {
|
||||||
|
const archived = sessionArchive.sweep();
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'session.archiveNow', resourceId: null, details: { archived } });
|
||||||
|
return reply.send({ archived });
|
||||||
|
});
|
||||||
|
|
||||||
app.delete('/api/v1/sessions/:id', async (req, reply) => {
|
app.delete('/api/v1/sessions/:id', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
if (!manager.kill(id)) {
|
if (!manager.kill(id)) {
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ import type { ServerInfo, SettingsResponse, UpdateSettingsRequest } from '@arbor
|
|||||||
import type { Config } from '../config.js';
|
import type { Config } from '../config.js';
|
||||||
import { type Db, setSetting } from '../db/index.js';
|
import { type Db, setSetting } from '../db/index.js';
|
||||||
import type { PushService } from '../core/push-service.js';
|
import type { PushService } from '../core/push-service.js';
|
||||||
|
import type { SettingsBus } from '../core/settings-bus.js';
|
||||||
import { recordAudit } from '../core/audit-log.js';
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
|
import { diagnoseClaudeBin } from '../core/claude-launcher.js';
|
||||||
import {
|
import {
|
||||||
SCAN_INTERVAL_KEY,
|
SCAN_INTERVAL_KEY,
|
||||||
SCAN_ROOTS_KEY,
|
SCAN_ROOTS_KEY,
|
||||||
@@ -15,6 +17,22 @@ import {
|
|||||||
readScanIntervalMin,
|
readScanIntervalMin,
|
||||||
readScanRoots,
|
readScanRoots,
|
||||||
} from '../core/scan-settings.js';
|
} from '../core/scan-settings.js';
|
||||||
|
import {
|
||||||
|
CLAUDE_BIN_PATH_KEY,
|
||||||
|
CLAUDE_HOME_KEY,
|
||||||
|
normalizeClaudeBinPath,
|
||||||
|
normalizeClaudeHome,
|
||||||
|
readClaudeBinPath,
|
||||||
|
readClaudeHome,
|
||||||
|
} from '../core/claude-settings.js';
|
||||||
|
import {
|
||||||
|
PURGE_DAYS_KEY,
|
||||||
|
RETENTION_DAYS_KEY,
|
||||||
|
normalizePurgeDays,
|
||||||
|
normalizeRetentionDays,
|
||||||
|
readPurgeDays,
|
||||||
|
readRetentionDays,
|
||||||
|
} from '../core/retention-settings.js';
|
||||||
|
|
||||||
// Réglages modifiables via l'API (allow-list stricte). Les secrets ne figurent JAMAIS ici.
|
// Réglages modifiables via l'API (allow-list stricte). Les secrets ne figurent JAMAIS ici.
|
||||||
export function registerSettingsRoutes(
|
export function registerSettingsRoutes(
|
||||||
@@ -23,6 +41,7 @@ export function registerSettingsRoutes(
|
|||||||
config: Config,
|
config: Config,
|
||||||
serverVersion: string,
|
serverVersion: string,
|
||||||
push: PushService,
|
push: PushService,
|
||||||
|
settingsBus: SettingsBus,
|
||||||
): void {
|
): void {
|
||||||
const serverInfo = (): ServerInfo => ({
|
const serverInfo = (): ServerInfo => ({
|
||||||
version: serverVersion,
|
version: serverVersion,
|
||||||
@@ -32,11 +51,18 @@ export function registerSettingsRoutes(
|
|||||||
dataDir: config.dataDir,
|
dataDir: config.dataDir,
|
||||||
vapidPublicKey: push.publicKey() || null,
|
vapidPublicKey: push.publicKey() || null,
|
||||||
vapidContact: config.vapidContact,
|
vapidContact: config.vapidContact,
|
||||||
|
claudeHome: config.claudeHome,
|
||||||
|
// Diagnostic recalculé à chaque GET : reflète l'état réel (override exécutable ? `which claude` ?).
|
||||||
|
claudeBin: diagnoseClaudeBin(readClaudeBinPath(db)),
|
||||||
});
|
});
|
||||||
const snapshot = (): SettingsResponse => ({
|
const snapshot = (): SettingsResponse => ({
|
||||||
settings: {
|
settings: {
|
||||||
scanRoots: readScanRoots(db),
|
scanRoots: readScanRoots(db),
|
||||||
scanIntervalMin: readScanIntervalMin(db),
|
scanIntervalMin: readScanIntervalMin(db),
|
||||||
|
claudeBinPath: readClaudeBinPath(db),
|
||||||
|
claudeHome: readClaudeHome(db),
|
||||||
|
retentionDays: readRetentionDays(db),
|
||||||
|
purgeDays: readPurgeDays(db),
|
||||||
},
|
},
|
||||||
server: serverInfo(),
|
server: serverInfo(),
|
||||||
});
|
});
|
||||||
@@ -59,11 +85,42 @@ export function registerSettingsRoutes(
|
|||||||
}
|
}
|
||||||
setSetting(db, SCAN_INTERVAL_KEY, String(interval));
|
setSetting(db, SCAN_INTERVAL_KEY, String(interval));
|
||||||
}
|
}
|
||||||
|
if ('claudeBinPath' in body) {
|
||||||
|
const value = normalizeClaudeBinPath(body.claudeBinPath);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'claudeBinPath must be an absolute path to an executable file (or "" to reset)' } });
|
||||||
|
}
|
||||||
|
setSetting(db, CLAUDE_BIN_PATH_KEY, value);
|
||||||
|
}
|
||||||
|
if ('claudeHome' in body) {
|
||||||
|
const value = normalizeClaudeHome(body.claudeHome);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'claudeHome must be an absolute path to an existing directory (or "" to reset)' } });
|
||||||
|
}
|
||||||
|
setSetting(db, CLAUDE_HOME_KEY, value);
|
||||||
|
}
|
||||||
|
if ('retentionDays' in body) {
|
||||||
|
const value = normalizeRetentionDays(body.retentionDays);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'retentionDays must be 0 (never) or an integer between 1 and 3650' } });
|
||||||
|
}
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, String(value));
|
||||||
|
}
|
||||||
|
if ('purgeDays' in body) {
|
||||||
|
const value = normalizePurgeDays(body.purgeDays);
|
||||||
|
if (value === null) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'purgeDays must be 0 (disabled) or an integer between 1 and 3650' } });
|
||||||
|
}
|
||||||
|
setSetting(db, PURGE_DAYS_KEY, String(value));
|
||||||
|
}
|
||||||
recordAudit(db, {
|
recordAudit(db, {
|
||||||
actor: req.authContext?.tokenId ?? 'unknown',
|
actor: req.authContext?.tokenId ?? 'unknown',
|
||||||
action: 'settings.update',
|
action: 'settings.update',
|
||||||
details: { keys: Object.keys(body) },
|
details: { keys: Object.keys(body) },
|
||||||
});
|
});
|
||||||
return reply.send(snapshot());
|
const snap = snapshot();
|
||||||
|
// 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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,32 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
import type {
|
import type {
|
||||||
AdoptWorktreeRequest,
|
AdoptWorktreeRequest,
|
||||||
|
CommitWorktreeRequest,
|
||||||
CreateWorktreeRequest,
|
CreateWorktreeRequest,
|
||||||
CreateWorktreeResponse,
|
CreateWorktreeResponse,
|
||||||
|
PromoteWorktreeRequest,
|
||||||
|
PushWorktreeRequest,
|
||||||
|
RepoBranchesResponse,
|
||||||
SessionResponse,
|
SessionResponse,
|
||||||
StartRepoSessionRequest,
|
StartRepoSessionRequest,
|
||||||
|
WorktreeBranchMode,
|
||||||
WorktreeResponse,
|
WorktreeResponse,
|
||||||
WorktreesListResponse,
|
WorktreesListResponse,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
import type { WorktreeManager } from '../core/worktree-manager.js';
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
|
import type { Db } from '../db/index.js';
|
||||||
|
import { recordAudit } from '../core/audit-log.js';
|
||||||
import { sendManagerError } from './repos.js';
|
import { sendManagerError } from './repos.js';
|
||||||
|
|
||||||
export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager): void {
|
/** Mappe l'API (mode prioritaire ; `newBranch` déprécié) vers la stratégie de résolution de branche. */
|
||||||
|
function resolveMode(body: { mode?: unknown; newBranch?: unknown }): WorktreeBranchMode {
|
||||||
|
if (body.mode === 'auto' || body.mode === 'create' || body.mode === 'checkout') return body.mode;
|
||||||
|
if (body.newBranch === true) return 'create';
|
||||||
|
if (body.newBranch === false) return 'checkout';
|
||||||
|
return 'auto';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager, db: Db): void {
|
||||||
app.get('/api/v1/worktrees', async (): Promise<WorktreesListResponse> => ({ worktrees: await wt.listAllWorktrees() }));
|
app.get('/api/v1/worktrees', async (): Promise<WorktreesListResponse> => ({ worktrees: await wt.listAllWorktrees() }));
|
||||||
|
|
||||||
app.get('/api/v1/repos/:id/worktrees', async (req): Promise<WorktreesListResponse> => {
|
app.get('/api/v1/repos/:id/worktrees', async (req): Promise<WorktreesListResponse> => {
|
||||||
@@ -31,7 +46,7 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
|
|||||||
try {
|
try {
|
||||||
const out = await wt.createWorktree(id, {
|
const out = await wt.createWorktree(id, {
|
||||||
branch: body.branch,
|
branch: body.branch,
|
||||||
newBranch: body.newBranch !== false, // défaut : créer la branche
|
mode: resolveMode(body), // défaut : auto (détecte créer / checkout / suivi remote)
|
||||||
...(body.baseRef !== undefined ? { baseRef: body.baseRef } : {}),
|
...(body.baseRef !== undefined ? { baseRef: body.baseRef } : {}),
|
||||||
...(body.path !== undefined ? { path: body.path } : {}),
|
...(body.path !== undefined ? { path: body.path } : {}),
|
||||||
...(body.runHooks !== undefined ? { runHooks: body.runHooks } : {}),
|
...(body.runHooks !== undefined ? { runHooks: body.runHooks } : {}),
|
||||||
@@ -45,6 +60,17 @@ 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.
|
||||||
|
app.get('/api/v1/repos/:id/branches', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
try {
|
||||||
|
const out = await wt.listRepoBranches(id);
|
||||||
|
return reply.send(out satisfies RepoBranchesResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Session sur le checkout principal (« bosser sur la branche principale » sans worktree),
|
// Session sur le checkout principal (« bosser sur la branche principale » sans worktree),
|
||||||
// avec création/bascule de branche optionnelle côté serveur.
|
// avec création/bascule de branche optionnelle côté serveur.
|
||||||
app.post('/api/v1/repos/:id/session', async (req, reply) => {
|
app.post('/api/v1/repos/:id/session', async (req, reply) => {
|
||||||
@@ -101,6 +127,63 @@ export function registerWorktreeRoutes(app: FastifyInstance, wt: WorktreeManager
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Commit (git add -A + commit) dans un worktree (ou le checkout principal).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/commit', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<CommitWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
const amend = body.amend === true;
|
||||||
|
if (!amend && (typeof body.message !== 'string' || body.message.trim() === '')) {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'message is required' } });
|
||||||
|
}
|
||||||
|
const mode = body.mode === 'staged' ? 'staged' : 'all';
|
||||||
|
try {
|
||||||
|
const worktree = await wt.commitWorktree(id, body.path, {
|
||||||
|
message: typeof body.message === 'string' ? body.message.trim() : '',
|
||||||
|
mode,
|
||||||
|
amend,
|
||||||
|
});
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.commit', resourceId: id, details: { path: body.path, mode, amend } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Push de la branche d'un worktree (upstream auto si absent).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/push', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<PushWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.pushWorktree(id, body.path);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.push', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree } satisfies WorktreeResponse);
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Promotion « en principal » : la branche du worktree devient le checkout principal (worktree supprimé).
|
||||||
|
app.post('/api/v1/repos/:id/worktrees/promote', async (req, reply) => {
|
||||||
|
const { id } = req.params as { id: string };
|
||||||
|
const body = req.body as Partial<PromoteWorktreeRequest> | null;
|
||||||
|
if (!body || typeof body.path !== 'string') {
|
||||||
|
return reply.status(400).send({ error: { code: 'BAD_REQUEST', message: 'path is required' } });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const worktree = await wt.promoteWorktree(id, body.path, body.force === true);
|
||||||
|
recordAudit(db, { actor: req.authContext?.tokenId ?? 'unknown', action: 'worktree.promote', resourceId: id, details: { path: body.path } });
|
||||||
|
return reply.send({ worktree });
|
||||||
|
} catch (err) {
|
||||||
|
return sendManagerError(reply, err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
app.delete('/api/v1/repos/:id/worktrees', async (req, reply) => {
|
app.delete('/api/v1/repos/:id/worktrees', async (req, reply) => {
|
||||||
const { id } = req.params as { id: string };
|
const { id } = req.params as { id: string };
|
||||||
const query = req.query as { path?: string; force?: string };
|
const query = req.query as { path?: string; force?: string };
|
||||||
|
|||||||
@@ -7,14 +7,19 @@ import {
|
|||||||
parseClientMessage,
|
parseClientMessage,
|
||||||
type GroupSummary,
|
type GroupSummary,
|
||||||
type RepoSummary,
|
type RepoSummary,
|
||||||
|
type CloneOperation,
|
||||||
type ServerMessage,
|
type ServerMessage,
|
||||||
type SessionSummary,
|
type SessionSummary,
|
||||||
|
type SettingsBroadcast,
|
||||||
type WorktreeSummary,
|
type WorktreeSummary,
|
||||||
} from '@arboretum/shared';
|
} from '@arboretum/shared';
|
||||||
import type { ClientBinding, PtyManager } from '../core/pty-manager.js';
|
import type { ClientBinding, PtyManager } from '../core/pty-manager.js';
|
||||||
import type { DiscoveryService } from '../core/discovery-service.js';
|
import type { DiscoveryService } from '../core/discovery-service.js';
|
||||||
|
import type { SessionArchiveService } from '../core/session-archive.js';
|
||||||
import type { WorktreeManager } from '../core/worktree-manager.js';
|
import type { WorktreeManager } from '../core/worktree-manager.js';
|
||||||
import type { GroupManager } from '../core/group-manager.js';
|
import type { GroupManager } from '../core/group-manager.js';
|
||||||
|
import type { SettingsBus } from '../core/settings-bus.js';
|
||||||
|
import type { CloneManager } from '../core/clone-manager.js';
|
||||||
|
|
||||||
const HEARTBEAT_MS = 30_000;
|
const HEARTBEAT_MS = 30_000;
|
||||||
|
|
||||||
@@ -27,8 +32,11 @@ export function registerWsGateway(
|
|||||||
app: FastifyInstance,
|
app: FastifyInstance,
|
||||||
manager: PtyManager,
|
manager: PtyManager,
|
||||||
discovery: DiscoveryService,
|
discovery: DiscoveryService,
|
||||||
|
sessionArchive: SessionArchiveService,
|
||||||
worktrees: WorktreeManager,
|
worktrees: WorktreeManager,
|
||||||
groups: GroupManager,
|
groups: GroupManager,
|
||||||
|
settingsBus: SettingsBus,
|
||||||
|
clones: CloneManager,
|
||||||
serverVersion: string,
|
serverVersion: string,
|
||||||
): void {
|
): void {
|
||||||
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
|
app.get('/ws', { websocket: true }, (socket: WebSocket, req) => {
|
||||||
@@ -39,7 +47,12 @@ export function registerWsGateway(
|
|||||||
let subscribedSessions = false;
|
let subscribedSessions = false;
|
||||||
let subscribedWorktrees = false;
|
let subscribedWorktrees = false;
|
||||||
let subscribedGroups = false;
|
let subscribedGroups = false;
|
||||||
|
let subscribedSettings = false;
|
||||||
|
let subscribedClones = false;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
|
// Worktrees « regardés » par CETTE connexion (clé repoId\0path) → push ciblé de worktree_changes.
|
||||||
|
const watched = new Set<string>();
|
||||||
|
const watchKey = (repoId: string, path: string): string => `${repoId}\0${path}`;
|
||||||
|
|
||||||
const send = (msg: ServerMessage): void => {
|
const send = (msg: ServerMessage): void => {
|
||||||
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(msg));
|
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(msg));
|
||||||
@@ -54,6 +67,10 @@ export function registerWsGateway(
|
|||||||
const onSessionExit = (e: { sessionId: string; exitCode: number | null; signal: number | null }): void => {
|
const onSessionExit = (e: { sessionId: string; exitCode: number | null; signal: number | null }): void => {
|
||||||
if (subscribedSessions) send({ type: 'session_exit', ...e });
|
if (subscribedSessions) send({ type: 'session_exit', ...e });
|
||||||
};
|
};
|
||||||
|
// 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 });
|
||||||
|
};
|
||||||
// Les sessions découvertes (DiscoveryService) sont relayées sur le même flux que les managées.
|
// Les sessions découvertes (DiscoveryService) sont relayées sur le même flux que les managées.
|
||||||
const onDiscoveryUpdate = (session: SessionSummary): void => {
|
const onDiscoveryUpdate = (session: SessionSummary): void => {
|
||||||
if (subscribedSessions) send({ type: 'session_update', session });
|
if (subscribedSessions) send({ type: 'session_update', session });
|
||||||
@@ -76,15 +93,31 @@ export function registerWsGateway(
|
|||||||
const onGroupRemoved = (groupId: string): void => {
|
const onGroupRemoved = (groupId: string): void => {
|
||||||
if (subscribedGroups) send({ type: 'group_removed', groupId });
|
if (subscribedGroups) send({ type: 'group_removed', groupId });
|
||||||
};
|
};
|
||||||
|
// 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'.
|
||||||
|
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.
|
||||||
|
const onWorktreeChanges = (e: { repoId: string; path: string }): void => {
|
||||||
|
if (watched.has(watchKey(e.repoId, e.path))) send({ type: 'worktree_changes', ...e });
|
||||||
|
};
|
||||||
manager.on('session_update', onSessionUpdate);
|
manager.on('session_update', onSessionUpdate);
|
||||||
manager.on('session_exit', onSessionExit);
|
manager.on('session_exit', onSessionExit);
|
||||||
|
sessionArchive.on('session_archived', onSessionArchived);
|
||||||
discovery.on('discovery_update', onDiscoveryUpdate);
|
discovery.on('discovery_update', onDiscoveryUpdate);
|
||||||
worktrees.on('repo_update', onRepoUpdate);
|
worktrees.on('repo_update', onRepoUpdate);
|
||||||
worktrees.on('repo_removed', onRepoRemoved);
|
worktrees.on('repo_removed', onRepoRemoved);
|
||||||
worktrees.on('worktree_update', onWorktreeUpdate);
|
worktrees.on('worktree_update', onWorktreeUpdate);
|
||||||
worktrees.on('worktree_removed', onWorktreeRemoved);
|
worktrees.on('worktree_removed', onWorktreeRemoved);
|
||||||
|
worktrees.on('worktree_changes', onWorktreeChanges);
|
||||||
groups.on('group_update', onGroupUpdate);
|
groups.on('group_update', onGroupUpdate);
|
||||||
groups.on('group_removed', onGroupRemoved);
|
groups.on('group_removed', onGroupRemoved);
|
||||||
|
settingsBus.on('settings_update', onSettingsUpdate);
|
||||||
|
clones.on('clone_update', onCloneUpdate);
|
||||||
|
|
||||||
const heartbeat = setInterval(() => {
|
const heartbeat = setInterval(() => {
|
||||||
if (!alive) {
|
if (!alive) {
|
||||||
@@ -124,6 +157,24 @@ export function registerWsGateway(
|
|||||||
subscribedSessions = msg.topics.includes('sessions');
|
subscribedSessions = msg.topics.includes('sessions');
|
||||||
subscribedWorktrees = msg.topics.includes('worktrees');
|
subscribedWorktrees = msg.topics.includes('worktrees');
|
||||||
subscribedGroups = msg.topics.includes('groups');
|
subscribedGroups = msg.topics.includes('groups');
|
||||||
|
subscribedSettings = msg.topics.includes('settings');
|
||||||
|
subscribedClones = msg.topics.includes('clones');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'watch': {
|
||||||
|
const key = watchKey(msg.repoId, msg.path);
|
||||||
|
if (watched.has(key)) return;
|
||||||
|
watched.add(key);
|
||||||
|
// Validation repo/worktree + armement du watcher FS (asynchrone, best-effort).
|
||||||
|
void worktrees.watch(msg.repoId, msg.path).catch((err) => {
|
||||||
|
watched.delete(key);
|
||||||
|
send({ type: 'error', code: 'NOT_FOUND', message: (err as Error).message });
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'unwatch': {
|
||||||
|
watched.delete(watchKey(msg.repoId, msg.path));
|
||||||
|
worktrees.unwatch(msg.repoId, msg.path);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'attach': {
|
case 'attach': {
|
||||||
@@ -210,15 +261,25 @@ export function registerWsGateway(
|
|||||||
clearInterval(heartbeat);
|
clearInterval(heartbeat);
|
||||||
manager.off('session_update', onSessionUpdate);
|
manager.off('session_update', onSessionUpdate);
|
||||||
manager.off('session_exit', onSessionExit);
|
manager.off('session_exit', onSessionExit);
|
||||||
|
sessionArchive.off('session_archived', onSessionArchived);
|
||||||
discovery.off('discovery_update', onDiscoveryUpdate);
|
discovery.off('discovery_update', onDiscoveryUpdate);
|
||||||
worktrees.off('repo_update', onRepoUpdate);
|
worktrees.off('repo_update', onRepoUpdate);
|
||||||
worktrees.off('repo_removed', onRepoRemoved);
|
worktrees.off('repo_removed', onRepoRemoved);
|
||||||
worktrees.off('worktree_update', onWorktreeUpdate);
|
worktrees.off('worktree_update', onWorktreeUpdate);
|
||||||
worktrees.off('worktree_removed', onWorktreeRemoved);
|
worktrees.off('worktree_removed', onWorktreeRemoved);
|
||||||
|
worktrees.off('worktree_changes', onWorktreeChanges);
|
||||||
groups.off('group_update', onGroupUpdate);
|
groups.off('group_update', onGroupUpdate);
|
||||||
groups.off('group_removed', onGroupRemoved);
|
groups.off('group_removed', onGroupRemoved);
|
||||||
|
settingsBus.off('settings_update', onSettingsUpdate);
|
||||||
|
clones.off('clone_update', onCloneUpdate);
|
||||||
for (const [, st] of channels) manager.detach(st.sessionId, st.binding);
|
for (const [, st] of channels) manager.detach(st.sessionId, st.binding);
|
||||||
channels.clear();
|
channels.clear();
|
||||||
|
// Libère le refcount du watcher pour chaque worktree regardé par cette connexion.
|
||||||
|
for (const key of watched) {
|
||||||
|
const sep = key.indexOf('\0');
|
||||||
|
worktrees.unwatch(key.slice(0, sep), key.slice(sep + 1));
|
||||||
|
}
|
||||||
|
watched.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
void req;
|
void req;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { buildSpawnSpec } from '../src/core/claude-launcher.js';
|
import { buildSpawnSpec, diagnoseClaudeBin, resolveClaudeBin } from '../src/core/claude-launcher.js';
|
||||||
|
|
||||||
// resolveClaudeBin() fait `which claude` : on le stub pour ne pas dépendre d'un claude réel en PATH.
|
// 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' }));
|
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||||
@@ -27,3 +27,28 @@ describe('buildSpawnSpec — session de groupe multi-repo (P6)', () => {
|
|||||||
expect(spec.args).toEqual(['--norc']);
|
expect(spec.args).toEqual(['--norc']);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
it('buildSpawnSpec utilise le chemin configuré tel quel quand fourni', () => {
|
||||||
|
const spec = buildSpawnSpec({ command: 'claude', claudeBinPath: realBin });
|
||||||
|
expect(spec.file).toBe(realBin);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolveClaudeBin retombe sur le PATH (which) sans override', () => {
|
||||||
|
expect(resolveClaudeBin()).toBe('/usr/bin/claude');
|
||||||
|
expect(resolveClaudeBin(null)).toBe('/usr/bin/claude');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolveClaudeBin throw si le chemin configuré n’est pas exécutable', () => {
|
||||||
|
expect(() => resolveClaudeBin('/no/such/claude')).toThrow(/not executable/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('diagnoseClaudeBin : configuré+exécutable → ok ; configuré absent → !ok ; sinon PATH', () => {
|
||||||
|
expect(diagnoseClaudeBin(realBin)).toEqual({ path: realBin, source: 'configured', ok: true });
|
||||||
|
expect(diagnoseClaudeBin('/no/such/claude')).toEqual({ path: '/no/such/claude', source: 'configured', ok: false });
|
||||||
|
expect(diagnoseClaudeBin()).toEqual({ path: '/usr/bin/claude', source: 'path', ok: true });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
89
packages/server/test/claude-settings.test.ts
Normal file
89
packages/server/test/claude-settings.test.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
// Réglages CLI Claude (chemin du binaire + override ~/.claude) : validateurs + lecture/écriture DB.
|
||||||
|
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
import { openDb, setSetting, type Db } from '../src/db/index.js';
|
||||||
|
import {
|
||||||
|
CLAUDE_BIN_PATH_KEY,
|
||||||
|
CLAUDE_HOME_KEY,
|
||||||
|
normalizeClaudeBinPath,
|
||||||
|
normalizeClaudeHome,
|
||||||
|
readClaudeBinPath,
|
||||||
|
readClaudeHome,
|
||||||
|
} from '../src/core/claude-settings.js';
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
let execFile: string;
|
||||||
|
let plainFile: string;
|
||||||
|
let subDir: string;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'arboretum-claude-settings-'));
|
||||||
|
execFile = join(dir, 'claude');
|
||||||
|
writeFileSync(execFile, '#!/bin/sh\n');
|
||||||
|
chmodSync(execFile, 0o755); // exécutable
|
||||||
|
plainFile = join(dir, 'notexec');
|
||||||
|
writeFileSync(plainFile, 'x');
|
||||||
|
chmodSync(plainFile, 0o644); // non exécutable
|
||||||
|
subDir = join(dir, 'home');
|
||||||
|
mkdirSync(subDir);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
||||||
|
|
||||||
|
describe('normalizeClaudeBinPath', () => {
|
||||||
|
it('accepte un chemin absolu vers un fichier exécutable', () => {
|
||||||
|
expect(normalizeClaudeBinPath(execFile)).toBe(execFile);
|
||||||
|
});
|
||||||
|
it('"" = réinitialisation (auto-détection)', () => {
|
||||||
|
expect(normalizeClaudeBinPath('')).toBe('');
|
||||||
|
expect(normalizeClaudeBinPath(' ')).toBe('');
|
||||||
|
});
|
||||||
|
it('rejette un fichier non exécutable, un répertoire, un chemin relatif ou avec ".." (null)', () => {
|
||||||
|
expect(normalizeClaudeBinPath(plainFile)).toBeNull();
|
||||||
|
expect(normalizeClaudeBinPath(subDir)).toBeNull(); // répertoire, pas un fichier
|
||||||
|
expect(normalizeClaudeBinPath('relative/claude')).toBeNull();
|
||||||
|
expect(normalizeClaudeBinPath(join(dir, '..', 'x'))).toBeNull();
|
||||||
|
expect(normalizeClaudeBinPath(join(dir, 'missing'))).toBeNull();
|
||||||
|
expect(normalizeClaudeBinPath(42)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('normalizeClaudeHome', () => {
|
||||||
|
it('accepte un chemin absolu vers un répertoire existant', () => {
|
||||||
|
expect(normalizeClaudeHome(subDir)).toBe(subDir);
|
||||||
|
});
|
||||||
|
it('"" = réinitialisation (défaut)', () => {
|
||||||
|
expect(normalizeClaudeHome('')).toBe('');
|
||||||
|
});
|
||||||
|
it('rejette un fichier, un chemin relatif/inexistant (null)', () => {
|
||||||
|
expect(normalizeClaudeHome(execFile)).toBeNull(); // fichier, pas un répertoire
|
||||||
|
expect(normalizeClaudeHome('relative/.claude')).toBeNull();
|
||||||
|
expect(normalizeClaudeHome(join(dir, 'missing'))).toBeNull();
|
||||||
|
expect(normalizeClaudeHome(null)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('readClaudeBinPath / readClaudeHome', () => {
|
||||||
|
let db: Db;
|
||||||
|
beforeAll(() => {
|
||||||
|
db = openDb(join(dir, 'settings.db'));
|
||||||
|
});
|
||||||
|
afterAll(() => db.close());
|
||||||
|
|
||||||
|
it('null quand non défini', () => {
|
||||||
|
expect(readClaudeBinPath(db)).toBeNull();
|
||||||
|
expect(readClaudeHome(db)).toBeNull();
|
||||||
|
});
|
||||||
|
it('lit la valeur stockée et traite "" stockée comme null', () => {
|
||||||
|
setSetting(db, CLAUDE_BIN_PATH_KEY, execFile);
|
||||||
|
setSetting(db, CLAUDE_HOME_KEY, subDir);
|
||||||
|
expect(readClaudeBinPath(db)).toBe(execFile);
|
||||||
|
expect(readClaudeHome(db)).toBe(subDir);
|
||||||
|
setSetting(db, CLAUDE_BIN_PATH_KEY, ''); // réinitialisé
|
||||||
|
setSetting(db, CLAUDE_HOME_KEY, '');
|
||||||
|
expect(readClaudeBinPath(db)).toBeNull();
|
||||||
|
expect(readClaudeHome(db)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -79,6 +79,21 @@ describe('cli install — renderSystemdUnit', () => {
|
|||||||
expect(unit).toContain('ExecStart="/path with space/node" /s.js');
|
expect(unit).toContain('ExecStart="/path with space/node" /s.js');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('fige le PATH d\'installation quand fourni (le service systemd a un PATH minimal)', () => {
|
||||||
|
const unit = renderSystemdUnit({
|
||||||
|
exec: '/usr/bin/node',
|
||||||
|
scriptArgs: ['/s.js'],
|
||||||
|
pathEnv: '/home/me/.local/bin:/usr/bin',
|
||||||
|
});
|
||||||
|
// Doubles quotes systemd : un chemin du PATH peut contenir un espace.
|
||||||
|
expect(unit).toContain('Environment="PATH=/home/me/.local/bin:/usr/bin"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("n'émet aucune ligne PATH sans pathEnv (rétrocompat)", () => {
|
||||||
|
const unit = renderSystemdUnit({ exec: '/usr/bin/node', scriptArgs: ['/s.js'] });
|
||||||
|
expect(unit).not.toContain('PATH=');
|
||||||
|
});
|
||||||
|
|
||||||
it('snapshot du unit pour un jeu de flags fixe', () => {
|
it('snapshot du unit pour un jeu de flags fixe', () => {
|
||||||
const unit = renderSystemdUnit({
|
const unit = renderSystemdUnit({
|
||||||
exec: '/usr/bin/node',
|
exec: '/usr/bin/node',
|
||||||
@@ -133,6 +148,19 @@ describe('cli install — renderLaunchAgentPlist', () => {
|
|||||||
expect(plist).toContain('https://a?b&c=d');
|
expect(plist).toContain('https://a?b&c=d');
|
||||||
expect(plist).not.toContain('b&c=d');
|
expect(plist).not.toContain('b&c=d');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('ajoute la clé PATH dans EnvironmentVariables quand fournie (launchd a un PATH minimal)', () => {
|
||||||
|
const plist = renderLaunchAgentPlist({ ...base, pathEnv: '/Users/me/.local/bin:/usr/bin' });
|
||||||
|
expect(plist).toContain('<key>PATH</key>');
|
||||||
|
expect(plist).toContain('<string>/Users/me/.local/bin:/usr/bin</string>');
|
||||||
|
// Reste dans le dict EnvironmentVariables, juste après NODE_ENV.
|
||||||
|
expect(plist.indexOf('<key>PATH</key>')).toBeGreaterThan(plist.indexOf('<key>NODE_ENV</key>'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("n'ajoute aucune clé PATH sans pathEnv (rétrocompat)", () => {
|
||||||
|
const plist = renderLaunchAgentPlist(base);
|
||||||
|
expect(plist).not.toContain('<key>PATH</key>');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('cli install — xmlEscape', () => {
|
describe('cli install — xmlEscape', () => {
|
||||||
|
|||||||
126
packages/server/test/fs-watcher.test.ts
Normal file
126
packages/server/test/fs-watcher.test.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
import { describe, expect, it, afterEach } from 'vitest';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { FsWatcherService, isIgnoredPath } from '../src/core/fs-watcher.js';
|
||||||
|
|
||||||
|
const dirs: string[] = [];
|
||||||
|
const services: FsWatcherService[] = [];
|
||||||
|
afterEach(async () => {
|
||||||
|
for (const s of services.splice(0)) await s.closeAll();
|
||||||
|
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function makeTmpRepo(): string {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'arb-fsw-'));
|
||||||
|
dirs.push(dir);
|
||||||
|
const run = (...args: string[]): void => void execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
|
||||||
|
run('init', '-b', 'main');
|
||||||
|
run('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
run('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(dir, 'README.md'), '# test\n');
|
||||||
|
run('add', '-A');
|
||||||
|
run('commit', '-m', 'init');
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Attend le prochain event `worktree_fs_change` (ou rejette au timeout). */
|
||||||
|
function nextChange(s: FsWatcherService, timeoutMs = 4000): Promise<{ repoId: string; path: string }> {
|
||||||
|
return new Promise((resolveP, reject) => {
|
||||||
|
const t = setTimeout(() => reject(new Error('timeout: aucun worktree_fs_change')), timeoutMs);
|
||||||
|
s.once('worktree_fs_change', (e) => {
|
||||||
|
clearTimeout(t);
|
||||||
|
resolveP(e);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('isIgnoredPath', () => {
|
||||||
|
it('ignore .git interne sauf HEAD/index, et node_modules', () => {
|
||||||
|
expect(isIgnoredPath('/r/.git/objects/ab/cd')).toBe(true);
|
||||||
|
expect(isIgnoredPath('/r/.git/refs/heads/main')).toBe(true);
|
||||||
|
expect(isIgnoredPath('/r/.git/HEAD')).toBe(false);
|
||||||
|
expect(isIgnoredPath('/r/.git/index')).toBe(false);
|
||||||
|
expect(isIgnoredPath('/r/node_modules/x/y.js')).toBe(true);
|
||||||
|
expect(isIgnoredPath('/r/src/a.ts')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FsWatcherService', () => {
|
||||||
|
it('refcount : watch ouvre, unwatch ne ferme pas tant que le plafond n’est pas atteint', () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const s = new FsWatcherService();
|
||||||
|
services.push(s);
|
||||||
|
expect(s.isWatching('r1', repo)).toBe(false);
|
||||||
|
s.watch('r1', repo);
|
||||||
|
expect(s.isWatching('r1', repo)).toBe(true);
|
||||||
|
expect(s.size()).toBe(1);
|
||||||
|
s.unwatch('r1', repo);
|
||||||
|
expect(s.isWatching('r1', repo)).toBe(true); // idle, pas encore évincé
|
||||||
|
});
|
||||||
|
|
||||||
|
it('émet un worktree_fs_change débouncé à l’édition d’un fichier', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const s = new FsWatcherService({ debounceMs: 50 });
|
||||||
|
services.push(s);
|
||||||
|
s.watch('r1', repo);
|
||||||
|
await s.whenReady('r1', repo);
|
||||||
|
const p = nextChange(s);
|
||||||
|
writeFileSync(join(repo, 'edited.txt'), 'hello\n');
|
||||||
|
const e = await p;
|
||||||
|
expect(e.repoId).toBe('r1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détecte un changement de branche externe (git checkout) via .git/HEAD', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
execFileSync('git', ['branch', 'feature'], { cwd: repo });
|
||||||
|
const s = new FsWatcherService({ debounceMs: 50 });
|
||||||
|
services.push(s);
|
||||||
|
s.watch('r1', repo);
|
||||||
|
await s.whenReady('r1', repo);
|
||||||
|
const p = nextChange(s);
|
||||||
|
execFileSync('git', ['checkout', 'feature'], { cwd: repo, stdio: 'pipe' });
|
||||||
|
const e = await p;
|
||||||
|
expect(e.path).toContain('arb-fsw-');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('le pool LRU évince les entrées idle au-delà du plafond, jamais les épinglées', () => {
|
||||||
|
const s = new FsWatcherService({ maxWatchers: 2 });
|
||||||
|
services.push(s);
|
||||||
|
const a = makeTmpRepo();
|
||||||
|
const b = makeTmpRepo();
|
||||||
|
const c = makeTmpRepo();
|
||||||
|
s.pinSession('a', a); // épinglé → jamais évincé
|
||||||
|
s.watch('b', b);
|
||||||
|
s.unwatch('b', b); // idle
|
||||||
|
s.watch('c', c); // dépasse le plafond → évince le plus ancien idle (b)
|
||||||
|
expect(s.isWatching('a', a)).toBe(true);
|
||||||
|
expect(s.isWatching('c', c)).toBe(true);
|
||||||
|
expect(s.isWatching('b', b)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pinRepo (checkout principal, P11) : jamais évincé par la LRU', () => {
|
||||||
|
const s = new FsWatcherService({ maxWatchers: 1 });
|
||||||
|
services.push(s);
|
||||||
|
const a = makeTmpRepo();
|
||||||
|
const b = makeTmpRepo();
|
||||||
|
s.pinRepo('a', a); // épingle permanente
|
||||||
|
s.watch('b', b);
|
||||||
|
s.unwatch('b', b);
|
||||||
|
expect(s.isWatching('a', a)).toBe(true); // toujours là malgré le dépassement du plafond
|
||||||
|
s.unpinRepo('a', a);
|
||||||
|
const c = makeTmpRepo();
|
||||||
|
s.watch('c', c); // 'a' n'est plus épinglé et idle → évinçable
|
||||||
|
expect(s.isWatching('a', a)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('closeAll libère tout', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const s = new FsWatcherService();
|
||||||
|
s.watch('r1', repo);
|
||||||
|
expect(s.size()).toBe(1);
|
||||||
|
await s.closeAll();
|
||||||
|
expect(s.size()).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
54
packages/server/test/git-credentials.test.ts
Normal file
54
packages/server/test/git-credentials.test.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
// Credentials git (P12) : round-trip SecretBox, résumé SANS secret, NULLification à la suppression.
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { openDb, type Db } from '../src/db/index.js';
|
||||||
|
import { SecretBox } from '../src/core/secret-box.js';
|
||||||
|
import { GitCredentialsManager } from '../src/core/git-credentials.js';
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
let mgr: GitCredentialsManager;
|
||||||
|
const SECRET = 'pat-super-secret-1234';
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
db = openDb(':memory:');
|
||||||
|
mgr = new GitCredentialsManager(db, new SecretBox(Buffer.alloc(32, 7)));
|
||||||
|
});
|
||||||
|
afterEach(() => db.close());
|
||||||
|
|
||||||
|
describe('GitCredentialsManager', () => {
|
||||||
|
it('crée un credential : secret chiffré en DB, résumé sans secret', () => {
|
||||||
|
const cred = mgr.create({ label: 'gh', service: 'github', authType: 'pat', secret: SECRET });
|
||||||
|
expect(cred.hasSecret).toBe(true);
|
||||||
|
expect(cred.secretLast4).toBe('1234');
|
||||||
|
// le résumé sérialisé ne contient JAMAIS le secret en clair.
|
||||||
|
expect(JSON.stringify(cred)).not.toContain(SECRET);
|
||||||
|
// en DB : valeur chiffrée (préfixe v1:), jamais le clair.
|
||||||
|
const row = db.prepare('SELECT secret_encrypted FROM git_credentials WHERE id = ?').get(cred.id) as { secret_encrypted: string };
|
||||||
|
expect(row.secret_encrypted.startsWith('v1:')).toBe(true);
|
||||||
|
expect(row.secret_encrypted).not.toContain(SECRET);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('getSecret déchiffre (round-trip)', () => {
|
||||||
|
const cred = mgr.create({ label: 'gl', service: 'gitlab', authType: 'pat', secret: SECRET });
|
||||||
|
expect(mgr.getSecret(cred.id)).toBe(SECRET);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('exige un base_url pour Gitea', () => {
|
||||||
|
expect(() => mgr.create({ label: 'x', service: 'gitea', authType: 'pat', secret: SECRET })).toThrow();
|
||||||
|
expect(mgr.create({ label: 'x', service: 'gitea', authType: 'pat', baseUrl: 'https://git.example.com', secret: SECRET }).baseUrl).toBe('https://git.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse ssh_key/oauth pour l’instant (P12a)', () => {
|
||||||
|
expect(() => mgr.create({ label: 'x', service: 'github', authType: 'ssh_key', secret: SECRET })).toThrow();
|
||||||
|
expect(() => mgr.create({ label: 'x', service: 'github', authType: 'oauth', secret: SECRET })).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('remove() NULLifie repos.credential_id (pas de FK)', () => {
|
||||||
|
const cred = mgr.create({ label: 'gh', service: 'github', authType: 'pat', secret: SECRET });
|
||||||
|
db.prepare(
|
||||||
|
"INSERT INTO repos (id, path, label, post_create_hooks, pre_trust, created_at, hidden, credential_id) VALUES ('r1', '/tmp/r1', 'r1', '[]', 0, '2020-01-01T00:00:00Z', 0, ?)",
|
||||||
|
).run(cred.id);
|
||||||
|
expect(mgr.remove(cred.id)).toBe(true);
|
||||||
|
const repo = db.prepare("SELECT credential_id FROM repos WHERE id = 'r1'").get() as { credential_id: string | null };
|
||||||
|
expect(repo.credential_id).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
parseWorktreePorcelain,
|
parseWorktreePorcelain,
|
||||||
isValidBranchName,
|
isValidBranchName,
|
||||||
isSafeAbsolutePath,
|
isSafeAbsolutePath,
|
||||||
|
isSafeRelativePath,
|
||||||
isRepo,
|
isRepo,
|
||||||
listWorktrees,
|
listWorktrees,
|
||||||
worktreeStatus,
|
worktreeStatus,
|
||||||
@@ -15,7 +16,24 @@ import {
|
|||||||
pruneWorktrees,
|
pruneWorktrees,
|
||||||
switchBranch,
|
switchBranch,
|
||||||
isDirtyWorktreeError,
|
isDirtyWorktreeError,
|
||||||
|
branchExists,
|
||||||
|
currentBranch,
|
||||||
|
listBranches,
|
||||||
|
commitAll,
|
||||||
|
parsePorcelainV2,
|
||||||
|
parseNumstatZ,
|
||||||
|
listChanges,
|
||||||
|
fileDiff,
|
||||||
|
stageFiles,
|
||||||
|
unstageFiles,
|
||||||
|
restoreFiles,
|
||||||
|
cleanFiles,
|
||||||
|
commitStaged,
|
||||||
|
amendCommit,
|
||||||
|
lastCommit,
|
||||||
|
isUnpushed,
|
||||||
} from '../src/core/git.js';
|
} from '../src/core/git.js';
|
||||||
|
import { appendFileSync } from 'node:fs';
|
||||||
|
|
||||||
const dirs: string[] = [];
|
const dirs: string[] = [];
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -96,7 +114,7 @@ describe('opérations git (repo tmp réel)', () => {
|
|||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await addWorktree(repo, { path: wtPath, branch: 'feat', newBranch: true });
|
await addWorktree(repo, { path: wtPath, branch: 'feat', mode: 'create' });
|
||||||
|
|
||||||
const list = await listWorktrees(repo);
|
const list = await listWorktrees(repo);
|
||||||
const wt = list.find((w) => resolve(w.path) === resolve(wtPath));
|
const wt = list.find((w) => resolve(w.path) === resolve(wtPath));
|
||||||
@@ -136,9 +154,167 @@ describe('opérations git (repo tmp réel)', () => {
|
|||||||
it('prune retire un worktree dont le dossier a disparu', async () => {
|
it('prune retire un worktree dont le dossier a disparu', async () => {
|
||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-gone`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-gone`);
|
||||||
await addWorktree(repo, { path: wtPath, branch: 'gone', newBranch: true });
|
await addWorktree(repo, { path: wtPath, branch: 'gone', mode: 'create' });
|
||||||
rmSync(wtPath, { recursive: true, force: true }); // suppression "à la main"
|
rmSync(wtPath, { recursive: true, force: true }); // suppression "à la main"
|
||||||
await pruneWorktrees(repo);
|
await pruneWorktrees(repo);
|
||||||
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
expect((await listWorktrees(repo)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('branche : existence, liste, courante, commit', () => {
|
||||||
|
it('branchExists / currentBranch / listBranches', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
expect(await currentBranch(repo)).toBe('main');
|
||||||
|
expect(await branchExists(repo, 'main')).toEqual({ local: true, remote: false });
|
||||||
|
expect(await branchExists(repo, 'nope')).toEqual({ local: false, remote: false });
|
||||||
|
|
||||||
|
execFileSync('git', ['branch', 'dev'], { cwd: repo });
|
||||||
|
const b = await listBranches(repo);
|
||||||
|
expect(b.local).toContain('main');
|
||||||
|
expect(b.local).toContain('dev');
|
||||||
|
expect(b.remote).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('commitAll : add -A + commit, fait baisser dirtyCount à 0', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
writeFileSync(join(repo, 'new.txt'), 'hello\n');
|
||||||
|
expect((await worktreeStatus(repo)).dirtyCount).toBeGreaterThan(0);
|
||||||
|
await commitAll(repo, 'add new.txt');
|
||||||
|
expect((await worktreeStatus(repo)).dirtyCount).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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' +
|
||||||
|
'1 A. N... 000000 100644 100644 0000 h3 added.txt\x00' +
|
||||||
|
'? new.txt\x00' +
|
||||||
|
'2 R. N... 100644 100644 100644 h4 h5 R100 newname.txt\x00oldname.txt\x00';
|
||||||
|
const e = parsePorcelainV2(z);
|
||||||
|
expect(e).toHaveLength(4);
|
||||||
|
expect(e[0]).toMatchObject({ path: 'file.txt', indexStatus: '.', worktreeStatus: 'M', staged: false, unstaged: true });
|
||||||
|
expect(e[1]).toMatchObject({ path: 'added.txt', indexStatus: 'A', staged: true, unstaged: false });
|
||||||
|
expect(e[2]).toMatchObject({ path: 'new.txt', untracked: true, unstaged: true, staged: false });
|
||||||
|
expect(e[3]).toMatchObject({ path: 'newname.txt', renamedFrom: 'oldname.txt', staged: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parseNumstatZ : normal, binaire, renommé', () => {
|
||||||
|
const z = '5\t2\tfile.txt\x00-\t-\timg.png\x003\t1\t\x00old.txt\x00new.txt\x00';
|
||||||
|
const m = parseNumstatZ(z);
|
||||||
|
expect(m.get('file.txt')).toEqual({ insertions: 5, deletions: 2, binary: false });
|
||||||
|
expect(m.get('img.png')).toEqual({ insertions: null, deletions: null, binary: true });
|
||||||
|
expect(m.get('new.txt')).toEqual({ insertions: 3, deletions: 1, binary: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('isSafeRelativePath', () => {
|
||||||
|
expect(isSafeRelativePath('src/a.ts')).toBe(true);
|
||||||
|
expect(isSafeRelativePath('/abs')).toBe(false);
|
||||||
|
expect(isSafeRelativePath('../escape')).toBe(false);
|
||||||
|
expect(isSafeRelativePath('-flag')).toBe(false);
|
||||||
|
expect(isSafeRelativePath('.git/config')).toBe(false);
|
||||||
|
expect(isSafeRelativePath('')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
appendFileSync(join(repo, 'README.md'), 'more\n');
|
||||||
|
writeFileSync(join(repo, 'staged.txt'), 'y\n');
|
||||||
|
await stageFiles(repo, ['staged.txt']);
|
||||||
|
|
||||||
|
const { changes } = await listChanges(repo);
|
||||||
|
const byPath = Object.fromEntries(changes.map((c) => [c.path, c]));
|
||||||
|
expect(byPath['untracked.txt']).toMatchObject({ untracked: true, staged: false });
|
||||||
|
expect(byPath['README.md']).toMatchObject({ unstaged: true, staged: false });
|
||||||
|
expect(byPath['staged.txt']).toMatchObject({ staged: true });
|
||||||
|
expect(byPath['staged.txt'].insertions).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fileDiff : fichier suivi modifié, refus binaire implicite, untracked via --no-index', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
appendFileSync(join(repo, 'README.md'), 'a new line\n');
|
||||||
|
const d = await fileDiff(repo, 'README.md');
|
||||||
|
expect(d.binary).toBe(false);
|
||||||
|
expect(d.diff).toContain('+a new line');
|
||||||
|
|
||||||
|
writeFileSync(join(repo, 'fresh.txt'), 'brand new\n');
|
||||||
|
const u = await fileDiff(repo, 'fresh.txt', { untracked: true });
|
||||||
|
expect(u.diff).toContain('+brand new');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stage / unstage / restore / clean', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
appendFileSync(join(repo, 'README.md'), 'edit\n');
|
||||||
|
await stageFiles(repo, ['README.md']);
|
||||||
|
expect((await listChanges(repo)).changes.find((c) => c.path === 'README.md')?.staged).toBe(true);
|
||||||
|
await unstageFiles(repo, ['README.md']);
|
||||||
|
expect((await listChanges(repo)).changes.find((c) => c.path === 'README.md')?.staged).toBe(false);
|
||||||
|
await restoreFiles(repo, ['README.md']);
|
||||||
|
expect((await listChanges(repo)).changes.find((c) => c.path === 'README.md')).toBeUndefined();
|
||||||
|
|
||||||
|
writeFileSync(join(repo, 'junk.txt'), 'junk\n');
|
||||||
|
await cleanFiles(repo, ['junk.txt']);
|
||||||
|
expect((await listChanges(repo)).changes.some((c) => c.path === 'junk.txt')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('commitStaged : ne commite QUE l’index', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
writeFileSync(join(repo, 'a.txt'), 'a\n');
|
||||||
|
writeFileSync(join(repo, 'b.txt'), 'b\n');
|
||||||
|
await stageFiles(repo, ['a.txt']);
|
||||||
|
await commitStaged(repo, 'add a only');
|
||||||
|
const { changes } = await listChanges(repo);
|
||||||
|
// a.txt committé (disparu), b.txt toujours non suivi.
|
||||||
|
expect(changes.some((c) => c.path === 'a.txt')).toBe(false);
|
||||||
|
expect(changes.some((c) => c.path === 'b.txt' && c.untracked)).toBe(true);
|
||||||
|
expect((await lastCommit(repo))?.subject).toBe('add a only');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('amendCommit + isUnpushed : HEAD local non poussé', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
expect(await isUnpushed(repo)).toBe(true);
|
||||||
|
await amendCommit(repo, 'init (amended)');
|
||||||
|
expect((await lastCommit(repo))?.subject).toBe('init (amended)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('worktreeStatus : compteurs détaillés + dernier commit', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
writeFileSync(join(repo, 'staged.txt'), 's\n');
|
||||||
|
await stageFiles(repo, ['staged.txt']);
|
||||||
|
appendFileSync(join(repo, 'README.md'), 'unstaged\n');
|
||||||
|
const st = await worktreeStatus(repo);
|
||||||
|
expect(st.stagedCount).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(st.unstagedCount).toBeGreaterThanOrEqual(1);
|
||||||
|
expect(st.conflictCount).toBe(0);
|
||||||
|
expect(st.lastCommitSubject).toBe('init');
|
||||||
|
expect(st.lastCommitHash).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('addWorktree : résolution auto (créer / réutiliser)', () => {
|
||||||
|
it('auto crée la branche si absente, la réutilise si présente', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
// branche absente → création (renvoie "created")
|
||||||
|
const wt1 = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
||||||
|
dirs.push(wt1);
|
||||||
|
expect(await addWorktree(repo, { path: wt1, branch: 'feat', mode: 'auto' })).toBe('created');
|
||||||
|
expect((await listWorktrees(repo)).find((w) => resolve(w.path) === resolve(wt1))?.branch).toBe('feat');
|
||||||
|
|
||||||
|
// la même branche existe désormais ; un AUTRE worktree dessus → checkout (renvoie "reused")
|
||||||
|
await removeWorktree(repo, wt1, true); // libère la branche
|
||||||
|
const wt2 = join(dirname(repo), `${basename(repo)}-wt-feat2`);
|
||||||
|
dirs.push(wt2);
|
||||||
|
expect(await addWorktree(repo, { path: wt2, branch: 'feat', mode: 'auto' })).toBe('reused');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mode create échoue si la branche existe déjà', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
execFileSync('git', ['branch', 'dup'], { cwd: repo });
|
||||||
|
const wt = join(dirname(repo), `${basename(repo)}-wt-dup`);
|
||||||
|
dirs.push(wt);
|
||||||
|
await expect(addWorktree(repo, { path: wt, branch: 'dup', mode: 'create' })).rejects.toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
45
packages/server/test/project.test.ts
Normal file
45
packages/server/test/project.test.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { isSafeProjectName, resolveProjectDir } from '../src/core/project.js';
|
||||||
|
|
||||||
|
describe('isSafeProjectName', () => {
|
||||||
|
it('accepte un segment simple', () => {
|
||||||
|
expect(isSafeProjectName('mon-projet')).toBe(true);
|
||||||
|
expect(isSafeProjectName('Projet_42.v2')).toBe(true);
|
||||||
|
expect(isSafeProjectName(' espaces-trim ')).toBe(true); // trim interne
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse vide / espaces seuls', () => {
|
||||||
|
expect(isSafeProjectName('')).toBe(false);
|
||||||
|
expect(isSafeProjectName(' ')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse `.` et `..`', () => {
|
||||||
|
expect(isSafeProjectName('.')).toBe(false);
|
||||||
|
expect(isSafeProjectName('..')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse les séparateurs et le NUL (anti-traversal)', () => {
|
||||||
|
expect(isSafeProjectName('a/b')).toBe(false);
|
||||||
|
expect(isSafeProjectName('../evil')).toBe(false);
|
||||||
|
expect(isSafeProjectName('a\\b')).toBe(false);
|
||||||
|
expect(isSafeProjectName('a\0b')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse un nom trop long (> 255)', () => {
|
||||||
|
expect(isSafeProjectName('x'.repeat(256))).toBe(false);
|
||||||
|
expect(isSafeProjectName('x'.repeat(255))).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('resolveProjectDir', () => {
|
||||||
|
it('joint root + name (trim) en chemin absolu', () => {
|
||||||
|
expect(resolveProjectDir('/home/johan/dev', 'mon-projet')).toBe('/home/johan/dev/mon-projet');
|
||||||
|
expect(resolveProjectDir('/home/johan/dev', ' mon-projet ')).toBe('/home/johan/dev/mon-projet');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lève (400) sur un nom invalide', () => {
|
||||||
|
expect(() => resolveProjectDir('/home/johan/dev', '..')).toThrow();
|
||||||
|
expect(() => resolveProjectDir('/home/johan/dev', 'a/b')).toThrow();
|
||||||
|
expect(() => resolveProjectDir('/home/johan/dev', '')).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
116
packages/server/test/projects-routes.test.ts
Normal file
116
packages/server/test/projects-routes.test.ts
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
import { mkdtempSync, existsSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { buildApp, type AppBundle } from '../src/app.js';
|
||||||
|
import { openDb, type Db } from '../src/db/index.js';
|
||||||
|
import type { Config } from '../src/config.js';
|
||||||
|
import type { CreateProjectResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
|
// On NE mocke PAS node:child_process : on veut un vrai `git init` (testé via command:'bash', qui
|
||||||
|
// n'a pas besoin de résoudre le binaire claude). Seul le PTY est simulé (pas de vrai process en CI).
|
||||||
|
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
|
||||||
|
class FakePty {
|
||||||
|
pid = 424242;
|
||||||
|
write = vi.fn();
|
||||||
|
resize = vi.fn();
|
||||||
|
pause = vi.fn();
|
||||||
|
resume = vi.fn();
|
||||||
|
kill = vi.fn();
|
||||||
|
onData(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
onExit(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { default: { spawn: (): FakePty => new FakePty() } };
|
||||||
|
});
|
||||||
|
|
||||||
|
process.env.ARBORETUM_LOG = 'silent';
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
let root: string;
|
||||||
|
let bundle: AppBundle;
|
||||||
|
let db: Db;
|
||||||
|
let token: string;
|
||||||
|
|
||||||
|
const auth = (): { authorization: string } => ({ authorization: `Bearer ${token}` });
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'arboretum-projects-'));
|
||||||
|
root = dir; // la racine existe déjà
|
||||||
|
|
||||||
|
const dbPath = join(dir, 'projects.db');
|
||||||
|
db = openDb(dbPath);
|
||||||
|
const config: Config = {
|
||||||
|
port: 7317,
|
||||||
|
bind: '127.0.0.1',
|
||||||
|
dbPath,
|
||||||
|
dataDir: dir,
|
||||||
|
allowedOrigins: [],
|
||||||
|
printToken: false,
|
||||||
|
claudeProjectsDir: join(dir, 'claude', 'projects'),
|
||||||
|
claudeSessionsDir: join(dir, 'claude', 'sessions'),
|
||||||
|
vapidContact: 'mailto:test@localhost',
|
||||||
|
};
|
||||||
|
bundle = buildApp(config, db, '0.0.0-test');
|
||||||
|
const t = bundle.auth.ensureBootstrapToken();
|
||||||
|
if (!t) throw new Error('bootstrap token attendu sur une base vierge');
|
||||||
|
token = t;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await bundle.app.close();
|
||||||
|
db.close();
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/projects', () => {
|
||||||
|
it('crée le dossier et lance une session (sans git)', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', headers: auth(), payload: { root, name: 'plain', command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(201);
|
||||||
|
const body = res.json() as CreateProjectResponse;
|
||||||
|
expect(body.path).toBe(join(root, 'plain'));
|
||||||
|
expect(body.gitInitialized).toBe(false);
|
||||||
|
expect(existsSync(join(root, 'plain'))).toBe(true);
|
||||||
|
expect(existsSync(join(root, 'plain', '.git'))).toBe(false);
|
||||||
|
expect(body.session.cwd).toBe(join(root, 'plain'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gitInit:true crée un dépôt git', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', headers: auth(), payload: { root, name: 'withgit', gitInit: true, command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(201);
|
||||||
|
const body = res.json() as CreateProjectResponse;
|
||||||
|
expect(body.gitInitialized).toBe(true);
|
||||||
|
expect(existsSync(join(root, 'withgit', '.git'))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('nom avec `..` ou séparateur → 400 (anti-traversal)', async () => {
|
||||||
|
for (const name of ['..', 'a/b', '../evil']) {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', headers: auth(), payload: { root, name, command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dossier déjà existant → 409 PROJECT_EXISTS', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', headers: auth(), payload: { root, name: 'plain', command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(409);
|
||||||
|
expect(res.json()).toMatchObject({ error: { code: 'PROJECT_EXISTS' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('racine inexistante → 404', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', headers: auth(), payload: { root: join(root, 'nope-xyz'), name: 'x', command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('root relatif → 400', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', headers: auth(), payload: { root: 'relatif/x', name: 'x', command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sans authentification → 401', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'POST', url: '/api/v1/projects', payload: { root, name: 'noauth', command: 'bash' } });
|
||||||
|
expect(res.statusCode).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -243,7 +243,11 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
|
|
||||||
it('resync à l’attach = queue du ring (REPLAY_TAIL_BYTES max)', () => {
|
it('resync à l’attach = queue du ring (REPLAY_TAIL_BYTES max)', () => {
|
||||||
const { summary, pty } = spawnBash();
|
const { summary, pty } = spawnBash();
|
||||||
const chunks = ['A', 'B', 'C'].map((c) => c.repeat(100 * 1024));
|
// on écrit volontairement PLUS que REPLAY_TAIL_BYTES (mais < RING_CAPACITY) pour vérifier
|
||||||
|
// le plafonnement de la queue rejouée. Tailles dérivées de la constante → robuste aux bumps.
|
||||||
|
const chunkSize = 256 * 1024;
|
||||||
|
const chunkCount = Math.ceil(REPLAY_TAIL_BYTES / chunkSize) + 2;
|
||||||
|
const chunks = Array.from({ length: chunkCount }, (_, i) => String.fromCharCode(65 + (i % 26)).repeat(chunkSize));
|
||||||
for (const c of chunks) pty.emitData(c);
|
for (const c of chunks) pty.emitData(c);
|
||||||
|
|
||||||
const b = makeBinding('interactive');
|
const b = makeBinding('interactive');
|
||||||
@@ -410,6 +414,44 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
rmSync(sessDir, { recursive: true, force: true });
|
rmSync(sessDir, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('une notif sur le front montant busy→idle (Claude a terminé → disponible), après le debounce', async () => {
|
||||||
|
const sessDir = mkdtempSync(join(tmpdir(), 'arb-push-idle-'));
|
||||||
|
const notifies: PushPayload[] = [];
|
||||||
|
const fakePush = {
|
||||||
|
notify: async (p: PushPayload) => {
|
||||||
|
notifies.push(p);
|
||||||
|
},
|
||||||
|
} as unknown as PushService;
|
||||||
|
const m = new PtyManager(db, sessDir, fakePush);
|
||||||
|
try {
|
||||||
|
const summary = m.spawn({ cwd, command: 'claude' });
|
||||||
|
const p = lastPty();
|
||||||
|
const regFile = join(sessDir, `${p.pid}.json`);
|
||||||
|
const writeReg = (status: string): void =>
|
||||||
|
writeFileSync(regFile, JSON.stringify({ pid: p.pid, procStart: '1', sessionId: 'sid', cwd, status }));
|
||||||
|
|
||||||
|
// busy d'abord : front montant vers busy, pas de notif
|
||||||
|
writeReg('busy');
|
||||||
|
p.emitData('working…');
|
||||||
|
await sleep(260);
|
||||||
|
expect(notifies).toHaveLength(0);
|
||||||
|
|
||||||
|
// idle : Claude a terminé → front busy→idle → planifie la notif (debounce 1500ms)
|
||||||
|
writeReg('idle');
|
||||||
|
p.emitData('\x1b[2J\x1b[HDone.\r\n');
|
||||||
|
await sleep(260);
|
||||||
|
expect(notifies).toHaveLength(0); // pas encore : debounce en cours
|
||||||
|
|
||||||
|
await sleep(1500); // dépasse le debounce
|
||||||
|
expect(notifies).toHaveLength(1);
|
||||||
|
expect(notifies[0]).toMatchObject({ sessionId: summary.id, kind: null, url: `/sessions/${summary.id}` });
|
||||||
|
expect(notifies[0].body).toMatch(/available/i);
|
||||||
|
} finally {
|
||||||
|
m.shutdown();
|
||||||
|
rmSync(sessDir, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('flow control', () => {
|
describe('flow control', () => {
|
||||||
|
|||||||
63
packages/server/test/retention-settings.test.ts
Normal file
63
packages/server/test/retention-settings.test.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
// Réglages de rétention des sessions (P10) : validateurs + lecture/écriture DB.
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { openDb, setSetting, type Db } from '../src/db/index.js';
|
||||||
|
import {
|
||||||
|
DEFAULT_PURGE_DAYS,
|
||||||
|
DEFAULT_RETENTION_DAYS,
|
||||||
|
PURGE_DAYS_KEY,
|
||||||
|
RETENTION_DAYS_KEY,
|
||||||
|
normalizePurgeDays,
|
||||||
|
normalizeRetentionDays,
|
||||||
|
readPurgeDays,
|
||||||
|
readRetentionDays,
|
||||||
|
} from '../src/core/retention-settings.js';
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
beforeEach(() => {
|
||||||
|
db = openDb(':memory:');
|
||||||
|
});
|
||||||
|
afterEach(() => db.close());
|
||||||
|
|
||||||
|
describe('normalizeRetentionDays', () => {
|
||||||
|
it('accepte 0 (= jamais)', () => {
|
||||||
|
expect(normalizeRetentionDays(0)).toBe(0);
|
||||||
|
});
|
||||||
|
it('accepte une valeur dans les bornes', () => {
|
||||||
|
expect(normalizeRetentionDays(30)).toBe(30);
|
||||||
|
expect(normalizeRetentionDays(1)).toBe(1);
|
||||||
|
expect(normalizeRetentionDays(3650)).toBe(3650);
|
||||||
|
});
|
||||||
|
it('rejette hors bornes, non-entier, non-nombre', () => {
|
||||||
|
expect(normalizeRetentionDays(-1)).toBeNull();
|
||||||
|
expect(normalizeRetentionDays(3651)).toBeNull();
|
||||||
|
expect(normalizeRetentionDays(1.5)).toBeNull();
|
||||||
|
expect(normalizeRetentionDays('30')).toBeNull();
|
||||||
|
expect(normalizeRetentionDays(null)).toBeNull();
|
||||||
|
});
|
||||||
|
it('purge partage exactement les mêmes règles', () => {
|
||||||
|
expect(normalizePurgeDays).toBe(normalizeRetentionDays);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('readRetentionDays / readPurgeDays', () => {
|
||||||
|
it('défaut quand absent', () => {
|
||||||
|
expect(readRetentionDays(db)).toBe(DEFAULT_RETENTION_DAYS);
|
||||||
|
expect(readPurgeDays(db)).toBe(DEFAULT_PURGE_DAYS);
|
||||||
|
});
|
||||||
|
it('lit une valeur posée', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '7');
|
||||||
|
setSetting(db, PURGE_DAYS_KEY, '90');
|
||||||
|
expect(readRetentionDays(db)).toBe(7);
|
||||||
|
expect(readPurgeDays(db)).toBe(90);
|
||||||
|
});
|
||||||
|
it('0 est une valeur valide (désactivé)', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '0');
|
||||||
|
expect(readRetentionDays(db)).toBe(0);
|
||||||
|
});
|
||||||
|
it('tolère une valeur corrompue → défaut', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, 'not-a-number');
|
||||||
|
expect(readRetentionDays(db)).toBe(DEFAULT_RETENTION_DAYS);
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '99999');
|
||||||
|
expect(readRetentionDays(db)).toBe(DEFAULT_RETENTION_DAYS);
|
||||||
|
});
|
||||||
|
});
|
||||||
69
packages/server/test/session-archive.test.ts
Normal file
69
packages/server/test/session-archive.test.ts
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
// Archivage automatique des sessions terminées (P10) : scheduler sweep() sur base :memory:.
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { isSessionArchived, openDb, setSetting, type Db } from '../src/db/index.js';
|
||||||
|
import { RETENTION_DAYS_KEY } from '../src/core/retention-settings.js';
|
||||||
|
import { SessionArchiveService } from '../src/core/session-archive.js';
|
||||||
|
|
||||||
|
let db: Db;
|
||||||
|
|
||||||
|
function insertSession(id: string, endedAt: string | null): void {
|
||||||
|
db.prepare('INSERT INTO sessions (id, cwd, command, created_at, ended_at) VALUES (?, ?, ?, ?, ?)').run(
|
||||||
|
id,
|
||||||
|
'/tmp/x',
|
||||||
|
'bash',
|
||||||
|
'2020-01-01T00:00:00.000Z',
|
||||||
|
endedAt,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
db = openDb(':memory:');
|
||||||
|
insertSession('old', '2020-01-01T00:00:00.000Z'); // terminée il y a longtemps
|
||||||
|
insertSession('recent', new Date().toISOString()); // terminée à l'instant
|
||||||
|
insertSession('live', null); // vivante (jamais archivée)
|
||||||
|
});
|
||||||
|
afterEach(() => db.close());
|
||||||
|
|
||||||
|
describe('SessionArchiveService.sweep', () => {
|
||||||
|
it('archive seulement les sessions terminées plus anciennes que la rétention', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '30');
|
||||||
|
const svc = new SessionArchiveService({ db });
|
||||||
|
const events: string[] = [];
|
||||||
|
svc.on('session_archived', (e) => events.push(e.id));
|
||||||
|
|
||||||
|
const n = svc.sweep();
|
||||||
|
|
||||||
|
expect(n).toBe(1);
|
||||||
|
expect(events).toEqual(['old']);
|
||||||
|
expect(isSessionArchived(db, 'old')).toBe(true);
|
||||||
|
expect(isSessionArchived(db, 'recent')).toBe(false);
|
||||||
|
expect(isSessionArchived(db, 'live')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('est idempotent : un second balayage n’archive rien de plus', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '30');
|
||||||
|
const svc = new SessionArchiveService({ db });
|
||||||
|
expect(svc.sweep()).toBe(1);
|
||||||
|
|
||||||
|
const events: string[] = [];
|
||||||
|
svc.on('session_archived', (e) => events.push(e.id));
|
||||||
|
expect(svc.sweep()).toBe(0);
|
||||||
|
expect(events).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rétention = 0 → no-op (archivage désactivé)', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '0');
|
||||||
|
const svc = new SessionArchiveService({ db });
|
||||||
|
expect(svc.sweep()).toBe(0);
|
||||||
|
expect(isSessionArchived(db, 'old')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('start() déclenche un balayage immédiat puis stop() est sûr', () => {
|
||||||
|
setSetting(db, RETENTION_DAYS_KEY, '30');
|
||||||
|
const svc = new SessionArchiveService({ db, intervalMs: 60_000 });
|
||||||
|
svc.start();
|
||||||
|
expect(isSessionArchived(db, 'old')).toBe(true);
|
||||||
|
svc.stop();
|
||||||
|
svc.stop(); // idempotent
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -48,6 +48,8 @@ beforeAll(() => {
|
|||||||
dataDir: dir,
|
dataDir: dir,
|
||||||
allowedOrigins: ['https://host.tailnet.ts.net'],
|
allowedOrigins: ['https://host.tailnet.ts.net'],
|
||||||
printToken: false,
|
printToken: false,
|
||||||
|
claudeHome: join(dir, 'claude'),
|
||||||
|
claudeHomeFromFlag: false,
|
||||||
claudeProjectsDir: join(dir, 'claude', 'projects'),
|
claudeProjectsDir: join(dir, 'claude', 'projects'),
|
||||||
claudeSessionsDir: join(dir, 'claude', 'sessions'),
|
claudeSessionsDir: join(dir, 'claude', 'sessions'),
|
||||||
vapidContact: 'mailto:test@localhost',
|
vapidContact: 'mailto:test@localhost',
|
||||||
@@ -77,6 +79,14 @@ describe('GET /api/v1/settings', () => {
|
|||||||
// défauts de découverte : AUCUNE racine (clean install → pas de scan) + intervalle 5 min
|
// défauts de découverte : AUCUNE racine (clean install → pas de scan) + intervalle 5 min
|
||||||
expect(body.settings.scanRoots).toEqual([]);
|
expect(body.settings.scanRoots).toEqual([]);
|
||||||
expect(body.settings.scanIntervalMin).toBe(5);
|
expect(body.settings.scanIntervalMin).toBe(5);
|
||||||
|
// Claude CLI : aucun override par défaut + diagnostic via PATH (execFileSync mocké → /usr/bin/claude).
|
||||||
|
expect(body.settings.claudeBinPath).toBeNull();
|
||||||
|
expect(body.settings.claudeHome).toBeNull();
|
||||||
|
expect(body.server.claudeHome).toBe(join(dir, 'claude'));
|
||||||
|
expect(body.server.claudeBin).toEqual({ path: '/usr/bin/claude', source: 'path', ok: true });
|
||||||
|
// rétention des sessions (P10) : défaut 30 j d'archivage, purge désactivée (0).
|
||||||
|
expect(body.settings.retentionDays).toBe(30);
|
||||||
|
expect(body.settings.purgeDays).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('n’expose AUCUN secret (server_secret, clé privée VAPID)', async () => {
|
it('n’expose AUCUN secret (server_secret, clé privée VAPID)', async () => {
|
||||||
@@ -137,3 +147,67 @@ describe('PATCH /api/v1/settings — découverte des dépôts', () => {
|
|||||||
expect(neg.statusCode).toBe(400);
|
expect(neg.statusCode).toBe(400);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
it('enregistre un chemin de binaire exécutable et reflète le diagnostic (source=configured)', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeBinPath: realBin } });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
const body = res.json() as SettingsResponse;
|
||||||
|
expect(body.settings.claudeBinPath).toBe(realBin);
|
||||||
|
expect(body.server.claudeBin).toEqual({ path: realBin, source: 'configured', ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('réinitialise le chemin avec "" (retour à l’auto-détection via PATH)', async () => {
|
||||||
|
await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeBinPath: realBin } });
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeBinPath: '' } });
|
||||||
|
const body = res.json() as SettingsResponse;
|
||||||
|
expect(body.settings.claudeBinPath).toBeNull();
|
||||||
|
expect(body.server.claudeBin.source).toBe('path'); // de nouveau via PATH (mock → /usr/bin/claude)
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette un chemin non absolu ou non exécutable (400)', async () => {
|
||||||
|
for (const claudeBinPath of ['relative/claude', '/a/../b', dir /* répertoire, pas un fichier */]) {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeBinPath } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enregistre un override claude_home (répertoire existant) et le réinitialise avec ""', async () => {
|
||||||
|
const set = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeHome: dir } });
|
||||||
|
expect(set.statusCode).toBe(200);
|
||||||
|
expect((set.json() as SettingsResponse).settings.claudeHome).toBe(dir);
|
||||||
|
const reset = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeHome: '' } });
|
||||||
|
expect((reset.json() as SettingsResponse).settings.claudeHome).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette un claude_home non absolu ou inexistant/fichier (400)', async () => {
|
||||||
|
for (const claudeHome of ['relative/.claude', join(dir, 'settings.db') /* fichier */, join(dir, 'nope')]) {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { claudeHome } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
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);
|
||||||
|
expect((res.json() as SettingsResponse).settings.retentionDays).toBe(7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepte 0 (= jamais archiver)', async () => {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { retentionDays: 0 } });
|
||||||
|
expect(res.statusCode).toBe(200);
|
||||||
|
expect((res.json() as SettingsResponse).settings.retentionDays).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette une rétention hors borne ou non-entière (400)', async () => {
|
||||||
|
for (const retentionDays of [-1, 3651, 1.5]) {
|
||||||
|
const res = await bundle.app.inject({ method: 'PATCH', url: '/api/v1/settings', headers: auth(), payload: { retentionDays } });
|
||||||
|
expect(res.statusCode).toBe(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -97,7 +97,8 @@ describe('WorktreeManager', () => {
|
|||||||
|
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-feat`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
const out = await wt.createWorktree(r.id, { branch: 'feat', newBranch: true, runHooks: true });
|
const out = await wt.createWorktree(r.id, { branch: 'feat', mode: 'create', runHooks: true });
|
||||||
|
expect(out.action).toBe('created');
|
||||||
|
|
||||||
expect(resolve(out.worktree.path)).toBe(resolve(wtPath));
|
expect(resolve(out.worktree.path)).toBe(resolve(wtPath));
|
||||||
expect(out.worktree.branch).toBe('feat');
|
expect(out.worktree.branch).toBe('feat');
|
||||||
@@ -113,7 +114,7 @@ describe('WorktreeManager', () => {
|
|||||||
it('createWorktree : branche invalide → 400', async () => {
|
it('createWorktree : branche invalide → 400', async () => {
|
||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
await expect(wt.createWorktree(r.id, { branch: '../evil', newBranch: true })).rejects.toMatchObject({ statusCode: 400 });
|
await expect(wt.createWorktree(r.id, { branch: '../evil', mode: 'create' })).rejects.toMatchObject({ statusCode: 400 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('startMainSession : session dans le checkout principal (branche actuelle, sans mutation git)', async () => {
|
it('startMainSession : session dans le checkout principal (branche actuelle, sans mutation git)', async () => {
|
||||||
@@ -163,7 +164,7 @@ describe('WorktreeManager', () => {
|
|||||||
|
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-x`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-x`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await wt.createWorktree(r.id, { branch: 'x', newBranch: true, runHooks: false });
|
await wt.createWorktree(r.id, { branch: 'x', mode: 'create', runHooks: false });
|
||||||
writeFileSync(join(wtPath, 'scratch.txt'), 'wip\n'); // worktree sale
|
writeFileSync(join(wtPath, 'scratch.txt'), 'wip\n'); // worktree sale
|
||||||
|
|
||||||
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'WORKTREE_DIRTY' });
|
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'WORKTREE_DIRTY' });
|
||||||
@@ -176,7 +177,7 @@ describe('WorktreeManager', () => {
|
|||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-sess`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-sess`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await wt.createWorktree(r.id, { branch: 'sess', newBranch: true, runHooks: false });
|
await wt.createWorktree(r.id, { branch: 'sess', mode: 'create', runHooks: false });
|
||||||
|
|
||||||
pty.spawn({ cwd: wtPath, command: 'bash' });
|
pty.spawn({ cwd: wtPath, command: 'bash' });
|
||||||
const list = await wt.listRepoWorktrees(r.id, true);
|
const list = await wt.listRepoWorktrees(r.id, true);
|
||||||
@@ -190,11 +191,49 @@ describe('WorktreeManager', () => {
|
|||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
const wtPath = join(dirname(repo), `${basename(repo)}-wt-busy`);
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-busy`);
|
||||||
dirs.push(wtPath);
|
dirs.push(wtPath);
|
||||||
await wt.createWorktree(r.id, { branch: 'busy', newBranch: true, runHooks: false });
|
await wt.createWorktree(r.id, { branch: 'busy', mode: 'create', runHooks: false });
|
||||||
pty.spawn({ cwd: wtPath, command: 'bash' });
|
pty.spawn({ cwd: wtPath, command: 'bash' });
|
||||||
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'SESSION_LIVE_IN_WORKTREE' });
|
await expect(wt.deleteWorktree(r.id, wtPath, false)).rejects.toMatchObject({ statusCode: 409, code: 'SESSION_LIVE_IN_WORKTREE' });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('listRepoBranches : renvoie les branches locales (dont main)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const b = await wt.listRepoBranches(r.id);
|
||||||
|
expect(b.local).toContain('main');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('commitWorktree : arbre propre → 409 NOTHING_TO_COMMIT ; arbre sale → commit (dirty=0)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
await expect(wt.commitWorktree(r.id, repo, 'noop')).rejects.toMatchObject({ statusCode: 409, code: 'NOTHING_TO_COMMIT' });
|
||||||
|
writeFileSync(join(repo, 'f.txt'), 'x\n');
|
||||||
|
const w = await wt.commitWorktree(r.id, repo, 'add f');
|
||||||
|
expect(w.git.dirtyCount).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('promoteWorktree : la branche du worktree devient le checkout principal, worktree supprimé, ancienne branche conservée', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const wtPath = join(dirname(repo), `${basename(repo)}-wt-prom`);
|
||||||
|
dirs.push(wtPath);
|
||||||
|
await wt.createWorktree(r.id, { branch: 'prom', mode: 'create', runHooks: false });
|
||||||
|
|
||||||
|
await wt.promoteWorktree(r.id, wtPath);
|
||||||
|
|
||||||
|
expect(execFileSync('git', ['branch', '--show-current'], { cwd: repo }).toString().trim()).toBe('prom');
|
||||||
|
expect((await wt.listRepoWorktrees(r.id, true)).some((w) => resolve(w.path) === resolve(wtPath))).toBe(false);
|
||||||
|
const branches = await wt.listRepoBranches(r.id);
|
||||||
|
expect(branches.local).toContain('main'); // ancienne branche principale conservée
|
||||||
|
expect(branches.local).toContain('prom');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('promoteWorktree : checkout principal refusé (400 IS_MAIN_WORKTREE)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
await expect(wt.promoteWorktree(r.id, repo)).rejects.toMatchObject({ statusCode: 400, code: 'IS_MAIN_WORKTREE' });
|
||||||
|
});
|
||||||
|
|
||||||
it('addRepo renvoie hidden:false ; updateRepo({hidden}) bascule et émet repo_update', async () => {
|
it('addRepo renvoie hidden:false ; updateRepo({hidden}) bascule et émet repo_update', async () => {
|
||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
// Types REST partagés (préfixe /api/v1).
|
// Types REST partagés (préfixe /api/v1).
|
||||||
import type { GroupSummary, PostCreateHook, RepoSummary, SessionSummary, WorktreeSummary } from './protocol.js';
|
import type { CloneOperation, GroupSummary, PostCreateHook, RepoSummary, SessionSummary, SettingsBroadcast, WorktreeSummary } from './protocol.js';
|
||||||
|
|
||||||
export interface ApiError {
|
export interface ApiError {
|
||||||
error: { code: string; message: string; details?: unknown };
|
error: { code: string; message: string; details?: unknown };
|
||||||
@@ -47,6 +47,29 @@ export interface CreateSessionRequest {
|
|||||||
/** 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';
|
command?: 'claude' | 'bash';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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`.
|
||||||
|
*/
|
||||||
|
export interface CreateProjectRequest {
|
||||||
|
/** racine absolue où créer le projet (doit déjà exister). */
|
||||||
|
root: string;
|
||||||
|
/** nom du dossier de projet : un seul segment, sans séparateur ni `..`. */
|
||||||
|
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. */
|
||||||
|
command?: 'claude' | 'bash';
|
||||||
|
}
|
||||||
|
export interface CreateProjectResponse {
|
||||||
|
session: SessionSummary;
|
||||||
|
/** chemin absolu du dossier de projet créé. */
|
||||||
|
path: string;
|
||||||
|
/** true si `git init` a réellement été exécuté. */
|
||||||
|
gitInitialized: boolean;
|
||||||
|
}
|
||||||
export interface SessionsListResponse {
|
export interface SessionsListResponse {
|
||||||
sessions: SessionSummary[];
|
sessions: SessionSummary[];
|
||||||
}
|
}
|
||||||
@@ -109,11 +132,25 @@ export interface HookRunResult {
|
|||||||
output: string;
|
output: string;
|
||||||
durationMs: number;
|
durationMs: number;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
* `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à.
|
||||||
|
* - `checkout` : force le checkout d'une branche existante, échoue si elle est absente.
|
||||||
|
*/
|
||||||
|
export type WorktreeBranchMode = 'auto' | 'create' | 'checkout';
|
||||||
|
/** Action réellement effectuée par la résolution `auto` (feedback UI). */
|
||||||
|
export type WorktreeBranchAction = 'created' | 'reused' | 'tracked';
|
||||||
|
|
||||||
export interface CreateWorktreeRequest {
|
export interface CreateWorktreeRequest {
|
||||||
branch: string;
|
branch: string;
|
||||||
/** true : créer la branche (`-b`) ; false : checkout d'une branche existante. */
|
/** stratégie de résolution de la branche (défaut : `auto`). Voir {@link WorktreeBranchMode}. */
|
||||||
newBranch: boolean;
|
mode?: WorktreeBranchMode;
|
||||||
/** point de départ de la nouvelle branche (défaut : HEAD courant du repo). */
|
/** @deprecated remplacé par `mode` ; mappé : true→create, false→checkout, absent→auto. */
|
||||||
|
newBranch?: boolean;
|
||||||
|
/** point de départ d'une branche créée (défaut : branche par défaut du dépôt, sinon HEAD). */
|
||||||
baseRef?: string;
|
baseRef?: string;
|
||||||
/** chemin cible du worktree (défaut : `<parent>/<repo>-wt-<branch>`). */
|
/** chemin cible du worktree (défaut : `<parent>/<repo>-wt-<branch>`). */
|
||||||
path?: string;
|
path?: string;
|
||||||
@@ -126,6 +163,135 @@ export interface CreateWorktreeResponse {
|
|||||||
worktree: WorktreeSummary;
|
worktree: WorktreeSummary;
|
||||||
hookResults: HookRunResult[];
|
hookResults: HookRunResult[];
|
||||||
session: SessionSummary | null;
|
session: SessionSummary | null;
|
||||||
|
/** action effective de la résolution de branche (créée / réutilisée / suivie du remote). */
|
||||||
|
action: WorktreeBranchAction;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/v1/repos/:id/branches — branches locales/remote pour alimenter un sélecteur de base. */
|
||||||
|
export interface RepoBranchesResponse {
|
||||||
|
local: string[];
|
||||||
|
remote: string[];
|
||||||
|
/** branche par défaut du dépôt (origin/HEAD), ou null si indéterminée. */
|
||||||
|
default: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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
|
||||||
|
* de l'index uniquement (staging sélectif préalable via /stage). `amend` réécrit le dernier
|
||||||
|
* commit (refusé s'il est déjà poussé).
|
||||||
|
*/
|
||||||
|
mode?: 'all' | 'staged';
|
||||||
|
amend?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- P7 : diff par fichier, statut détaillé, contenu de fichier (IDE worktree) ----
|
||||||
|
/** Un fichier modifié dans un worktree (sortie de `git status --porcelain=v2` + `--numstat`). */
|
||||||
|
export interface FileChange {
|
||||||
|
/** chemin relatif à la racine du worktree (POSIX). */
|
||||||
|
path: string;
|
||||||
|
/** code d'état dans l'index (X de XY porcelain), '.' si inchangé. */
|
||||||
|
indexStatus: string;
|
||||||
|
/** code d'état dans l'arbre de travail (Y de XY porcelain), '.' si inchangé. */
|
||||||
|
worktreeStatus: string;
|
||||||
|
/** true si une partie est indexée (staged). */
|
||||||
|
staged: boolean;
|
||||||
|
/** true si une partie est non indexée (unstaged) ou non suivie (untracked). */
|
||||||
|
unstaged: boolean;
|
||||||
|
/** true pour les fichiers non suivis (untracked). */
|
||||||
|
untracked: boolean;
|
||||||
|
/** true pour les fichiers en conflit de merge (XY de type U/AA/DD). */
|
||||||
|
conflicted: boolean;
|
||||||
|
/** lignes ajoutées (null si binaire). */
|
||||||
|
insertions: number | null;
|
||||||
|
/** lignes supprimées (null si binaire). */
|
||||||
|
deletions: number | null;
|
||||||
|
/** true si git considère le fichier comme binaire (numstat = '-'). */
|
||||||
|
binary: boolean;
|
||||||
|
/** 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. */
|
||||||
|
export interface WorktreeChangesResponse {
|
||||||
|
repoId: string;
|
||||||
|
path: string;
|
||||||
|
changes: FileChange[];
|
||||||
|
/** 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. */
|
||||||
|
export interface FileDiffResponse {
|
||||||
|
path: string;
|
||||||
|
file: string;
|
||||||
|
staged: boolean;
|
||||||
|
binary: boolean;
|
||||||
|
/** true si le diff a été tronqué (fichier trop volumineux). */
|
||||||
|
tooLarge: boolean;
|
||||||
|
/** 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). */
|
||||||
|
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: 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). */
|
||||||
|
export interface WriteFileRequest {
|
||||||
|
/** chemin absolu du worktree. */
|
||||||
|
wt: string;
|
||||||
|
/** chemin relatif au worktree (POSIX). */
|
||||||
|
path: string;
|
||||||
|
content: string;
|
||||||
|
/** mtime (ms) lu au chargement ; si fourni et que le fichier a changé depuis → 409 STALE_FILE (P8). */
|
||||||
|
baseMtime?: number;
|
||||||
|
}
|
||||||
|
export interface WriteFileResponse {
|
||||||
|
ok: true;
|
||||||
|
size: number;
|
||||||
|
/** 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. */
|
||||||
|
export interface WorktreeFilesRequest {
|
||||||
|
path: string;
|
||||||
|
/** chemins relatifs au worktree. */
|
||||||
|
files: string[];
|
||||||
|
}
|
||||||
|
/** DELETE des changements locaux ; `includeUntracked` autorise `git clean` (destructif, opt-in). */
|
||||||
|
export interface DiscardFilesRequest extends WorktreeFilesRequest {
|
||||||
|
includeUntracked?: boolean;
|
||||||
|
}
|
||||||
|
/** 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). */
|
||||||
|
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). */
|
||||||
|
export interface PushWorktreeRequest {
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 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 {
|
||||||
|
path: string;
|
||||||
|
/** outrepasse les garde-fous d'arbre sale (worktree/checkout principal). */
|
||||||
|
force?: boolean;
|
||||||
}
|
}
|
||||||
export interface AdoptWorktreeRequest {
|
export interface AdoptWorktreeRequest {
|
||||||
path: string;
|
path: string;
|
||||||
@@ -190,10 +356,12 @@ export interface GroupSessionResponse {
|
|||||||
// ---- Navigateur de répertoires (sélecteur de dossier côté web) ----
|
// ---- Navigateur de répertoires (sélecteur de dossier côté web) ----
|
||||||
export interface FsEntry {
|
export interface FsEntry {
|
||||||
name: string;
|
name: string;
|
||||||
/** chemin absolu du dossier */
|
/** chemin absolu de l'entrée */
|
||||||
path: string;
|
path: string;
|
||||||
/** présent (true) uniquement en mode markRepos quand le dossier est un dépôt git */
|
/** présent (true) uniquement en mode markRepos quand le dossier est un dépôt git */
|
||||||
isRepo?: boolean;
|
isRepo?: boolean;
|
||||||
|
/** P7 — présent (true) en mode includeFiles quand l'entrée est un fichier (pas un dossier) */
|
||||||
|
isFile?: boolean;
|
||||||
}
|
}
|
||||||
export interface FsListResponse {
|
export interface FsListResponse {
|
||||||
/** chemin absolu listé (normalisé) */
|
/** chemin absolu listé (normalisé) */
|
||||||
@@ -230,15 +398,23 @@ export interface ServerInfo {
|
|||||||
/** clé publique VAPID (sûre à exposer) ; null si push indisponible. */
|
/** clé publique VAPID (sûre à exposer) ; null si push indisponible. */
|
||||||
vapidPublicKey: string | null;
|
vapidPublicKey: string | null;
|
||||||
vapidContact: string;
|
vapidContact: string;
|
||||||
|
/** racine effective de l'install Claude (~/.claude, --claude-home, ou réglage claude_home). */
|
||||||
|
claudeHome: string;
|
||||||
|
/** diagnostic de résolution du binaire `claude` (présence + exécutabilité). */
|
||||||
|
claudeBin: ClaudeBinDiagnostic;
|
||||||
|
}
|
||||||
|
/** Diagnostic de résolution du CLI `claude` exposé en lecture dans les Réglages. */
|
||||||
|
export interface ClaudeBinDiagnostic {
|
||||||
|
/** chemin résolu du binaire, ou null si introuvable. */
|
||||||
|
path: string | null;
|
||||||
|
/** 'configured' = réglage explicite ; 'path' = trouvé via PATH ; null = introuvable. */
|
||||||
|
source: 'configured' | 'path' | null;
|
||||||
|
/** true si le binaire est présent et exécutable. */
|
||||||
|
ok: boolean;
|
||||||
}
|
}
|
||||||
export interface SettingsResponse {
|
export interface SettingsResponse {
|
||||||
/** réglages modifiables à chaud (allow-list serveur — jamais les secrets). */
|
/** réglages modifiables à chaud (allow-list serveur — jamais les secrets). Cf. SettingsBroadcast. */
|
||||||
settings: {
|
settings: SettingsBroadcast;
|
||||||
/** racines absolues scannées pour la découverte auto des repos (défaut : aucune → pas de scan). */
|
|
||||||
scanRoots: string[];
|
|
||||||
/** intervalle du re-scan périodique en minutes ; 0 = périodique désactivé. */
|
|
||||||
scanIntervalMin: number;
|
|
||||||
};
|
|
||||||
server: ServerInfo;
|
server: ServerInfo;
|
||||||
}
|
}
|
||||||
export interface UpdateSettingsRequest {
|
export interface UpdateSettingsRequest {
|
||||||
@@ -246,6 +422,14 @@ export interface UpdateSettingsRequest {
|
|||||||
scanRoots?: string[];
|
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;
|
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). */
|
||||||
|
retentionDays?: number;
|
||||||
|
/** purge définitive après N jours (0 = désactivée ; sinon 1–3650). */
|
||||||
|
purgeDays?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Journal d'audit (conformité entreprise) ----
|
// ---- Journal d'audit (conformité entreprise) ----
|
||||||
@@ -287,3 +471,88 @@ export interface DeleteMyDataResponse {
|
|||||||
/** récapitulatif de ce qui sera/a été supprimé. */
|
/** récapitulatif de ce qui sera/a été supprimé. */
|
||||||
summary: { pushSubscriptions: number; tokenRevoked: boolean };
|
summary: { pushSubscriptions: number; tokenRevoked: boolean };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Services git distants + clone (P12) ----
|
||||||
|
export type GitService = 'gitea' | 'gitlab' | 'github';
|
||||||
|
export type GitAuthType = 'pat' | 'app_password' | 'ssh_key' | 'oauth';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Résumé d'un credential exposé à l'UI. Ne contient JAMAIS le secret : `hasSecret` indique sa
|
||||||
|
* présence, `secretLast4` n'en révèle que les 4 derniers caractères (repère visuel, non sensible).
|
||||||
|
*/
|
||||||
|
export interface GitCredentialSummary {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
service: GitService;
|
||||||
|
baseUrl: string | null;
|
||||||
|
authType: GitAuthType;
|
||||||
|
username: string | null;
|
||||||
|
hasSecret: boolean;
|
||||||
|
secretLast4: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
lastTestedAt: string | null;
|
||||||
|
/** diagnostic du dernier /test : 'ok' | 'AUTH_FAILED' | 'RATE_LIMITED' | 'UNREACHABLE' | … */
|
||||||
|
testResult: string | null;
|
||||||
|
}
|
||||||
|
export interface GitCredentialsListResponse {
|
||||||
|
credentials: GitCredentialSummary[];
|
||||||
|
}
|
||||||
|
export interface CreateGitCredentialRequest {
|
||||||
|
label: string;
|
||||||
|
service: GitService;
|
||||||
|
/** P12a : 'pat' | 'app_password' (HTTPS). 'ssh_key'/'oauth' arrivent en P12b/P12c. */
|
||||||
|
authType: GitAuthType;
|
||||||
|
/** 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. */
|
||||||
|
secret?: string;
|
||||||
|
}
|
||||||
|
export interface UpdateGitCredentialRequest {
|
||||||
|
label?: string;
|
||||||
|
baseUrl?: string;
|
||||||
|
username?: string;
|
||||||
|
/** si fourni, re-chiffre le secret ; absent = inchangé. */
|
||||||
|
secret?: string;
|
||||||
|
}
|
||||||
|
export interface GitCredentialResponse {
|
||||||
|
credential: GitCredentialSummary;
|
||||||
|
}
|
||||||
|
export interface TestCredentialResponse {
|
||||||
|
ok: boolean;
|
||||||
|
/** login renvoyé par le service en cas de succès. */
|
||||||
|
user?: string;
|
||||||
|
/** code d'erreur typé en cas d'échec (AUTH_FAILED, RATE_LIMITED, UNREACHABLE). */
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dépôt distant listé via l'API du service. */
|
||||||
|
export interface RemoteRepoSummary {
|
||||||
|
/** owner/name */
|
||||||
|
fullName: string;
|
||||||
|
/** URL HTTPS de clone. */
|
||||||
|
cloneUrl: string;
|
||||||
|
private: boolean;
|
||||||
|
description: string | null;
|
||||||
|
defaultBranch: string | null;
|
||||||
|
}
|
||||||
|
export interface RemoteReposResponse {
|
||||||
|
repos: RemoteRepoSummary[];
|
||||||
|
/** numéro de page suivant si d'autres résultats existent, sinon null. */
|
||||||
|
nextPage: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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. */
|
||||||
|
dest: string;
|
||||||
|
}
|
||||||
|
export interface CloneStartResponse {
|
||||||
|
operationId: string;
|
||||||
|
}
|
||||||
|
/** État d'un clone (GET /repos/clone/:id) — même forme que le push WS clone_update. */
|
||||||
|
export interface CloneStatusResponse {
|
||||||
|
operation: CloneOperation;
|
||||||
|
}
|
||||||
|
|||||||
@@ -51,8 +51,12 @@ export const FLOW = {
|
|||||||
LAGGING_BYTES: 2 * 1024 * 1024,
|
LAGGING_BYTES: 2 * 1024 * 1024,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
/** Replay à l'attach : reset terminal + queue du ring (l'écran TUI se repeint en continu) */
|
/**
|
||||||
export const REPLAY_TAIL_BYTES = 256 * 1024;
|
* 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 ;
|
||||||
|
* reste < LAGGING_BYTES (pas de faux lagging) et bien dans RING_CAPACITY.
|
||||||
|
*/
|
||||||
|
export const REPLAY_TAIL_BYTES = 1024 * 1024;
|
||||||
|
|
||||||
// ---- États de session (sous-ensemble P1 ; étendu en P3) ----
|
// ---- États de session (sous-ensemble P1 ; étendu en P3) ----
|
||||||
export type SessionRuntimeStatus =
|
export type SessionRuntimeStatus =
|
||||||
@@ -121,6 +125,9 @@ export interface SessionSummary {
|
|||||||
// ---- Masquage (additif) ----
|
// ---- Masquage (additif) ----
|
||||||
/** true = session découverte masquée par l'utilisateur (exclue de la liste sauf includeHidden). */
|
/** true = session découverte masquée par l'utilisateur (exclue de la liste sauf includeHidden). */
|
||||||
hidden?: boolean;
|
hidden?: boolean;
|
||||||
|
// ---- Archivage auto (P10, additif) ----
|
||||||
|
/** true = session managée auto-archivée par ancienneté (exclue de la liste sauf includeArchived). */
|
||||||
|
archived?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- Worktrees & repos (P3) ----
|
// ---- Worktrees & repos (P3) ----
|
||||||
@@ -153,6 +160,20 @@ export interface WorktreeGitStatus {
|
|||||||
behind: number;
|
behind: number;
|
||||||
dirtyCount: number;
|
dirtyCount: number;
|
||||||
upstream: string | null;
|
upstream: string | null;
|
||||||
|
// ---- 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`).
|
||||||
|
/** fichiers avec des modifications indexées (staged). */
|
||||||
|
stagedCount?: number;
|
||||||
|
/** fichiers avec des modifications non indexées (unstaged, untracked inclus). */
|
||||||
|
unstagedCount?: number;
|
||||||
|
/** fichiers en conflit de merge. */
|
||||||
|
conflictCount?: number;
|
||||||
|
/** hash court du dernier commit (HEAD), null si le dépôt n'a aucun commit. */
|
||||||
|
lastCommitHash?: string | null;
|
||||||
|
/** sujet (première ligne) du dernier commit. */
|
||||||
|
lastCommitSubject?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WorktreeSummary {
|
export interface WorktreeSummary {
|
||||||
@@ -186,6 +207,41 @@ export interface GroupSummary {
|
|||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- Réglages diffusables (P11) ----
|
||||||
|
// Sous-ensemble NON sensible des réglages, transporté tel quel par `settings_update` et par la
|
||||||
|
// réponse REST GET /settings (source de vérité unique du type). JAMAIS de secret ici.
|
||||||
|
export interface SettingsBroadcast {
|
||||||
|
/** racines absolues scannées pour la découverte auto des repos (défaut : aucune → pas de scan). */
|
||||||
|
scanRoots: string[];
|
||||||
|
/** intervalle du re-scan périodique en minutes ; 0 = périodique désactivé. */
|
||||||
|
scanIntervalMin: number;
|
||||||
|
/** chemin explicite du binaire `claude` ; null = auto-détection via PATH. */
|
||||||
|
claudeBinPath: string | null;
|
||||||
|
/** override de la racine ~/.claude ; null = défaut. */
|
||||||
|
claudeHome: string | null;
|
||||||
|
/** rétention des sessions terminées : auto-archivage après N jours ; 0 = jamais (P10). */
|
||||||
|
retentionDays: number;
|
||||||
|
/** purge définitive après N jours ; 0 = désactivée. */
|
||||||
|
purgeDays: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Clone d'un dépôt distant (P12) ----
|
||||||
|
export type CloneState = 'pending' | 'running' | 'done' | 'error';
|
||||||
|
/** État d'une opération de clone (poussé en WS sous le topic 'clones' ET lu en REST). */
|
||||||
|
export interface CloneOperation {
|
||||||
|
id: string;
|
||||||
|
state: CloneState;
|
||||||
|
/** 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;
|
||||||
|
error: string | null;
|
||||||
|
/** id du repo enregistré une fois le clone terminé (null avant). */
|
||||||
|
repoId: string | null;
|
||||||
|
/** dossier de destination du clone. */
|
||||||
|
dest: string;
|
||||||
|
}
|
||||||
|
|
||||||
// ---- Messages client → serveur ----
|
// ---- Messages client → serveur ----
|
||||||
export type ClientMessage =
|
export type ClientMessage =
|
||||||
| { type: 'hello'; protocol: number }
|
| { type: 'hello'; protocol: number }
|
||||||
@@ -198,7 +254,12 @@ export type ClientMessage =
|
|||||||
| { type: 'answer'; channel: number; action: 'select' | 'confirm' | 'deny'; optionN?: number }
|
| { type: 'answer'; channel: number; action: 'select' | 'confirm' | 'deny'; optionN?: number }
|
||||||
| { type: 'resize'; channel: number; cols: number; rows: number }
|
| { type: 'resize'; channel: number; cols: number; rows: number }
|
||||||
| { type: 'ack'; channel: number; bytes: number }
|
| { type: 'ack'; channel: number; bytes: number }
|
||||||
| { type: 'sub'; topics: Array<'sessions' | 'worktrees' | 'groups'> }
|
| { 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
|
||||||
|
// 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 }
|
||||||
|
| { type: 'unwatch'; repoId: string; path: string }
|
||||||
| { type: 'ping' };
|
| { type: 'ping' };
|
||||||
|
|
||||||
// ---- Messages serveur → client ----
|
// ---- Messages serveur → client ----
|
||||||
@@ -209,10 +270,23 @@ export type ServerMessage =
|
|||||||
| { type: 'control_changed'; channel: number; controlling: boolean }
|
| { type: 'control_changed'; channel: number; controlling: boolean }
|
||||||
| { type: 'session_update'; session: SessionSummary }
|
| { type: 'session_update'; session: SessionSummary }
|
||||||
| { type: 'session_exit'; sessionId: string; exitCode: number | null; signal: number | null }
|
| { 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
|
||||||
|
// 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
|
||||||
|
// 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
|
||||||
|
// (state) discrimine progress/done/error en un seul message.
|
||||||
|
| { type: 'clone_update'; operation: CloneOperation }
|
||||||
| { type: 'repo_update'; repo: RepoSummary }
|
| { type: 'repo_update'; repo: RepoSummary }
|
||||||
| { type: 'repo_removed'; repoId: string }
|
| { type: 'repo_removed'; repoId: string }
|
||||||
| { type: 'worktree_update'; repoId: string; worktree: WorktreeSummary }
|
| { type: 'worktree_update'; repoId: string; worktree: WorktreeSummary }
|
||||||
| { type: 'worktree_removed'; repoId: string; path: string }
|
| { 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
|
||||||
|
// 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 }
|
||||||
| { type: 'group_update'; group: GroupSummary }
|
| { type: 'group_update'; group: GroupSummary }
|
||||||
| { type: 'group_removed'; groupId: string }
|
| { type: 'group_removed'; groupId: string }
|
||||||
| { type: 'error'; code: ErrorCode; message: string; channel?: number }
|
| { type: 'error'; code: ErrorCode; message: string; channel?: number }
|
||||||
@@ -272,8 +346,16 @@ export function parseClientMessage(raw: string): ClientMessage | null {
|
|||||||
? { type: 'ack', channel: m.channel, bytes: m.bytes }
|
? { type: 'ack', channel: m.channel, bytes: m.bytes }
|
||||||
: null;
|
: null;
|
||||||
case 'sub':
|
case 'sub':
|
||||||
return Array.isArray(m.topics) && m.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups')
|
return Array.isArray(m.topics) && m.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups' || t === 'settings' || t === 'clones')
|
||||||
? { type: 'sub', topics: m.topics as Array<'sessions' | 'worktrees' | 'groups'> }
|
? { type: 'sub', topics: m.topics as Array<'sessions' | 'worktrees' | 'groups' | 'settings' | 'clones'> }
|
||||||
|
: null;
|
||||||
|
case 'watch':
|
||||||
|
case 'unwatch':
|
||||||
|
// repoId/path bornés ici (typage + longueur) ; l'existence repo/worktree et la sûreté du
|
||||||
|
// chemin sont re-validées côté serveur (isSafeAbsolutePath + findWorktree) avant d'armer.
|
||||||
|
return typeof m.repoId === 'string' && m.repoId.length > 0 && m.repoId.length <= 128 &&
|
||||||
|
typeof m.path === 'string' && m.path.length > 0 && m.path.length <= 4096
|
||||||
|
? { type: m.type, repoId: m.repoId, path: m.path }
|
||||||
: null;
|
: null;
|
||||||
case 'ping':
|
case 'ping':
|
||||||
return { type: 'ping' };
|
return { type: 'ping' };
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ function assertInvariants(msg: ClientMessage): void {
|
|||||||
expect(msg.bytes).toBeGreaterThanOrEqual(0);
|
expect(msg.bytes).toBeGreaterThanOrEqual(0);
|
||||||
break;
|
break;
|
||||||
case 'sub':
|
case 'sub':
|
||||||
expect(msg.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups')).toBe(true);
|
expect(msg.topics.every((t) => t === 'sessions' || t === 'worktrees' || t === 'groups' || t === 'settings')).toBe(true);
|
||||||
break;
|
break;
|
||||||
case 'ping':
|
case 'ping':
|
||||||
break;
|
break;
|
||||||
@@ -128,6 +128,17 @@ describe('parseClientMessage — cas valides', () => {
|
|||||||
expect(parseClientMessage('{"type":"sub","topics":[]}')).toEqual({ type: 'sub', topics: [] });
|
expect(parseClientMessage('{"type":"sub","topics":[]}')).toEqual({ type: 'sub', topics: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('sub accepte le topic settings (P11) et rejette un topic inconnu', () => {
|
||||||
|
expect(parseClientMessage('{"type":"sub","topics":["settings"]}')).toEqual({ type: 'sub', topics: ['settings'] });
|
||||||
|
expect(parseClientMessage('{"type":"sub","topics":["sessions","settings"]}')).toEqual({ type: 'sub', topics: ['sessions', 'settings'] });
|
||||||
|
expect(parseClientMessage('{"type":"sub","topics":["bogus"]}')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('watch / unwatch (P7) avec repoId + path', () => {
|
||||||
|
expect(parseClientMessage('{"type":"watch","repoId":"r1","path":"/home/u/wt"}')).toEqual({ type: 'watch', repoId: 'r1', path: '/home/u/wt' });
|
||||||
|
expect(parseClientMessage('{"type":"unwatch","repoId":"r1","path":"/home/u/wt"}')).toEqual({ type: 'unwatch', repoId: 'r1', path: '/home/u/wt' });
|
||||||
|
});
|
||||||
|
|
||||||
it('ping (champs superflus ignorés)', () => {
|
it('ping (champs superflus ignorés)', () => {
|
||||||
expect(parseClientMessage('{"type":"ping","extra":42}')).toEqual({ type: 'ping' });
|
expect(parseClientMessage('{"type":"ping","extra":42}')).toEqual({ type: 'ping' });
|
||||||
});
|
});
|
||||||
@@ -152,6 +163,13 @@ describe('parseClientMessage — cas malformés', () => {
|
|||||||
expect(parseClientMessage('{"type":"hello","protocol":"1"}')).toBeNull();
|
expect(parseClientMessage('{"type":"hello","protocol":"1"}')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('watch / unwatch : repoId ou path manquant / mal typé', () => {
|
||||||
|
expect(parseClientMessage('{"type":"watch","path":"/x"}')).toBeNull();
|
||||||
|
expect(parseClientMessage('{"type":"watch","repoId":"r1"}')).toBeNull();
|
||||||
|
expect(parseClientMessage('{"type":"watch","repoId":"","path":"/x"}')).toBeNull();
|
||||||
|
expect(parseClientMessage('{"type":"unwatch","repoId":"r1","path":42}')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('attach : dimensions hors bornes ou non entières', () => {
|
it('attach : dimensions hors bornes ou non entières', () => {
|
||||||
const make = (over: Record<string, unknown>): string =>
|
const make = (over: Record<string, unknown>): string =>
|
||||||
JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 80, rows: 24, ...over });
|
JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 80, rows: 24, ...over });
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
<title>Arboretum — Mission control for your AI coding agents</title>
|
<title>Arboretum — Mission control for your AI coding agents</title>
|
||||||
<meta
|
<meta
|
||||||
name="description"
|
name="description"
|
||||||
content="Arboretum is a local-first daemon you launch with npx that serves a web dashboard to run and supervise many Claude Code sessions across git worktrees — from any device, even your phone."
|
content="Arboretum is a local-first daemon you launch with npx that serves a web IDE to run and supervise many Claude Code sessions across git worktrees — edit files, diff, stage and commit, connect git services, all from any device, even your phone."
|
||||||
/>
|
/>
|
||||||
<link rel="canonical" href="https://git-arboretum.com/" />
|
<link rel="canonical" href="https://git-arboretum.com/" />
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
<meta property="og:title" content="Arboretum — Mission control for your AI coding agents" />
|
<meta property="og:title" content="Arboretum — Mission control for your AI coding agents" />
|
||||||
<meta
|
<meta
|
||||||
property="og:description"
|
property="og:description"
|
||||||
content="Run and supervise many Claude Code sessions across every git worktree — from any device, even your phone."
|
content="Run and supervise many Claude Code sessions across every git worktree — a browser IDE to edit, diff, commit and clone, from any device, even your phone."
|
||||||
/>
|
/>
|
||||||
<meta property="og:site_name" content="Arboretum" />
|
<meta property="og:site_name" content="Arboretum" />
|
||||||
<meta property="og:image" content="https://git-arboretum.com/assets/og-cover.png" />
|
<meta property="og:image" content="https://git-arboretum.com/assets/og-cover.png" />
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
<meta name="twitter:title" content="Arboretum — Mission control for your AI coding agents" />
|
<meta name="twitter:title" content="Arboretum — Mission control for your AI coding agents" />
|
||||||
<meta
|
<meta
|
||||||
name="twitter:description"
|
name="twitter:description"
|
||||||
content="Run and supervise many Claude Code sessions across every git worktree — from any device, even your phone."
|
content="Run and supervise many Claude Code sessions across every git worktree — a browser IDE to edit, diff, commit and clone, from any device, even your phone."
|
||||||
/>
|
/>
|
||||||
<meta name="twitter:image" content="https://git-arboretum.com/assets/og-cover.png" />
|
<meta name="twitter:image" content="https://git-arboretum.com/assets/og-cover.png" />
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@arboretum/site",
|
"name": "@arboretum/site",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.0",
|
"version": "0.2.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import HeroSection from './components/HeroSection.vue';
|
|||||||
import ProblemSection from './components/ProblemSection.vue';
|
import ProblemSection from './components/ProblemSection.vue';
|
||||||
import FeaturesSection from './components/FeaturesSection.vue';
|
import FeaturesSection from './components/FeaturesSection.vue';
|
||||||
import ShowcaseSection from './components/ShowcaseSection.vue';
|
import ShowcaseSection from './components/ShowcaseSection.vue';
|
||||||
|
import WorkspaceShowcase from './components/WorkspaceShowcase.vue';
|
||||||
|
import RemoteGitSection from './components/RemoteGitSection.vue';
|
||||||
import WorkGroupsSection from './components/WorkGroupsSection.vue';
|
import WorkGroupsSection from './components/WorkGroupsSection.vue';
|
||||||
import HowItWorksSection from './components/HowItWorksSection.vue';
|
import HowItWorksSection from './components/HowItWorksSection.vue';
|
||||||
import SecuritySection from './components/SecuritySection.vue';
|
import SecuritySection from './components/SecuritySection.vue';
|
||||||
@@ -62,6 +64,8 @@ const glowStyle = {
|
|||||||
<ProblemSection />
|
<ProblemSection />
|
||||||
<FeaturesSection />
|
<FeaturesSection />
|
||||||
<ShowcaseSection />
|
<ShowcaseSection />
|
||||||
|
<WorkspaceShowcase />
|
||||||
|
<RemoteGitSection />
|
||||||
<WorkGroupsSection />
|
<WorkGroupsSection />
|
||||||
<HowItWorksSection />
|
<HowItWorksSection />
|
||||||
<SecuritySection />
|
<SecuritySection />
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ const { t } = useI18n();
|
|||||||
|
|
||||||
const navLinks = [
|
const navLinks = [
|
||||||
{ href: '#features', key: 'navFeatures' },
|
{ href: '#features', key: 'navFeatures' },
|
||||||
|
{ href: '#workspace', key: 'navWorkspace' },
|
||||||
{ href: '#how', key: 'navHow' },
|
{ href: '#how', key: 'navHow' },
|
||||||
{ href: '#security', key: 'navSecurity' },
|
{ href: '#security', key: 'navSecurity' },
|
||||||
{ href: '#faq', key: 'navFaq' },
|
{ href: '#faq', key: 'navFaq' },
|
||||||
|
|||||||
@@ -71,6 +71,55 @@ const { t } = useI18n();
|
|||||||
</template>
|
</template>
|
||||||
{{ t('feat8Desc') }}
|
{{ t('feat8Desc') }}
|
||||||
</FeatureCard>
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat9Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat9Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat10Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 10v6" /><path d="M9 13h6" /><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat10Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat11Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="18" x="3" y="3" rx="2" /><path d="m9 9-2 3 2 3" /><path d="m13 9 2 3-2 3" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat11Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat12Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="18" r="3" /><circle cx="6" cy="6" r="3" /><path d="M13 6h3a2 2 0 0 1 2 2v7" /><path d="M11 18H8a2 2 0 0 1-2-2V9" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat12Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat13Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 2v6" /><path d="M15 2v6" /><path d="M12 17v5" /><path d="M5 8h14" /><path d="M6 11V8h12v3a6 6 0 0 1-12 0Z" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat13Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat14Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="20" height="5" x="2" y="3" rx="1" /><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" /><path d="M10 12h4" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat14Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
|
|
||||||
|
<FeatureCard :title="t('feat15Title')">
|
||||||
|
<template #icon>
|
||||||
|
<svg width="21" height="21" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" /><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" /><path d="M3 21v-5h5" /></svg>
|
||||||
|
</template>
|
||||||
|
{{ t('feat15Desc') }}
|
||||||
|
</FeatureCard>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
83
packages/site/src/components/RemoteGitSection.vue
Normal file
83
packages/site/src/components/RemoteGitSection.vue
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
// Connexions (fidèle à GitConnectionsSection : badge service + label + username + ••••last4 + badge tested).
|
||||||
|
const connections = [
|
||||||
|
{ service: 'gitea', label: 'lidge', username: 'johanleroy', last4: 'a4f1' },
|
||||||
|
{ service: 'github', label: 'work', username: 'jleroy', last4: '9c0e' },
|
||||||
|
{ service: 'gitlab', label: 'oss', username: 'johan', last4: '2db7' },
|
||||||
|
] as const;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="remotegit" class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 pb-[100px]">
|
||||||
|
<div v-reveal class="flex flex-wrap items-center gap-12">
|
||||||
|
<div class="min-w-[280px] flex-[1_1_360px]">
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-emerald-400">{{ t('rgKicker') }}</div>
|
||||||
|
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,34px)] font-semibold leading-[1.15] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('rgTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="m-0 text-[16.5px] leading-[1.6] text-zinc-400">{{ t('rgBody') }}</p>
|
||||||
|
<div class="mt-4 inline-flex items-center gap-2 rounded-lg border border-emerald-500/30 bg-emerald-500/[0.08] px-3 py-1.5 text-[13px] font-medium text-emerald-300">
|
||||||
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="11" x="3" y="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>
|
||||||
|
{{ t('rgEncrypted') }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex min-w-[280px] flex-[1_1_440px] flex-col gap-3">
|
||||||
|
<!-- carte connexions (fidèle à GitConnectionsSection) -->
|
||||||
|
<div class="flex flex-col gap-2 rounded-xl border border-zinc-800 bg-zinc-900/50 p-3 shadow-card">
|
||||||
|
<h3 class="flex items-center gap-2 text-sm font-semibold text-zinc-100">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 2v6" /><path d="M15 2v6" /><path d="M12 17v5" /><path d="M5 8h14" /><path d="M6 11V8h12v3a6 6 0 0 1-12 0Z" /></svg>
|
||||||
|
{{ t('rgConnections') }}
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<ul class="flex flex-col gap-1">
|
||||||
|
<li
|
||||||
|
v-for="c in connections"
|
||||||
|
:key="c.label"
|
||||||
|
class="flex flex-wrap items-center gap-2 rounded-lg border border-zinc-800 bg-zinc-900/40 px-2.5 py-2"
|
||||||
|
>
|
||||||
|
<!-- icône service (Gitea / GitHub / GitLab) -->
|
||||||
|
<span class="inline-flex h-6 w-6 flex-none items-center justify-center rounded-md bg-zinc-800 text-zinc-300">
|
||||||
|
<svg v-if="c.service === 'github'" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 1.3a10.7 10.7 0 0 0-3.38 20.86c.53.1.73-.23.73-.51l-.01-1.79c-2.98.65-3.61-1.44-3.61-1.44-.49-1.24-1.19-1.57-1.19-1.57-.97-.66.07-.65.07-.65 1.08.08 1.64 1.11 1.64 1.11.96 1.64 2.51 1.16 3.12.89.1-.69.37-1.16.68-1.43-2.38-.27-4.88-1.19-4.88-5.3 0-1.17.42-2.13 1.1-2.88-.11-.27-.48-1.36.1-2.84 0 0 .9-.29 2.96 1.1a10.3 10.3 0 0 1 5.38 0c2.05-1.39 2.95-1.1 2.95-1.1.59 1.48.22 2.57.11 2.84.69.75 1.1 1.71 1.1 2.88 0 4.12-2.51 5.02-4.9 5.29.39.33.73.98.73 1.97l-.01 2.92c0 .29.2.62.74.51A10.7 10.7 0 0 0 12 1.3" /></svg>
|
||||||
|
<svg v-else-if="c.service === 'gitlab'" width="15" height="15" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="m12 21.42 3.68-11.33H8.32L12 21.42Z" /><path d="M12 21.42 8.32 10.09H3.16L12 21.42Z" /><path d="M3.16 10.09 2.04 13.53a.76.76 0 0 0 .28.85L12 21.42 3.16 10.09Z" /><path d="M3.16 10.09h5.16L6.1 3.26a.38.38 0 0 0-.72 0l-2.22 6.83Z" /><path d="M12 21.42l3.68-11.33h5.16L12 21.42Z" /><path d="m20.84 10.09 1.12 3.44a.76.76 0 0 1-.28.85L12 21.42l8.84-11.33Z" /><path d="M20.84 10.09h-5.16l2.22-6.83a.38.38 0 0 1 .72 0l2.22 6.83Z" /></svg>
|
||||||
|
<svg v-else width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 10h12v4a4 4 0 0 1-4 4H8a4 4 0 0 1-4-4z" /><path d="M16 11h2.5a2.5 2.5 0 0 1 0 5H16" /><path d="M7 3c-.5.8.5 1.6 0 2.5" /><path d="M11 3c-.5.8.5 1.6 0 2.5" /></svg>
|
||||||
|
</span>
|
||||||
|
<span class="inline-flex items-center rounded bg-sky-950 px-1.5 py-0.5 text-[11px] font-medium text-sky-300">{{ c.service }}</span>
|
||||||
|
<span class="font-medium text-zinc-200">{{ c.label }}</span>
|
||||||
|
<span class="text-xs text-zinc-500">{{ c.username }}</span>
|
||||||
|
<span class="font-mono text-xs text-zinc-600">••••{{ c.last4 }}</span>
|
||||||
|
<span class="ml-auto inline-flex items-center gap-1 rounded bg-emerald-950 px-1.5 py-0.5 text-[11px] font-medium text-emerald-400">
|
||||||
|
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5" /></svg>
|
||||||
|
{{ t('rgTested') }}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-1.5 text-xs font-medium text-zinc-200">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14" /><path d="M12 5v14" /></svg>
|
||||||
|
{{ t('rgAddConnection') }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- progression de clone (fidèle à CloneRepoModal) -->
|
||||||
|
<div class="flex flex-col gap-2 rounded-xl border border-zinc-800 bg-zinc-900/50 p-3 shadow-card">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="7 10 12 15 17 10" /><line x1="12" x2="12" y1="15" y2="3" /></svg>
|
||||||
|
<span class="font-mono text-[13px] text-zinc-200">github.com/jleroy/api</span>
|
||||||
|
<span class="ml-auto font-mono text-xs text-zinc-500">62%</span>
|
||||||
|
</div>
|
||||||
|
<div class="h-2 w-full overflow-hidden rounded bg-zinc-800">
|
||||||
|
<div class="h-full rounded bg-emerald-500" style="width: 62%"></div>
|
||||||
|
</div>
|
||||||
|
<span class="font-mono text-xs text-zinc-500">{{ t('rgCloneReceiving') }}… 62%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
@@ -41,6 +41,11 @@ const { t } = useI18n();
|
|||||||
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec4Title') }}</div>
|
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec4Title') }}</div>
|
||||||
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec4Desc') }}</div>
|
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec4Desc') }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex flex-col gap-2.5 rounded-[11px] border border-zinc-800 bg-[#0c0c0e] p-[18px]">
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="11" x="3" y="11" rx="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /><path d="M12 16v-2" /></svg>
|
||||||
|
<div class="text-[15px] font-semibold text-zinc-50">{{ t('sec5Title') }}</div>
|
||||||
|
<div class="text-[13.5px] leading-[1.5] text-zinc-400">{{ t('sec5Desc') }}</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -96,6 +96,11 @@ const dlgOpts = computed(() => DLG_OPTS[locale.value as AppLocale]);
|
|||||||
<span class="font-mono text-[11px] text-zinc-400">claude</span>
|
<span class="font-mono text-[11px] text-zinc-400">claude</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- actions git de la carte : commit / push (fidèle au WorktreeCard) -->
|
||||||
|
<div class="mt-1 flex items-center gap-1.5">
|
||||||
|
<span class="inline-flex items-center rounded border border-zinc-700 bg-zinc-800 px-1.5 py-0.5 text-[11px] font-medium text-zinc-300">{{ t('mCommit') }}</span>
|
||||||
|
<span class="inline-flex items-center rounded border border-zinc-700 bg-zinc-800 px-1.5 py-0.5 text-[11px] font-medium text-zinc-300">{{ t('mPush') }} ↑2</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
231
packages/site/src/components/WorkspaceShowcase.vue
Normal file
231
packages/site/src/components/WorkspaceShowcase.vue
Normal file
@@ -0,0 +1,231 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
// Lignes du diff (fidèle à DiffViewer : add → emerald-950/40, del → rose-950/40).
|
||||||
|
type DiffLine = { o: string; n: string; type: 'ctx' | 'add' | 'del' | 'hunk'; text: string };
|
||||||
|
const diffLines: DiffLine[] = [
|
||||||
|
{ o: '', n: '', type: 'hunk', text: '@@ -12,7 +12,9 @@ export function session(' },
|
||||||
|
{ o: '12', n: '12', type: 'ctx', text: ' const claims = verify(req);' },
|
||||||
|
{ o: '13', n: '13', type: 'ctx', text: ' if (!claims) return null;' },
|
||||||
|
{ o: '14', n: '', type: 'del', text: ' return signLegacyCookie(claims);' },
|
||||||
|
{ o: '', n: '14', type: 'add', text: ' const token = sign(claims, { ttl: 900 });' },
|
||||||
|
{ o: '', n: '15', type: 'add', text: ' return refreshable(token);' },
|
||||||
|
{ o: '15', n: '16', type: 'ctx', text: '}' },
|
||||||
|
];
|
||||||
|
|
||||||
|
function rowClass(type: DiffLine['type']): string {
|
||||||
|
if (type === 'add') return 'bg-emerald-950/40 text-emerald-200';
|
||||||
|
if (type === 'del') return 'bg-rose-950/40 text-rose-200';
|
||||||
|
return 'text-zinc-300';
|
||||||
|
}
|
||||||
|
function marker(type: DiffLine['type']): string {
|
||||||
|
return type === 'add' ? '+' : type === 'del' ? '-' : ' ';
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section id="workspace" class="mx-auto max-w-[1200px] scroll-mt-[84px] px-6 pb-[100px]">
|
||||||
|
<div v-reveal class="mb-[40px] max-w-[720px]">
|
||||||
|
<div class="mb-3 font-mono text-xs uppercase tracking-[0.12em] text-emerald-400">{{ t('wsKicker') }}</div>
|
||||||
|
<h2 class="m-0 mb-4 text-[clamp(26px,3vw,38px)] font-semibold leading-[1.15] tracking-[-0.025em] text-zinc-50">
|
||||||
|
{{ t('wsTitle') }}
|
||||||
|
</h2>
|
||||||
|
<p class="m-0 text-[16.5px] leading-[1.6] text-zinc-400">{{ t('wsBody') }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- maquette IDE : fidèle à WorkspaceView (/workspace) -->
|
||||||
|
<div v-reveal class="overflow-hidden rounded-[14px] border border-zinc-800 bg-[#09090b] shadow-card">
|
||||||
|
<!-- en-tête IDE : retour · repo · badge git · SegmentedControl Editor/Diff -->
|
||||||
|
<header class="flex flex-wrap items-center gap-3 border-b border-zinc-800 px-3 py-2">
|
||||||
|
<span class="inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-zinc-400">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6" /></svg>
|
||||||
|
{{ t('mWorktrees') }}
|
||||||
|
</span>
|
||||||
|
<span class="truncate text-sm font-medium text-zinc-200">api</span>
|
||||||
|
<!-- badge git (fidèle à GitStatusBadge) -->
|
||||||
|
<span class="flex items-center gap-2 text-xs">
|
||||||
|
<span class="flex items-center gap-1 font-mono text-zinc-300">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="6" x2="6" y1="3" y2="15" /><circle cx="18" cy="6" r="3" /><circle cx="6" cy="18" r="3" /><path d="M18 9a9 9 0 0 1-9 9" /></svg>
|
||||||
|
feat/auth
|
||||||
|
</span>
|
||||||
|
<span class="text-emerald-400">↑2</span>
|
||||||
|
<span class="text-amber-400">○3</span>
|
||||||
|
</span>
|
||||||
|
<!-- SegmentedControl Editor/Diff (fidèle à SegmentedControl) -->
|
||||||
|
<div class="ml-auto inline-flex rounded-lg border border-zinc-800 bg-zinc-950/40 p-0.5">
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium text-zinc-400">{{ t('wsEditor') }}</span>
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-md bg-zinc-800 px-2.5 py-1 text-xs font-medium text-zinc-100">{{ t('wsDiff') }}</span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- corps : 3 colonnes (desktop) / empilé (mobile) -->
|
||||||
|
<div class="flex flex-col md:flex-row">
|
||||||
|
<!-- colonne gauche : arbre de fichiers + panneau commit -->
|
||||||
|
<aside class="flex min-w-0 flex-col border-b border-zinc-800 md:w-[262px] md:flex-none md:border-b-0 md:border-r">
|
||||||
|
<!-- arbre de fichiers (fidèle à FileTree / FileTreeNode) -->
|
||||||
|
<div class="flex flex-col">
|
||||||
|
<div class="flex items-center gap-1 px-2 py-1.5 text-[11px] font-semibold uppercase tracking-wide text-zinc-500">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 14 3h-3a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z" /><path d="M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H11a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z" /><path d="M3 5a2 2 0 0 0 2 2h3" /><path d="M3 3v13a2 2 0 0 0 2 2h3" /></svg>
|
||||||
|
{{ t('wsFiles') }}
|
||||||
|
</div>
|
||||||
|
<div class="px-1 pb-2 font-mono text-xs">
|
||||||
|
<!-- src/ (dossier ouvert) -->
|
||||||
|
<div class="flex items-center gap-1 rounded py-0.5 pl-[6px] pr-2 text-zinc-300">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-zinc-500" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg>
|
||||||
|
<span class="truncate">src</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-1 rounded py-0.5 pl-[18px] pr-2 text-zinc-300">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-zinc-500" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
|
||||||
|
<span class="truncate">core</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between gap-1 rounded bg-zinc-800 py-0.5 pl-[30px] pr-2 text-zinc-100">
|
||||||
|
<span class="flex min-w-0 items-center gap-1">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-zinc-500" aria-hidden="true"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /><path d="M14 2v4a2 2 0 0 0 2 2h4" /></svg>
|
||||||
|
<span class="truncate">session.ts</span>
|
||||||
|
</span>
|
||||||
|
<span class="shrink-0 font-bold text-amber-400">M</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center justify-between gap-1 rounded py-0.5 pl-[30px] pr-2 text-zinc-300">
|
||||||
|
<span class="flex min-w-0 items-center gap-1">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-zinc-500" aria-hidden="true"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /><path d="M14 2v4a2 2 0 0 0 2 2h4" /></svg>
|
||||||
|
<span class="truncate">token.ts</span>
|
||||||
|
</span>
|
||||||
|
<span class="shrink-0 font-bold text-emerald-400">A</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-1 rounded py-0.5 pl-[18px] pr-2 text-zinc-300">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-zinc-500" aria-hidden="true"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /><path d="M14 2v4a2 2 0 0 0 2 2h4" /></svg>
|
||||||
|
<span class="truncate">app.ts</span>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-1 rounded py-0.5 pl-[6px] pr-2 text-zinc-300">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="shrink-0 text-zinc-500" aria-hidden="true"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z" /><path d="M14 2v4a2 2 0 0 0 2 2h4" /></svg>
|
||||||
|
<span class="truncate">package.json</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- panneau commit (fidèle à CommitPanel) -->
|
||||||
|
<div class="flex flex-col border-t border-zinc-800">
|
||||||
|
<div class="flex items-center gap-1 px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-zinc-500">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="18" cy="18" r="3" /><circle cx="6" cy="6" r="3" /><path d="M13 6h3a2 2 0 0 1 2 2v7" /><path d="M11 18H8a2 2 0 0 1-2-2V9" /></svg>
|
||||||
|
{{ t('wsChanges') }}
|
||||||
|
<span class="text-emerald-500">↑2</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Staged (1) -->
|
||||||
|
<div class="px-1">
|
||||||
|
<div class="flex items-center px-1 py-0.5 text-[11px] text-zinc-500">{{ t('wsStaged') }} (1)</div>
|
||||||
|
<div class="group flex items-center gap-2 rounded bg-zinc-800 px-2 py-0.5 text-xs text-zinc-100">
|
||||||
|
<span class="flex min-w-0 flex-1 items-center gap-2">
|
||||||
|
<span class="w-3 shrink-0 text-center font-mono font-bold text-emerald-400">A</span>
|
||||||
|
<span class="min-w-0 flex-1 truncate font-mono">token.ts<span class="text-zinc-600"> src/core</span></span>
|
||||||
|
<span class="shrink-0 text-emerald-500">+24</span>
|
||||||
|
</span>
|
||||||
|
<button type="button" class="shrink-0 rounded p-0.5 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200" :title="t('wsUnstage')" :aria-label="t('wsUnstage')">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14" /></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Changes (1) -->
|
||||||
|
<div class="px-1 pb-1">
|
||||||
|
<div class="flex items-center px-1 py-0.5 text-[11px] text-zinc-500">{{ t('wsChanges') }} (1)</div>
|
||||||
|
<div class="group flex items-center gap-2 rounded px-2 py-0.5 text-xs text-zinc-300 hover:bg-zinc-800/60">
|
||||||
|
<span class="flex min-w-0 flex-1 items-center gap-2">
|
||||||
|
<span class="w-3 shrink-0 text-center font-mono font-bold text-amber-400">M</span>
|
||||||
|
<span class="min-w-0 flex-1 truncate font-mono">session.ts<span class="text-zinc-600"> src/core</span></span>
|
||||||
|
<span class="shrink-0 text-emerald-500">+2</span>
|
||||||
|
<span class="shrink-0 text-rose-500">−1</span>
|
||||||
|
</span>
|
||||||
|
<span class="flex shrink-0 items-center gap-0.5 text-zinc-400">
|
||||||
|
<button type="button" class="rounded p-0.5 hover:bg-zinc-700" :title="t('wsDiscard')" :aria-label="t('wsDiscard')">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14 4 9l5-5" /><path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5v0a5.5 5.5 0 0 1-5.5 5.5H11" /></svg>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="rounded p-0.5 hover:bg-zinc-700" :title="t('wsStage')" :aria-label="t('wsStage')">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14" /><path d="M12 5v14" /></svg>
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- zone de commit -->
|
||||||
|
<div class="flex flex-col gap-1 border-t border-zinc-800 p-2">
|
||||||
|
<div class="resize-none rounded-md border border-zinc-700 bg-zinc-950/40 px-2 py-1.5 text-xs text-zinc-200">{{ t('wsCommitMsg') }}</div>
|
||||||
|
<label class="flex items-center gap-1.5 text-[11px] text-zinc-400">
|
||||||
|
<span class="inline-flex h-3.5 w-3.5 items-center justify-center rounded-[3px] border border-zinc-600 bg-zinc-950"></span>
|
||||||
|
{{ t('wsAmend') }}
|
||||||
|
</label>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-md bg-emerald-500 px-2.5 py-1 text-xs font-semibold text-emerald-950">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5" /></svg>
|
||||||
|
{{ t('wsCommitBtn') }}
|
||||||
|
</span>
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-md border border-zinc-700 bg-zinc-800 px-2.5 py-1 text-xs font-medium text-zinc-200">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3v12" /><path d="m17 8-5-5-5 5" /><path d="M5 21h14" /></svg>
|
||||||
|
{{ t('wsPushBtn') }} ↑2
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<!-- colonne centrale : diff (fidèle à DiffViewer) -->
|
||||||
|
<main class="flex min-w-0 flex-1 flex-col border-b border-zinc-800 md:border-b-0">
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-2 py-1">
|
||||||
|
<div class="inline-flex rounded-lg border border-zinc-800 bg-zinc-950/40 p-0.5">
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-md px-2.5 py-1 text-xs font-medium text-zinc-400">{{ t('wsEditor') }}</span>
|
||||||
|
<span class="inline-flex items-center gap-1.5 rounded-md bg-zinc-800 px-2.5 py-1 text-xs font-medium text-zinc-100">{{ t('wsDiff') }}</span>
|
||||||
|
</div>
|
||||||
|
<span class="truncate font-mono text-[11px] text-zinc-500">src/core/session.ts</span>
|
||||||
|
</div>
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto">
|
||||||
|
<div class="flex items-center gap-3 border-b border-zinc-800 px-3 py-1 text-[11px] text-zinc-500">
|
||||||
|
<span class="text-emerald-500">+2</span>
|
||||||
|
<span class="text-rose-500">−1</span>
|
||||||
|
<span class="rounded bg-emerald-950 px-1 text-emerald-400">{{ t('wsStaged') }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="overflow-x-auto">
|
||||||
|
<table class="w-full border-collapse font-mono text-xs leading-5">
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="(l, i) in diffLines" :key="i" :class="l.type === 'hunk' ? 'bg-zinc-900/60 text-sky-300/80' : rowClass(l.type)">
|
||||||
|
<td class="w-10 select-none px-2 text-right text-zinc-600">{{ l.o }}</td>
|
||||||
|
<td class="w-10 select-none px-2 text-right text-zinc-600">{{ l.n }}</td>
|
||||||
|
<td class="whitespace-pre px-2">{{ l.type === 'hunk' ? l.text : marker(l.type) + l.text }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<!-- colonne droite : terminal de la session corrélée (fidèle au style des terminaux du site) -->
|
||||||
|
<section class="flex min-w-0 flex-col md:w-[300px] md:flex-none md:border-l md:border-zinc-800">
|
||||||
|
<div class="flex items-center gap-1 border-b border-zinc-800 px-2 py-1 text-[11px] font-semibold uppercase tracking-wide text-zinc-500">
|
||||||
|
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m7 11 2-2-2-2" /><path d="M11 13h4" /><rect width="18" height="18" x="3" y="3" rx="2" ry="2" /></svg>
|
||||||
|
{{ t('wsTerminal') }}
|
||||||
|
</div>
|
||||||
|
<!-- barre de titre repo · branche + badge d'état -->
|
||||||
|
<div class="flex items-center gap-2 border-b border-zinc-800 px-[11px] py-2">
|
||||||
|
<span class="truncate font-mono text-[11.5px] text-zinc-300">api · feat/auth</span>
|
||||||
|
<span class="ml-auto inline-flex items-center gap-1.5 rounded bg-sky-950 px-2 py-[3px] font-mono text-[11px] text-sky-300">
|
||||||
|
<span class="h-1.5 w-1.5 flex-none animate-pulse-sky rounded-full bg-sky-300"></span>{{ t('busy') }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="min-h-[180px] flex-1 p-[11px] font-mono text-[11px] leading-[1.75] text-zinc-300">
|
||||||
|
<div class="text-emerald-400">● Edit session.ts</div>
|
||||||
|
<div class="text-emerald-400">+ const token = sign(...)</div>
|
||||||
|
<div class="text-red-400">- legacy cookie auth</div>
|
||||||
|
<div class="text-emerald-400">● Write token.ts</div>
|
||||||
|
<div class="text-zinc-500">running tests…</div>
|
||||||
|
<div class="text-emerald-400">✓ 24 passed</div>
|
||||||
|
<div>
|
||||||
|
<span class="text-emerald-400">$</span>
|
||||||
|
<span class="ml-1 inline-block h-[11px] w-1.5 animate-blink align-middle bg-zinc-200"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
@@ -11,7 +11,7 @@ export const FAQS: Record<AppLocale, FaqItem[]> = {
|
|||||||
en: [
|
en: [
|
||||||
{
|
{
|
||||||
q: 'How is this different from running Claude Code in a terminal?',
|
q: 'How is this different from running Claude Code in a terminal?',
|
||||||
a: 'It runs the very same interactive claude CLI — Arboretum just wraps it in a managed terminal you reach from a browser. What you gain on top: a worktree-first dashboard across all your repos, live busy / waiting / idle states, a multi-terminal grid, push notifications, and the ability to answer a prompt from your phone. It supervises your sessions; it does not change how Claude Code works.',
|
a: 'It runs the very same interactive claude CLI — Arboretum just wraps it in a managed terminal you reach from a browser. What you gain on top: a worktree-first dashboard across all your repos, live busy / waiting / available states, a multi-terminal grid, push notifications, and the ability to answer a prompt from your phone. It supervises your sessions; it does not change how Claude Code works.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
q: 'Does it need the cloud?',
|
q: 'Does it need the cloud?',
|
||||||
@@ -29,11 +29,23 @@ export const FAQS: Record<AppLocale, FaqItem[]> = {
|
|||||||
q: 'Is my code safe?',
|
q: 'Is my code safe?',
|
||||||
a: 'Arboretum binds to localhost, hashes access tokens at rest, and enforces strict origin checks on every request. Remote access runs through Tailscale rather than an open port.',
|
a: 'Arboretum binds to localhost, hashes access tokens at rest, and enforces strict origin checks on every request. Remote access runs through Tailscale rather than an open port.',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
q: 'Can I edit files directly?',
|
||||||
|
a: 'Yes. The /workspace view is a real IDE: a file tree, a full Monaco editor with inline diffs, and the correlated session terminal. Stage changes file by file, write a commit message, amend, then push — all from the browser, on any device.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Can I connect GitHub, GitLab or Gitea and clone?',
|
||||||
|
a: 'Yes. Add a connection with a personal access token or app password — credentials are encrypted at rest (AES-256-GCM) and never returned in clear by the API. Then browse remote repos and clone over HTTPS with live progress.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'What happens to old sessions?',
|
||||||
|
a: 'Finished sessions are archived automatically after a configurable retention window (30 days by default), so the dashboard stays focused on what is live without losing your history.',
|
||||||
|
},
|
||||||
],
|
],
|
||||||
fr: [
|
fr: [
|
||||||
{
|
{
|
||||||
q: 'En quoi est-ce différent de lancer Claude Code dans un terminal ?',
|
q: 'En quoi est-ce différent de lancer Claude Code dans un terminal ?',
|
||||||
a: "C'est exactement le même CLI claude interactif — Arboretum l'enveloppe simplement dans un terminal managé accessible depuis un navigateur. Ce que vous gagnez en plus : un dashboard worktree-first sur tous vos repos, les états occupée / en attente / inactive en direct, une grille multi-terminaux, des notifications push, et la possibilité de répondre à une question depuis votre téléphone. Il supervise vos sessions ; il ne change rien au fonctionnement de Claude Code.",
|
a: "C'est exactement le même CLI claude interactif — Arboretum l'enveloppe simplement dans un terminal managé accessible depuis un navigateur. Ce que vous gagnez en plus : un dashboard worktree-first sur tous vos repos, les états occupée / en attente / disponible en direct, une grille multi-terminaux, des notifications push, et la possibilité de répondre à une question depuis votre téléphone. Il supervise vos sessions ; il ne change rien au fonctionnement de Claude Code.",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
q: 'A-t-il besoin du cloud ?',
|
q: 'A-t-il besoin du cloud ?',
|
||||||
@@ -51,6 +63,18 @@ export const FAQS: Record<AppLocale, FaqItem[]> = {
|
|||||||
q: 'Mon code est-il en sécurité ?',
|
q: 'Mon code est-il en sécurité ?',
|
||||||
a: "Arboretum se lie à localhost, hashe les tokens au repos, et applique une vérification d'origine stricte sur chaque requête. L'accès distant passe par Tailscale plutôt qu'un port ouvert.",
|
a: "Arboretum se lie à localhost, hashe les tokens au repos, et applique une vérification d'origine stricte sur chaque requête. L'accès distant passe par Tailscale plutôt qu'un port ouvert.",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
q: 'Puis-je éditer les fichiers directement ?',
|
||||||
|
a: "Oui. La vue /workspace est un vrai IDE : un arbre de fichiers, un éditeur Monaco complet avec les diffs inline, et le terminal de la session corrélée. Indexez les changements fichier par fichier, rédigez un message de commit, amendez, puis poussez — le tout depuis le navigateur, sur n'importe quel appareil.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: 'Puis-je connecter GitHub, GitLab ou Gitea et cloner ?',
|
||||||
|
a: "Oui. Ajoutez une connexion avec un token d'accès personnel ou un app password — les identifiants sont chiffrés au repos (AES-256-GCM) et jamais renvoyés en clair par l'API. Parcourez ensuite les repos distants et clonez en HTTPS avec progression en direct.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
q: "Qu'advient-il des anciennes sessions ?",
|
||||||
|
a: 'Les sessions terminées sont archivées automatiquement après une rétention configurable (30 jours par défaut), pour que le dashboard reste centré sur ce qui est en cours sans perdre votre historique.',
|
||||||
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Messages EN — copie fidèle du dict() du design Arboretum.dc.html.
|
// Messages EN — copie fidèle du dict() du design Arboretum.dc.html.
|
||||||
export default {
|
export default {
|
||||||
navFeatures: 'Features',
|
navFeatures: 'Features',
|
||||||
|
navWorkspace: 'Workspace',
|
||||||
navHow: 'How it works',
|
navHow: 'How it works',
|
||||||
navSecurity: 'Security',
|
navSecurity: 'Security',
|
||||||
navFaq: 'FAQ',
|
navFaq: 'FAQ',
|
||||||
@@ -17,7 +18,7 @@ export default {
|
|||||||
featKicker: 'Everything in one view',
|
featKicker: 'Everything in one view',
|
||||||
featTitle: 'Built to supervise agents working in parallel',
|
featTitle: 'Built to supervise agents working in parallel',
|
||||||
feat1Title: 'Worktree-first',
|
feat1Title: 'Worktree-first',
|
||||||
feat1Desc: 'Work on your main branch or spin up an isolated worktree — every session stays pinned to a branch. Branches, not chaos.',
|
feat1Desc: 'Work on your main branch or spin up an isolated worktree — then commit, push or promote a branch to main, without opening a terminal. Branches, not chaos.',
|
||||||
feat2Title: 'Many sessions, one view',
|
feat2Title: 'Many sessions, one view',
|
||||||
feat2Desc: 'Run parallel Claude Code agents side by side in a single live grid.',
|
feat2Desc: 'Run parallel Claude Code agents side by side in a single live grid.',
|
||||||
feat3Title: 'Fine-grained states',
|
feat3Title: 'Fine-grained states',
|
||||||
@@ -32,10 +33,14 @@ export default {
|
|||||||
feat7Desc: 'Group repos and run one Claude session across all of them at once.',
|
feat7Desc: 'Group repos and run one Claude session across all of them at once.',
|
||||||
feat8Title: 'Local-first & secure',
|
feat8Title: 'Local-first & secure',
|
||||||
feat8Desc: 'Binds to localhost, hashes tokens, remote access via Tailscale.',
|
feat8Desc: 'Binds to localhost, hashes tokens, remote access via Tailscale.',
|
||||||
|
feat9Title: 'Native VS Code extension',
|
||||||
|
feat9Desc: 'Drive worktrees and attach sessions in native terminals, right inside your editor.',
|
||||||
|
feat10Title: 'New project in one click',
|
||||||
|
feat10Desc: 'Create a project folder anywhere (optional git init) and start a Claude session in it, from any device.',
|
||||||
scAKicker: 'Worktree-first dashboard',
|
scAKicker: 'Worktree-first dashboard',
|
||||||
scATitle: 'See what needs you — before anything stalls',
|
scATitle: 'See what needs you — before anything stalls',
|
||||||
scABody:
|
scABody:
|
||||||
'A live list of every worktree and its session state. The Needs attention rail floats the agents waiting on a decision to the top, so nothing sits blocked while you are heads-down elsewhere. Hide the noisy history left by past terminal sessions so the list stays actionable.',
|
'A live list of every worktree and its session state. The Needs attention rail floats the agents waiting on a decision to the top, so nothing sits blocked while you are heads-down elsewhere. Commit, push or promote a branch to main straight from the card, and hide the noisy history left by past terminal sessions so the list stays actionable.',
|
||||||
scBKicker: 'Multi-terminal grid',
|
scBKicker: 'Multi-terminal grid',
|
||||||
scBTitle: "Every agent's output, streaming live",
|
scBTitle: "Every agent's output, streaming live",
|
||||||
scBBody:
|
scBBody:
|
||||||
@@ -86,13 +91,15 @@ export default {
|
|||||||
mAttn: 'Needs attention',
|
mAttn: 'Needs attention',
|
||||||
waiting: 'waiting',
|
waiting: 'waiting',
|
||||||
busy: 'busy',
|
busy: 'busy',
|
||||||
idle: 'idle',
|
idle: 'available',
|
||||||
mPermission: 'Permission',
|
mPermission: 'Permission',
|
||||||
mDeny: 'Deny (Esc)',
|
mDeny: 'Deny (Esc)',
|
||||||
mMain: 'main',
|
mMain: 'main',
|
||||||
mClean: 'clean',
|
mClean: 'clean',
|
||||||
mDirty: '3 changed',
|
mDirty: '3 changed',
|
||||||
mStart: 'Start work',
|
mStart: 'Start work',
|
||||||
|
mCommit: 'Commit',
|
||||||
|
mPush: 'Push',
|
||||||
toastTitle: 'Session waiting for you',
|
toastTitle: 'Session waiting for you',
|
||||||
toastBody: 'api · feat/auth needs a decision',
|
toastBody: 'api · feat/auth needs a decision',
|
||||||
dlgQ: 'Apply this change to login.ts?',
|
dlgQ: 'Apply this change to login.ts?',
|
||||||
@@ -100,4 +107,52 @@ export default {
|
|||||||
copied: 'Copied',
|
copied: 'Copied',
|
||||||
copyCommand: 'Copy command',
|
copyCommand: 'Copy command',
|
||||||
copyUrl: 'Copy URL',
|
copyUrl: 'Copy URL',
|
||||||
|
|
||||||
|
// New feature cards (P7→P12: IDE worktree)
|
||||||
|
feat11Title: 'A real IDE for every worktree',
|
||||||
|
feat11Desc: 'Browse the file tree, edit in a full Monaco editor, and read changes as inline diffs — all in the /workspace view.',
|
||||||
|
feat12Title: 'Diff & selective staging',
|
||||||
|
feat12Desc: 'Stage, unstage or discard file by file, then commit (all or staged), amend, fetch and pull — without leaving the dashboard.',
|
||||||
|
feat13Title: 'Remote git services',
|
||||||
|
feat13Desc: 'Connect GitHub, GitLab or Gitea with a PAT or app password — credentials encrypted at rest — and clone over HTTPS with live progress.',
|
||||||
|
feat14Title: 'Auto-archive sessions',
|
||||||
|
feat14Desc: 'Finished sessions are archived automatically after a configurable retention window (30 days by default), keeping the list clean.',
|
||||||
|
feat15Title: 'Real-time file sync',
|
||||||
|
feat15Desc: 'A filesystem watcher streams changes the moment a file moves on disk — diffs and status update live, no refresh needed.',
|
||||||
|
|
||||||
|
// Workspace IDE showcase
|
||||||
|
wsKicker: 'The worktree IDE',
|
||||||
|
wsTitle: 'A full IDE for every worktree, in the browser',
|
||||||
|
wsBody:
|
||||||
|
'Open any worktree in /workspace: a file tree on the left, a Monaco editor and inline diff in the center, and the correlated session terminal on the right. Stage changes file by file, write a commit message, push — all without leaving the page, on any device.',
|
||||||
|
wsEditor: 'Editor',
|
||||||
|
wsDiff: 'Diff',
|
||||||
|
wsFiles: 'Files',
|
||||||
|
wsChanges: 'Changes',
|
||||||
|
wsStaged: 'Staged',
|
||||||
|
wsTerminal: 'Terminal',
|
||||||
|
wsCommitMsg: 'Implement token refresh',
|
||||||
|
wsCommitPlaceholder: 'Commit message…',
|
||||||
|
wsAmend: 'Amend last commit',
|
||||||
|
wsCommitBtn: 'Commit',
|
||||||
|
wsPushBtn: 'Push',
|
||||||
|
wsStage: 'Stage',
|
||||||
|
wsUnstage: 'Unstage',
|
||||||
|
wsDiscard: 'Discard',
|
||||||
|
|
||||||
|
// Remote git services + clone
|
||||||
|
rgKicker: 'Remote git · encrypted',
|
||||||
|
rgTitle: 'Connect your git services and clone in a click',
|
||||||
|
rgBody:
|
||||||
|
'Add GitHub, GitLab or Gitea connections with a personal access token or app password. Secrets are encrypted at rest (AES-256-GCM) and never returned in clear by the API. Browse remote repos and clone over HTTPS with live progress.',
|
||||||
|
rgConnections: 'Connections',
|
||||||
|
rgTested: 'tested',
|
||||||
|
rgAddConnection: 'Add connection',
|
||||||
|
rgEncrypted: 'Encrypted at rest',
|
||||||
|
rgCloning: 'Cloning',
|
||||||
|
rgCloneReceiving: 'Receiving objects',
|
||||||
|
|
||||||
|
// Security pillar (encrypted secrets)
|
||||||
|
sec5Title: 'Encrypted secrets',
|
||||||
|
sec5Desc: 'Remote git credentials are encrypted at rest (AES-256-GCM) and never returned in clear by the API.',
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Messages FR — copie fidèle du dict() du design Arboretum.dc.html.
|
// Messages FR — copie fidèle du dict() du design Arboretum.dc.html.
|
||||||
export default {
|
export default {
|
||||||
navFeatures: 'Fonctionnalités',
|
navFeatures: 'Fonctionnalités',
|
||||||
|
navWorkspace: 'Workspace',
|
||||||
navHow: 'Comment ça marche',
|
navHow: 'Comment ça marche',
|
||||||
navSecurity: 'Sécurité',
|
navSecurity: 'Sécurité',
|
||||||
navFaq: 'FAQ',
|
navFaq: 'FAQ',
|
||||||
@@ -17,7 +18,7 @@ export default {
|
|||||||
featKicker: 'Tout dans une seule vue',
|
featKicker: 'Tout dans une seule vue',
|
||||||
featTitle: 'Conçu pour superviser des agents qui travaillent en parallèle',
|
featTitle: 'Conçu pour superviser des agents qui travaillent en parallèle',
|
||||||
feat1Title: "Worktree d'abord",
|
feat1Title: "Worktree d'abord",
|
||||||
feat1Desc: 'Travaillez sur votre branche principale ou créez un worktree isolé — chaque session reste rattachée à une branche. Des branches, pas du chaos.',
|
feat1Desc: 'Travaillez sur votre branche principale ou créez un worktree isolé — puis commitez, poussez ou passez une branche en principal, sans ouvrir de terminal. Des branches, pas du chaos.',
|
||||||
feat2Title: 'Plusieurs sessions, une vue',
|
feat2Title: 'Plusieurs sessions, une vue',
|
||||||
feat2Desc: 'Lancez des agents Claude Code en parallèle, côte à côte dans une seule grille en direct.',
|
feat2Desc: 'Lancez des agents Claude Code en parallèle, côte à côte dans une seule grille en direct.',
|
||||||
feat3Title: 'États fins',
|
feat3Title: 'États fins',
|
||||||
@@ -32,10 +33,14 @@ export default {
|
|||||||
feat7Desc: 'Regroupez des repos et pilotez-les via une seule session Claude, tous à la fois.',
|
feat7Desc: 'Regroupez des repos et pilotez-les via une seule session Claude, tous à la fois.',
|
||||||
feat8Title: 'Local-first & sécurisé',
|
feat8Title: 'Local-first & sécurisé',
|
||||||
feat8Desc: 'Se lie à localhost, hashe les tokens, accès distant via Tailscale.',
|
feat8Desc: 'Se lie à localhost, hashe les tokens, accès distant via Tailscale.',
|
||||||
|
feat9Title: 'Extension VS Code native',
|
||||||
|
feat9Desc: 'Pilotez vos worktrees et attachez vos sessions dans des terminaux natifs, directement dans votre éditeur.',
|
||||||
|
feat10Title: 'Nouveau projet en un clic',
|
||||||
|
feat10Desc: "Créez un dossier de projet où vous voulez (git init optionnel) et lancez-y une session Claude, depuis n'importe quel appareil.",
|
||||||
scAKicker: 'Dashboard worktree-first',
|
scAKicker: 'Dashboard worktree-first',
|
||||||
scATitle: 'Voyez ce qui vous attend — avant que ça ne bloque',
|
scATitle: 'Voyez ce qui vous attend — avant que ça ne bloque',
|
||||||
scABody:
|
scABody:
|
||||||
"Une liste en direct de chaque worktree et de l'état de sa session. Le bandeau À traiter fait remonter les agents en attente d'une décision, pour que rien ne reste bloqué pendant que vous êtes concentré ailleurs. Masquez l'historique encombrant laissé par vos anciennes sessions terminal pour garder la liste actionnable.",
|
"Une liste en direct de chaque worktree et de l'état de sa session. Le bandeau À traiter fait remonter les agents en attente d'une décision, pour que rien ne reste bloqué pendant que vous êtes concentré ailleurs. Commitez, poussez ou passez une branche en principal directement depuis la carte, et masquez l'historique encombrant laissé par vos anciennes sessions terminal pour garder la liste actionnable.",
|
||||||
scBKicker: 'Grille multi-terminaux',
|
scBKicker: 'Grille multi-terminaux',
|
||||||
scBTitle: 'La sortie de chaque agent, en direct',
|
scBTitle: 'La sortie de chaque agent, en direct',
|
||||||
scBBody:
|
scBBody:
|
||||||
@@ -86,13 +91,15 @@ export default {
|
|||||||
mAttn: 'À traiter',
|
mAttn: 'À traiter',
|
||||||
waiting: 'en attente',
|
waiting: 'en attente',
|
||||||
busy: 'occupée',
|
busy: 'occupée',
|
||||||
idle: 'inactive',
|
idle: 'disponible',
|
||||||
mPermission: 'Permission',
|
mPermission: 'Permission',
|
||||||
mDeny: 'Refuser (Échap)',
|
mDeny: 'Refuser (Échap)',
|
||||||
mMain: 'principal',
|
mMain: 'principal',
|
||||||
mClean: 'propre',
|
mClean: 'propre',
|
||||||
mDirty: '3 modifiés',
|
mDirty: '3 modifiés',
|
||||||
mStart: 'Démarrer',
|
mStart: 'Démarrer',
|
||||||
|
mCommit: 'Commit',
|
||||||
|
mPush: 'Push',
|
||||||
toastTitle: 'Une session vous attend',
|
toastTitle: 'Une session vous attend',
|
||||||
toastBody: 'api · feat/auth attend une décision',
|
toastBody: 'api · feat/auth attend une décision',
|
||||||
dlgQ: 'Appliquer ce changement à login.ts ?',
|
dlgQ: 'Appliquer ce changement à login.ts ?',
|
||||||
@@ -100,4 +107,52 @@ export default {
|
|||||||
copied: 'Copié',
|
copied: 'Copié',
|
||||||
copyCommand: 'Copier la commande',
|
copyCommand: 'Copier la commande',
|
||||||
copyUrl: "Copier l'URL",
|
copyUrl: "Copier l'URL",
|
||||||
|
|
||||||
|
// Nouvelles cartes de fonctionnalités (P7→P12 : IDE worktree)
|
||||||
|
feat11Title: 'Un vrai IDE pour chaque worktree',
|
||||||
|
feat11Desc: "Parcourez l'arbre de fichiers, éditez dans un éditeur Monaco complet, et lisez les changements en diff inline — le tout dans la vue /workspace.",
|
||||||
|
feat12Title: 'Diff & staging sélectif',
|
||||||
|
feat12Desc: 'Indexez, désindexez ou annulez fichier par fichier, puis commitez (tout ou indexé), amendez, fetchez et pullez — sans quitter le dashboard.',
|
||||||
|
feat13Title: 'Services git distants',
|
||||||
|
feat13Desc: 'Connectez GitHub, GitLab ou Gitea avec un PAT ou un app password — identifiants chiffrés au repos — et clonez en HTTPS avec progression en direct.',
|
||||||
|
feat14Title: 'Archivage auto des sessions',
|
||||||
|
feat14Desc: 'Les sessions terminées sont archivées automatiquement après une rétention configurable (30 jours par défaut), pour garder la liste propre.',
|
||||||
|
feat15Title: 'Synchro fichiers temps réel',
|
||||||
|
feat15Desc: "Un watcher du système de fichiers pousse les changements dès qu'un fichier bouge sur le disque — diffs et statut se mettent à jour en direct, sans rafraîchir.",
|
||||||
|
|
||||||
|
// Showcase IDE workspace
|
||||||
|
wsKicker: "L'IDE worktree",
|
||||||
|
wsTitle: 'Un IDE complet pour chaque worktree, dans le navigateur',
|
||||||
|
wsBody:
|
||||||
|
"Ouvrez n'importe quel worktree dans /workspace : un arbre de fichiers à gauche, un éditeur Monaco et le diff inline au centre, et le terminal de la session corrélée à droite. Indexez les changements fichier par fichier, rédigez un message de commit, poussez — sans quitter la page, depuis n'importe quel appareil.",
|
||||||
|
wsEditor: 'Éditeur',
|
||||||
|
wsDiff: 'Diff',
|
||||||
|
wsFiles: 'Fichiers',
|
||||||
|
wsChanges: 'Changements',
|
||||||
|
wsStaged: 'Indexés',
|
||||||
|
wsTerminal: 'Terminal',
|
||||||
|
wsCommitMsg: 'Implémente le rafraîchissement du token',
|
||||||
|
wsCommitPlaceholder: 'Message de commit…',
|
||||||
|
wsAmend: 'Amender le dernier commit',
|
||||||
|
wsCommitBtn: 'Commit',
|
||||||
|
wsPushBtn: 'Push',
|
||||||
|
wsStage: 'Indexer',
|
||||||
|
wsUnstage: 'Désindexer',
|
||||||
|
wsDiscard: 'Annuler',
|
||||||
|
|
||||||
|
// Services git distants + clone
|
||||||
|
rgKicker: 'Git distant · chiffré',
|
||||||
|
rgTitle: 'Connectez vos services git et clonez en un clic',
|
||||||
|
rgBody:
|
||||||
|
"Ajoutez des connexions GitHub, GitLab ou Gitea avec un token d'accès personnel ou un app password. Les secrets sont chiffrés au repos (AES-256-GCM) et jamais renvoyés en clair par l'API. Parcourez les repos distants et clonez en HTTPS avec progression en direct.",
|
||||||
|
rgConnections: 'Connexions',
|
||||||
|
rgTested: 'testée',
|
||||||
|
rgAddConnection: 'Ajouter une connexion',
|
||||||
|
rgEncrypted: 'Chiffré au repos',
|
||||||
|
rgCloning: 'Clonage',
|
||||||
|
rgCloneReceiving: 'Réception des objets',
|
||||||
|
|
||||||
|
// Pilier sécurité (secrets chiffrés)
|
||||||
|
sec5Title: 'Secrets chiffrés',
|
||||||
|
sec5Desc: "Les identifiants git distants sont chiffrés au repos (AES-256-GCM) et jamais renvoyés en clair par l'API.",
|
||||||
};
|
};
|
||||||
|
|||||||
2
packages/vscode/.gitignore
vendored
Normal file
2
packages/vscode/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
dist/
|
||||||
|
*.vsix
|
||||||
9
packages/vscode/.vscodeignore
Normal file
9
packages/vscode/.vscodeignore
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Tout est bundlé dans dist/extension.js par esbuild : on n'embarque que le bundle + la meta.
|
||||||
|
src/**
|
||||||
|
test/**
|
||||||
|
node_modules/**
|
||||||
|
esbuild.mjs
|
||||||
|
tsconfig.json
|
||||||
|
.gitignore
|
||||||
|
**/*.ts
|
||||||
|
**/*.map
|
||||||
28
packages/vscode/CHANGELOG.md
Normal file
28
packages/vscode/CHANGELOG.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 0.2.0
|
||||||
|
|
||||||
|
Follows the daemon's "worktree IDE" milestone (P7→P12), while keeping the extension a lightweight
|
||||||
|
**visual worktree manager** — no editor/diff duplicated here, that lives in the web IDE:
|
||||||
|
|
||||||
|
- **Detailed git status** in the worktree tree: staged / unstaged / conflict counts and the last commit
|
||||||
|
subject (from the daemon's enriched `WorktreeGitStatus`).
|
||||||
|
- **Open Worktree IDE** command — deep-links to the web `/workspace/:repoId/:wt` view.
|
||||||
|
- **Fetch** and **Pull** (fast-forward only or rebase) commands on worktrees, alongside commit/push.
|
||||||
|
- **Archived sessions**: the `session_archived` event is handled live; finished, auto-archived sessions
|
||||||
|
are badged and hidden by default, with a new `arboretum.showArchivedSessions` setting to reveal them.
|
||||||
|
|
||||||
|
## 0.1.0
|
||||||
|
|
||||||
|
Initial release — native VS Code integration for the Arboretum daemon:
|
||||||
|
|
||||||
|
- Real-time **Repositories** and **Groups** trees (repos → worktrees → sessions) over the daemon WebSocket.
|
||||||
|
- **Native terminals** (`Pseudoterminal`) to attach/observe any session, reusing VS Code's rendering and
|
||||||
|
scrollback.
|
||||||
|
- **Status-bar** waiting counter and native **notifications** on the rising edge to `waiting`, with
|
||||||
|
Yes/No answers via the `answer` command.
|
||||||
|
- Git mutations from the tree: **create worktree, commit, push, promote**; start session / start group
|
||||||
|
session; resume / fork / kill / hide.
|
||||||
|
- **Workspace awareness**: reveal the worktree for the open folder; start a session or create a worktree
|
||||||
|
for the current folder.
|
||||||
|
- Token auth via `Authorization: Bearer` (REST + WebSocket), token stored in SecretStorage.
|
||||||
21
packages/vscode/LICENSE
Normal file
21
packages/vscode/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Johan Leroy
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
78
packages/vscode/README.md
Normal file
78
packages/vscode/README.md
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# Arboretum for VS Code
|
||||||
|
|
||||||
|
Pilot your git **worktrees** and **Claude Code sessions** from inside VS Code — a real native
|
||||||
|
integration on top of the [Arboretum](https://git.lidge.fr/johanleroy/arboretum) daemon, not a webview.
|
||||||
|
|
||||||
|
- **Live tree** of Repositories → Worktrees → Sessions (and a Groups view), updated in real time over
|
||||||
|
the daemon's WebSocket.
|
||||||
|
- **Native terminals**: attach to any session in a real VS Code terminal (a `Pseudoterminal` bridges the
|
||||||
|
daemon's PTY) — you get VS Code's own rendering, scrollback, copy/paste and links for free.
|
||||||
|
- **Waiting alerts**: a status-bar counter and native notifications when a Claude session is waiting for
|
||||||
|
input — answer **Yes/No** without even opening the terminal (uses the daemon's `answer` command).
|
||||||
|
- **Git mutations** from the tree: create worktree, commit, push, fetch, pull, promote to main — with a
|
||||||
|
**detailed git status** on each worktree (staged / unstaged / conflicts and the last commit subject).
|
||||||
|
- **Open Worktree IDE**: jump from any worktree to its full `/workspace` view (file tree, Monaco editor,
|
||||||
|
inline diffs, integrated terminal) in the browser. The extension stays a lightweight visual worktree
|
||||||
|
manager — the heavy editing lives in the web IDE.
|
||||||
|
- **Workspace-aware**: the worktree matching your open folder is highlighted; start a session or create a
|
||||||
|
worktree for the current folder in one command.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- A running Arboretum daemon (`npx @johanleroy/git-arboretum`, or installed as a user service via
|
||||||
|
`arboretum install`). The extension is a **client** — it does not start the daemon.
|
||||||
|
- An access token. The bootstrap token is printed once on first daemon start; you can also create one in
|
||||||
|
the Arboretum dashboard (**Settings → Tokens**).
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
1. Start the daemon and copy a token.
|
||||||
|
2. In VS Code, run **Arboretum: Sign In** (Command Palette) and paste the token. The token is validated
|
||||||
|
against the daemon and stored in VS Code's encrypted **SecretStorage**.
|
||||||
|
3. The **Arboretum** view container appears in the Activity Bar with the Repositories and Groups trees.
|
||||||
|
|
||||||
|
## Settings
|
||||||
|
|
||||||
|
| Setting | Default | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `arboretum.url` | `http://127.0.0.1:7317` | Base URL of the daemon (REST + WebSocket). |
|
||||||
|
| `arboretum.showExternalSessions` | `false` | Also show Claude sessions started outside Arboretum (CLI). |
|
||||||
|
| `arboretum.showArchivedSessions` | `false` | Also show finished sessions auto-archived after their retention window. |
|
||||||
|
| `arboretum.notifyOnWaiting` | `true` | Native notification when a session starts waiting for input. |
|
||||||
|
|
||||||
|
The extension authenticates with `Authorization: Bearer <token>` on both REST and the WebSocket upgrade.
|
||||||
|
For remote access, point `arboretum.url` at your Tailscale Serve URL (`https://…`) — the WebSocket is
|
||||||
|
derived automatically (`wss://`).
|
||||||
|
|
||||||
|
## Building & packaging (private VSIX)
|
||||||
|
|
||||||
|
The extension is bundled with esbuild (`@arboretum/shared` is inlined → the VSIX is self-contained).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# from the monorepo root
|
||||||
|
npm install
|
||||||
|
npm run build:vscode # builds @arboretum/shared then bundles the extension
|
||||||
|
cd packages/vscode && npx @vscode/vsce package --no-dependencies
|
||||||
|
# → git-arboretum-0.2.0.vsix
|
||||||
|
```
|
||||||
|
|
||||||
|
Install it with **Extensions: Install from VSIX…** in the Command Palette, or:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
code --install-extension git-arboretum-0.2.0.vsix # also: codium / cursor
|
||||||
|
```
|
||||||
|
|
||||||
|
### Other distribution channels (optional)
|
||||||
|
|
||||||
|
- **Open VSX** (VSCodium, Cursor, Windsurf): `npx ovsx publish *.vsix -p <token>` after creating an
|
||||||
|
Open VSX account and namespace.
|
||||||
|
- **VS Code Marketplace**: create an Azure DevOps publisher + PAT, then `npx @vscode/vsce publish`.
|
||||||
|
|
||||||
|
A Gitea Actions workflow packages the VSIX automatically on a `vscode-vX.Y.Z` tag (see
|
||||||
|
`.gitea/workflows/vscode-release.yml`) and attaches it to the release.
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
The extension never weakens the daemon's security model: it speaks the same authenticated protocol as the
|
||||||
|
web dashboard. A Node client sends no `Origin` header, so it passes the daemon's strict Origin check while
|
||||||
|
still requiring a valid token.
|
||||||
28
packages/vscode/esbuild.mjs
Normal file
28
packages/vscode/esbuild.mjs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
// Build de l'extension : un seul bundle CJS `dist/extension.js`.
|
||||||
|
// esbuild résout `@arboretum/shared` via le symlink workspace et l'inline dans le bundle
|
||||||
|
// (VSIX 100 % autonome, sans node_modules embarqué) ; seul `vscode` reste externe (fourni par l'hôte).
|
||||||
|
import esbuild from 'esbuild';
|
||||||
|
|
||||||
|
const watch = process.argv.includes('--watch');
|
||||||
|
|
||||||
|
/** @type {import('esbuild').BuildOptions} */
|
||||||
|
const options = {
|
||||||
|
entryPoints: ['src/extension.ts'],
|
||||||
|
bundle: true,
|
||||||
|
platform: 'node',
|
||||||
|
format: 'cjs',
|
||||||
|
target: 'node18', // VSCode 1.85 embarque Electron/Node 18
|
||||||
|
outfile: 'dist/extension.js',
|
||||||
|
external: ['vscode'], // module fourni par l'hôte VSCode, jamais bundlé
|
||||||
|
sourcemap: true,
|
||||||
|
minify: !watch,
|
||||||
|
logLevel: 'info',
|
||||||
|
};
|
||||||
|
|
||||||
|
if (watch) {
|
||||||
|
const ctx = await esbuild.context(options);
|
||||||
|
await ctx.watch();
|
||||||
|
console.log('[esbuild] watching…');
|
||||||
|
} else {
|
||||||
|
await esbuild.build(options);
|
||||||
|
}
|
||||||
8
packages/vscode/media/arboretum.svg
Normal file
8
packages/vscode/media/arboretum.svg
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||||
|
<path d="M12 22v-6" />
|
||||||
|
<path d="M12 16c0-3 2.5-3.5 4-5 1.4-1.4 1.5-3.6 1-5" />
|
||||||
|
<path d="M12 16c0-3-2.5-3.5-4-5C6.6 9.6 6.5 7.4 7 6" />
|
||||||
|
<circle cx="12" cy="4" r="1.6" />
|
||||||
|
<circle cx="17" cy="6" r="1.6" />
|
||||||
|
<circle cx="7" cy="6" r="1.6" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 416 B |
179
packages/vscode/package.json
Normal file
179
packages/vscode/package.json
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
{
|
||||||
|
"name": "git-arboretum",
|
||||||
|
"displayName": "Arboretum",
|
||||||
|
"description": "Pilot your git worktrees and Claude Code sessions from VS Code — native terminals, live tree, waiting alerts.",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"private": true,
|
||||||
|
"publisher": "johanleroy",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"vscode": "^1.85.0"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://git.lidge.fr/johanleroy/arboretum"
|
||||||
|
},
|
||||||
|
"categories": [
|
||||||
|
"SCM Providers",
|
||||||
|
"Other"
|
||||||
|
],
|
||||||
|
"keywords": [
|
||||||
|
"git",
|
||||||
|
"worktree",
|
||||||
|
"claude",
|
||||||
|
"terminal",
|
||||||
|
"arboretum"
|
||||||
|
],
|
||||||
|
"main": "./dist/extension.js",
|
||||||
|
"activationEvents": [
|
||||||
|
"onStartupFinished"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"configuration": {
|
||||||
|
"title": "Arboretum",
|
||||||
|
"properties": {
|
||||||
|
"arboretum.url": {
|
||||||
|
"type": "string",
|
||||||
|
"default": "http://127.0.0.1:7317",
|
||||||
|
"markdownDescription": "Base URL of the Arboretum daemon (REST + WebSocket). Defaults to the loopback bind."
|
||||||
|
},
|
||||||
|
"arboretum.showExternalSessions": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": false,
|
||||||
|
"markdownDescription": "Show Claude sessions discovered outside Arboretum (started from the CLI) in the trees. Off by default to avoid clutter."
|
||||||
|
},
|
||||||
|
"arboretum.showArchivedSessions": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": false,
|
||||||
|
"markdownDescription": "Show finished sessions that Arboretum auto-archived after their retention window. Off by default to keep the trees focused on live work."
|
||||||
|
},
|
||||||
|
"arboretum.notifyOnWaiting": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": true,
|
||||||
|
"markdownDescription": "Show a native notification when a Claude session starts waiting for input."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"viewsContainers": {
|
||||||
|
"activitybar": [
|
||||||
|
{
|
||||||
|
"id": "arboretum",
|
||||||
|
"title": "Arboretum",
|
||||||
|
"icon": "media/arboretum.svg"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"views": {
|
||||||
|
"arboretum": [
|
||||||
|
{
|
||||||
|
"id": "arboretum.repos",
|
||||||
|
"name": "Repositories",
|
||||||
|
"icon": "media/arboretum.svg"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "arboretum.groups",
|
||||||
|
"name": "Groups",
|
||||||
|
"icon": "media/arboretum.svg"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"viewsWelcome": [
|
||||||
|
{
|
||||||
|
"view": "arboretum.repos",
|
||||||
|
"contents": "Not connected to an Arboretum daemon.\n[Sign in](command:arboretum.signIn)\n\nMake sure the daemon is running (`npx @johanleroy/git-arboretum`) and paste a token.",
|
||||||
|
"when": "!arboretum.connected"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"commands": [
|
||||||
|
{ "command": "arboretum.signIn", "title": "Sign In", "category": "Arboretum" },
|
||||||
|
{ "command": "arboretum.signOut", "title": "Sign Out", "category": "Arboretum" },
|
||||||
|
{ "command": "arboretum.refresh", "title": "Refresh", "category": "Arboretum", "icon": "$(refresh)" },
|
||||||
|
{ "command": "arboretum.openDashboard", "title": "Open Dashboard in Browser", "category": "Arboretum", "icon": "$(globe)" },
|
||||||
|
{ "command": "arboretum.attachSession", "title": "Attach Terminal", "category": "Arboretum", "icon": "$(terminal)" },
|
||||||
|
{ "command": "arboretum.observeSession", "title": "Observe Terminal (read-only)", "category": "Arboretum", "icon": "$(eye)" },
|
||||||
|
{ "command": "arboretum.answerSession", "title": "Answer Prompt…", "category": "Arboretum", "icon": "$(comment-discussion)" },
|
||||||
|
{ "command": "arboretum.killSession", "title": "Kill Session", "category": "Arboretum", "icon": "$(trash)" },
|
||||||
|
{ "command": "arboretum.hideSession", "title": "Hide Session", "category": "Arboretum", "icon": "$(eye-closed)" },
|
||||||
|
{ "command": "arboretum.resumeSession", "title": "Resume Session", "category": "Arboretum", "icon": "$(debug-restart)" },
|
||||||
|
{ "command": "arboretum.forkSession", "title": "Fork Session", "category": "Arboretum", "icon": "$(git-branch)" },
|
||||||
|
{ "command": "arboretum.createWorktree", "title": "Create Worktree…", "category": "Arboretum", "icon": "$(add)" },
|
||||||
|
{ "command": "arboretum.commitWorktree", "title": "Commit…", "category": "Arboretum", "icon": "$(git-commit)" },
|
||||||
|
{ "command": "arboretum.pushWorktree", "title": "Push", "category": "Arboretum", "icon": "$(repo-push)" },
|
||||||
|
{ "command": "arboretum.fetchWorktree", "title": "Fetch", "category": "Arboretum", "icon": "$(cloud-download)" },
|
||||||
|
{ "command": "arboretum.pullWorktree", "title": "Pull…", "category": "Arboretum", "icon": "$(arrow-down)" },
|
||||||
|
{ "command": "arboretum.promoteWorktree", "title": "Promote to Main", "category": "Arboretum", "icon": "$(arrow-up)" },
|
||||||
|
{ "command": "arboretum.openWorktreeIde", "title": "Open Worktree IDE", "category": "Arboretum", "icon": "$(link-external)" },
|
||||||
|
{ "command": "arboretum.startSession", "title": "Start Claude Session", "category": "Arboretum", "icon": "$(play)" },
|
||||||
|
{ "command": "arboretum.startGroupSession", "title": "Start Group Session…", "category": "Arboretum", "icon": "$(play)" },
|
||||||
|
{ "command": "arboretum.startSessionHere", "title": "Start Session in Current Folder", "category": "Arboretum" },
|
||||||
|
{ "command": "arboretum.createWorktreeHere", "title": "Create Worktree for Current Folder…", "category": "Arboretum" },
|
||||||
|
{ "command": "arboretum.revealWorktree", "title": "Reveal Worktree for Current Folder", "category": "Arboretum" }
|
||||||
|
],
|
||||||
|
"menus": {
|
||||||
|
"view/title": [
|
||||||
|
{ "command": "arboretum.refresh", "when": "view == arboretum.repos || view == arboretum.groups", "group": "navigation" },
|
||||||
|
{ "command": "arboretum.openDashboard", "when": "view == arboretum.repos", "group": "navigation" },
|
||||||
|
{ "command": "arboretum.signOut", "when": "view == arboretum.repos && arboretum.connected", "group": "1_auth" },
|
||||||
|
{ "command": "arboretum.signIn", "when": "view == arboretum.repos && !arboretum.connected", "group": "1_auth" }
|
||||||
|
],
|
||||||
|
"view/item/context": [
|
||||||
|
{ "command": "arboretum.createWorktree", "when": "viewItem == arboretum:repo", "group": "inline" },
|
||||||
|
{ "command": "arboretum.startSession", "when": "viewItem == arboretum:repo", "group": "1_session" },
|
||||||
|
{ "command": "arboretum.openWorktreeIde", "when": "viewItem == arboretum:worktree", "group": "inline" },
|
||||||
|
{ "command": "arboretum.commitWorktree", "when": "viewItem == arboretum:worktree", "group": "1_git" },
|
||||||
|
{ "command": "arboretum.pushWorktree", "when": "viewItem == arboretum:worktree", "group": "1_git" },
|
||||||
|
{ "command": "arboretum.fetchWorktree", "when": "viewItem == arboretum:worktree", "group": "1_git" },
|
||||||
|
{ "command": "arboretum.pullWorktree", "when": "viewItem == arboretum:worktree", "group": "1_git" },
|
||||||
|
{ "command": "arboretum.promoteWorktree", "when": "viewItem == arboretum:worktree", "group": "2_git" },
|
||||||
|
{ "command": "arboretum.openWorktreeIde", "when": "viewItem == arboretum:worktree", "group": "2_git" },
|
||||||
|
{ "command": "arboretum.startSession", "when": "viewItem == arboretum:worktree", "group": "3_session" },
|
||||||
|
{ "command": "arboretum.attachSession", "when": "viewItem =~ /arboretum:session:live/", "group": "inline" },
|
||||||
|
{ "command": "arboretum.observeSession", "when": "viewItem =~ /arboretum:session:live/", "group": "1_term" },
|
||||||
|
{ "command": "arboretum.answerSession", "when": "viewItem =~ /arboretum:session:live:.*waiting/", "group": "1_term" },
|
||||||
|
{ "command": "arboretum.killSession", "when": "viewItem =~ /arboretum:session:live/", "group": "9_danger" },
|
||||||
|
{ "command": "arboretum.resumeSession", "when": "viewItem =~ /arboretum:session:dead/", "group": "inline" },
|
||||||
|
{ "command": "arboretum.forkSession", "when": "viewItem =~ /arboretum:session/", "group": "2_term" },
|
||||||
|
{ "command": "arboretum.hideSession", "when": "viewItem =~ /arboretum:session:.*discovered/", "group": "9_danger" },
|
||||||
|
{ "command": "arboretum.startGroupSession", "when": "viewItem == arboretum:group", "group": "inline" }
|
||||||
|
],
|
||||||
|
"commandPalette": [
|
||||||
|
{ "command": "arboretum.refresh", "when": "arboretum.connected" },
|
||||||
|
{ "command": "arboretum.signOut", "when": "arboretum.connected" },
|
||||||
|
{ "command": "arboretum.attachSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.observeSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.answerSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.killSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.hideSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.resumeSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.forkSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.createWorktree", "when": "false" },
|
||||||
|
{ "command": "arboretum.commitWorktree", "when": "false" },
|
||||||
|
{ "command": "arboretum.pushWorktree", "when": "false" },
|
||||||
|
{ "command": "arboretum.fetchWorktree", "when": "false" },
|
||||||
|
{ "command": "arboretum.pullWorktree", "when": "false" },
|
||||||
|
{ "command": "arboretum.promoteWorktree", "when": "false" },
|
||||||
|
{ "command": "arboretum.openWorktreeIde", "when": "false" },
|
||||||
|
{ "command": "arboretum.startSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.startGroupSession", "when": "false" },
|
||||||
|
{ "command": "arboretum.revealWorktree", "when": "false" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"typecheck": "tsc -p . --noEmit",
|
||||||
|
"build": "npm run typecheck && node esbuild.mjs",
|
||||||
|
"dev": "node esbuild.mjs --watch",
|
||||||
|
"vscode:prepublish": "node esbuild.mjs",
|
||||||
|
"package": "vsce package --no-dependencies"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@arboretum/shared": "0.1.0",
|
||||||
|
"@types/node": "^22.10.0",
|
||||||
|
"@types/vscode": "^1.85.0",
|
||||||
|
"@types/ws": "^8.5.0",
|
||||||
|
"@vscode/vsce": "^3.2.0",
|
||||||
|
"esbuild": "^0.21.0",
|
||||||
|
"typescript": "^5.7.0",
|
||||||
|
"ws": "^8.18.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
186
packages/vscode/src/api/rest-client.ts
Normal file
186
packages/vscode/src/api/rest-client.ts
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
// Client REST typé du daemon Arboretum — module pur (pas d'import vscode), testable.
|
||||||
|
// Auth par en-tête `Authorization: Bearer <token>` (le hook preValidation du serveur l'accepte
|
||||||
|
// au même titre que le cookie). Un client Node n'envoie pas d'en-tête Origin → il passe le check
|
||||||
|
// Origin strict côté serveur. Réutilise les types de `@arboretum/shared`.
|
||||||
|
import type {
|
||||||
|
ApiError,
|
||||||
|
CommitWorktreeRequest,
|
||||||
|
CreateGroupSessionRequest,
|
||||||
|
CreateSessionRequest,
|
||||||
|
CreateWorktreeRequest,
|
||||||
|
CreateWorktreeResponse,
|
||||||
|
FetchWorktreeRequest,
|
||||||
|
GroupSessionResponse,
|
||||||
|
GroupsListResponse,
|
||||||
|
MeResponse,
|
||||||
|
PromoteWorktreeRequest,
|
||||||
|
PullWorktreeRequest,
|
||||||
|
PushWorktreeRequest,
|
||||||
|
RepoBranchesResponse,
|
||||||
|
ReposListResponse,
|
||||||
|
SessionResponse,
|
||||||
|
SessionsListResponse,
|
||||||
|
StartRepoSessionRequest,
|
||||||
|
WorktreeResponse,
|
||||||
|
WorktreesListResponse,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import { normalizeBaseUrl } from '../config.js';
|
||||||
|
|
||||||
|
/** Erreur normalisée portant le code/HTTP renvoyés par le serveur. */
|
||||||
|
export class RestError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
readonly status: number,
|
||||||
|
readonly code: string,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'RestError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FetchLike = typeof fetch;
|
||||||
|
|
||||||
|
export class RestClient {
|
||||||
|
private baseUrl: string;
|
||||||
|
private token: string | null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
opts: { baseUrl: string; token?: string | null },
|
||||||
|
private readonly fetchImpl: FetchLike = fetch,
|
||||||
|
) {
|
||||||
|
this.baseUrl = normalizeBaseUrl(opts.baseUrl);
|
||||||
|
this.token = opts.token ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setBaseUrl(url: string): void {
|
||||||
|
this.baseUrl = normalizeBaseUrl(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
setToken(token: string | null): void {
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
get url(): string {
|
||||||
|
return this.baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- auth ----
|
||||||
|
/** Valide le token courant ; lève RestError(401) si invalide. */
|
||||||
|
me(): Promise<MeResponse> {
|
||||||
|
return this.request<MeResponse>('GET', '/api/v1/auth/me');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- repos & worktrees ----
|
||||||
|
listRepos(): Promise<ReposListResponse> {
|
||||||
|
return this.request<ReposListResponse>('GET', '/api/v1/repos');
|
||||||
|
}
|
||||||
|
|
||||||
|
listWorktrees(): Promise<WorktreesListResponse> {
|
||||||
|
return this.request<WorktreesListResponse>('GET', '/api/v1/worktrees');
|
||||||
|
}
|
||||||
|
|
||||||
|
getBranches(repoId: string): Promise<RepoBranchesResponse> {
|
||||||
|
return this.request<RepoBranchesResponse>('GET', `/api/v1/repos/${encodeURIComponent(repoId)}/branches`);
|
||||||
|
}
|
||||||
|
|
||||||
|
createWorktree(repoId: string, body: CreateWorktreeRequest): Promise<CreateWorktreeResponse> {
|
||||||
|
return this.request<CreateWorktreeResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/worktrees`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
commitWorktree(repoId: string, body: CommitWorktreeRequest): Promise<WorktreeResponse> {
|
||||||
|
return this.request<WorktreeResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/worktrees/commit`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
pushWorktree(repoId: string, body: PushWorktreeRequest): Promise<WorktreeResponse> {
|
||||||
|
return this.request<WorktreeResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/worktrees/push`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchWorktree(repoId: string, body: FetchWorktreeRequest): Promise<WorktreeResponse> {
|
||||||
|
return this.request<WorktreeResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/worktrees/fetch`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
pullWorktree(repoId: string, body: PullWorktreeRequest): Promise<WorktreeResponse> {
|
||||||
|
return this.request<WorktreeResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/worktrees/pull`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
promoteWorktree(repoId: string, body: PromoteWorktreeRequest): Promise<WorktreeResponse> {
|
||||||
|
return this.request<WorktreeResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/worktrees/promote`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
startRepoSession(repoId: string, body: StartRepoSessionRequest): Promise<SessionResponse> {
|
||||||
|
return this.request<SessionResponse>('POST', `/api/v1/repos/${encodeURIComponent(repoId)}/session`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- sessions ----
|
||||||
|
createSession(body: CreateSessionRequest): Promise<SessionResponse> {
|
||||||
|
return this.request<SessionResponse>('POST', '/api/v1/sessions', body);
|
||||||
|
}
|
||||||
|
|
||||||
|
listSessions(opts: { includeHidden?: boolean; includeArchived?: boolean } = {}): Promise<SessionsListResponse> {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (opts.includeHidden) params.set('includeHidden', 'true');
|
||||||
|
if (opts.includeArchived) params.set('includeArchived', 'true');
|
||||||
|
const q = params.toString();
|
||||||
|
return this.request<SessionsListResponse>('GET', `/api/v1/sessions${q ? `?${q}` : ''}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
resumeSession(id: string): Promise<SessionResponse> {
|
||||||
|
return this.request<SessionResponse>('POST', `/api/v1/sessions/${encodeURIComponent(id)}/resume`, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
forkSession(id: string): Promise<SessionResponse> {
|
||||||
|
return this.request<SessionResponse>('POST', `/api/v1/sessions/${encodeURIComponent(id)}/fork`, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
hideSession(id: string): Promise<{ ok: true }> {
|
||||||
|
return this.request<{ ok: true }>('POST', `/api/v1/sessions/${encodeURIComponent(id)}/hide`, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
killSession(id: string): Promise<{ ok: true }> {
|
||||||
|
return this.request<{ ok: true }>('DELETE', `/api/v1/sessions/${encodeURIComponent(id)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- groupes ----
|
||||||
|
listGroups(): Promise<GroupsListResponse> {
|
||||||
|
return this.request<GroupsListResponse>('GET', '/api/v1/groups');
|
||||||
|
}
|
||||||
|
|
||||||
|
createGroupSession(groupId: string, body: CreateGroupSessionRequest): Promise<GroupSessionResponse> {
|
||||||
|
return this.request<GroupSessionResponse>('POST', `/api/v1/groups/${encodeURIComponent(groupId)}/session`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- interne ----
|
||||||
|
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
||||||
|
const headers: Record<string, string> = { Accept: 'application/json' };
|
||||||
|
if (this.token) headers.Authorization = `Bearer ${this.token}`;
|
||||||
|
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
||||||
|
|
||||||
|
const init: RequestInit = { method, headers };
|
||||||
|
if (body !== undefined) init.body = JSON.stringify(body);
|
||||||
|
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await this.fetchImpl(`${this.baseUrl}${path}`, init);
|
||||||
|
} catch (err) {
|
||||||
|
throw new RestError(`Cannot reach Arboretum at ${this.baseUrl}: ${(err as Error).message}`, 0, 'NETWORK');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
let code = `HTTP_${res.status}`;
|
||||||
|
let message = `${method} ${path} → ${res.status}`;
|
||||||
|
try {
|
||||||
|
const data = (await res.json()) as ApiError;
|
||||||
|
if (data?.error) {
|
||||||
|
code = data.error.code ?? code;
|
||||||
|
message = data.error.message ?? message;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
/* corps non-JSON : on garde le message générique */
|
||||||
|
}
|
||||||
|
throw new RestError(message, res.status, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.status === 204) return undefined as T;
|
||||||
|
return (await res.json()) as T;
|
||||||
|
}
|
||||||
|
}
|
||||||
430
packages/vscode/src/api/ws-client.ts
Normal file
430
packages/vscode/src/api/ws-client.ts
Normal file
@@ -0,0 +1,430 @@
|
|||||||
|
// Client WebSocket multiplexé Node — portage du client web (packages/web/src/lib/ws-client.ts).
|
||||||
|
// UNE connexion, plusieurs canaux ; handshake hello/hello_ok, sub des topics, corrélation FIFO des
|
||||||
|
// 'attached', flow control par ACK (cumul d'octets PAR CANAL, remis à 0 à chaque RESYNC), reconnexion
|
||||||
|
// avec backoff. Différences vs web :
|
||||||
|
// - transport injecté (RawSocket) → testable sans réseau ; l'implémentation par défaut utilise `ws`
|
||||||
|
// avec l'en-tête `Authorization: Bearer` posé à l'upgrade (le navigateur, lui, envoie le cookie).
|
||||||
|
// - pas de callback de rendu (xterm) : on ACK les octets AU MOMENT où on les remet au sink (onDidWrite
|
||||||
|
// d'un Pseudoterminal émet de façon synchrone). Un ACK traînant débouncé flushe le reliquat < 64 Ko.
|
||||||
|
import {
|
||||||
|
BINARY_FRAME,
|
||||||
|
FLOW,
|
||||||
|
PROTOCOL_VERSION,
|
||||||
|
decodeBinaryFrame,
|
||||||
|
type ClientMessage,
|
||||||
|
type ServerMessage,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import { wsUrlFromBase } from '../config.js';
|
||||||
|
|
||||||
|
export type WsStatus = 'idle' | 'connecting' | 'open' | 'reconnecting';
|
||||||
|
export type DetachReason = 'client' | 'session_exit' | 'replaced';
|
||||||
|
|
||||||
|
export type SessionEvent = Extract<ServerMessage, { type: 'session_update' | 'session_exit' }>;
|
||||||
|
export type WorktreeEvent = Extract<ServerMessage, { type: 'repo_update' | 'repo_removed' | 'worktree_update' | 'worktree_removed' }>;
|
||||||
|
export type GroupEvent = Extract<ServerMessage, { type: 'group_update' | 'group_removed' }>;
|
||||||
|
|
||||||
|
/** Sink d'un canal : reçoit les octets BRUTS (le décodage UTF-8 est délégué au SessionBridge). */
|
||||||
|
export interface AttachmentSink {
|
||||||
|
data(payload: Uint8Array): void;
|
||||||
|
reset(): void;
|
||||||
|
detached(reason: DetachReason): void;
|
||||||
|
controlChanged(controlling: boolean): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AttachOptions {
|
||||||
|
sessionId: string;
|
||||||
|
mode: 'interactive' | 'observer';
|
||||||
|
cols: number;
|
||||||
|
rows: number;
|
||||||
|
sink: AttachmentSink;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Transport minimal — abstrait pour les tests ; l'impl par défaut enveloppe `ws`. */
|
||||||
|
export interface RawSocket {
|
||||||
|
send(data: string): void;
|
||||||
|
close(): void;
|
||||||
|
onOpen(cb: () => void): void;
|
||||||
|
onText(cb: (text: string) => void): void;
|
||||||
|
onBinary(cb: (data: Uint8Array) => void): void;
|
||||||
|
onClose(cb: () => void): void;
|
||||||
|
onError(cb: (err: Error) => void): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SocketFactory = (wsUrl: string, token: string) => RawSocket;
|
||||||
|
|
||||||
|
const BACKOFF_MIN_MS = 500;
|
||||||
|
const BACKOFF_MAX_MS = 10_000;
|
||||||
|
|
||||||
|
export class Attachment {
|
||||||
|
channel = -1;
|
||||||
|
controlling = false;
|
||||||
|
closed = false;
|
||||||
|
cols: number;
|
||||||
|
rows: number;
|
||||||
|
epoch = 0;
|
||||||
|
processedBytes = 0;
|
||||||
|
lastAckBytes = 0;
|
||||||
|
trailingAckTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
pending: { resolve: (a: Attachment) => void; reject: (err: Error) => void } | null = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly client: ArbWsClient,
|
||||||
|
readonly sessionId: string,
|
||||||
|
readonly mode: 'interactive' | 'observer',
|
||||||
|
readonly sink: AttachmentSink,
|
||||||
|
cols: number,
|
||||||
|
rows: number,
|
||||||
|
) {
|
||||||
|
this.cols = cols;
|
||||||
|
this.rows = rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendStdin(data: string): void {
|
||||||
|
if (this.closed || this.channel < 0) return;
|
||||||
|
this.client.sendControl({ type: 'stdin', channel: this.channel, data });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Répond à un dialogue Claude sans clavier ; le serveur traduit en keystrokes. */
|
||||||
|
answer(action: 'select' | 'confirm' | 'deny', optionN?: number): void {
|
||||||
|
if (this.closed || this.channel < 0) return;
|
||||||
|
this.client.sendControl(
|
||||||
|
action === 'select' && optionN !== undefined
|
||||||
|
? { type: 'answer', channel: this.channel, action, optionN }
|
||||||
|
: { type: 'answer', channel: this.channel, action },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
resize(cols: number, rows: number): void {
|
||||||
|
this.cols = cols;
|
||||||
|
this.rows = rows;
|
||||||
|
if (this.closed || this.channel < 0 || !this.controlling) return;
|
||||||
|
this.client.sendControl({ type: 'resize', channel: this.channel, cols, rows });
|
||||||
|
}
|
||||||
|
|
||||||
|
detach(): void {
|
||||||
|
if (this.closed) return;
|
||||||
|
this.closed = true;
|
||||||
|
this.pending = null;
|
||||||
|
this.client.releaseAttachment(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ArbWsClientOptions {
|
||||||
|
socketFactory: SocketFactory;
|
||||||
|
onStatus?: (status: WsStatus) => void;
|
||||||
|
onSession?: (e: SessionEvent) => void;
|
||||||
|
onWorktree?: (e: WorktreeEvent) => void;
|
||||||
|
onGroup?: (e: GroupEvent) => void;
|
||||||
|
/** P10 : une session managée terminée vient d'être auto-archivée. */
|
||||||
|
onSessionArchived?: (sessionId: string) => void;
|
||||||
|
/** appelé au premier hello_ok après (re)connexion → re-seed du store via REST. */
|
||||||
|
onReady?: () => void;
|
||||||
|
log?: (msg: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ArbWsClient {
|
||||||
|
status: WsStatus = 'idle';
|
||||||
|
|
||||||
|
private baseUrl = '';
|
||||||
|
private token = '';
|
||||||
|
private socket: RawSocket | null = null;
|
||||||
|
private ready = false;
|
||||||
|
private stopped = true;
|
||||||
|
private backoffMs = BACKOFF_MIN_MS;
|
||||||
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private readonly attachments = new Set<Attachment>();
|
||||||
|
private readonly byChannel = new Map<number, Attachment>();
|
||||||
|
private awaitingAttached: Attachment[] = [];
|
||||||
|
|
||||||
|
constructor(private readonly opts: ArbWsClientOptions) {}
|
||||||
|
|
||||||
|
/** (Re)configure l'URL/token ; si la connexion était active, elle est relancée. */
|
||||||
|
configure(baseUrl: string, token: string): void {
|
||||||
|
const wasActive = !this.stopped;
|
||||||
|
this.baseUrl = baseUrl;
|
||||||
|
this.token = token;
|
||||||
|
if (wasActive) {
|
||||||
|
this.hardReset();
|
||||||
|
this.connect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connect(): void {
|
||||||
|
this.stopped = false;
|
||||||
|
if (this.socket || this.reconnectTimer) return;
|
||||||
|
if (!this.token) return; // pas authentifié : on n'ouvre rien
|
||||||
|
this.setStatus('connecting');
|
||||||
|
this.openSocket();
|
||||||
|
}
|
||||||
|
|
||||||
|
disconnect(): void {
|
||||||
|
this.stopped = true;
|
||||||
|
this.hardReset();
|
||||||
|
this.setStatus('idle');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** résout sur le prochain 'attached' corrélé ; rejette si la session est introuvable/terminée */
|
||||||
|
attach(opts: AttachOptions): Promise<Attachment> {
|
||||||
|
const att = new Attachment(this, opts.sessionId, opts.mode, opts.sink, opts.cols, opts.rows);
|
||||||
|
const promise = new Promise<Attachment>((resolve, reject) => {
|
||||||
|
att.pending = { resolve, reject };
|
||||||
|
});
|
||||||
|
this.attachments.add(att);
|
||||||
|
this.connect();
|
||||||
|
if (this.ready) this.sendAttach(att);
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
sendControl(msg: ClientMessage): void {
|
||||||
|
if (!this.ready || !this.socket) return;
|
||||||
|
try {
|
||||||
|
this.socket.send(JSON.stringify(msg));
|
||||||
|
} catch {
|
||||||
|
/* socket en cours de fermeture : la reconnexion rejouera */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
releaseAttachment(att: Attachment): void {
|
||||||
|
this.attachments.delete(att);
|
||||||
|
if (att.trailingAckTimer) {
|
||||||
|
clearTimeout(att.trailingAckTimer);
|
||||||
|
att.trailingAckTimer = null;
|
||||||
|
}
|
||||||
|
if (att.channel >= 0) {
|
||||||
|
this.byChannel.delete(att.channel);
|
||||||
|
this.sendControl({ type: 'detach', channel: att.channel });
|
||||||
|
att.channel = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- interne ----
|
||||||
|
|
||||||
|
private setStatus(s: WsStatus): void {
|
||||||
|
this.status = s;
|
||||||
|
this.opts.onStatus?.(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ferme la socket courante et invalide tous les états sans toucher au flag stopped. */
|
||||||
|
private hardReset(): void {
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
const socket = this.socket;
|
||||||
|
this.socket = null;
|
||||||
|
this.ready = false;
|
||||||
|
for (const att of this.attachments) {
|
||||||
|
if (att.trailingAckTimer) {
|
||||||
|
clearTimeout(att.trailingAckTimer);
|
||||||
|
att.trailingAckTimer = null;
|
||||||
|
}
|
||||||
|
att.pending?.reject(new Error('disconnected'));
|
||||||
|
att.pending = null;
|
||||||
|
att.closed = true;
|
||||||
|
att.sink.detached('client');
|
||||||
|
}
|
||||||
|
this.attachments.clear();
|
||||||
|
this.byChannel.clear();
|
||||||
|
this.awaitingAttached = [];
|
||||||
|
socket?.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private openSocket(): void {
|
||||||
|
const socket = this.opts.socketFactory(wsUrlFromBase(this.baseUrl), this.token);
|
||||||
|
this.socket = socket;
|
||||||
|
socket.onOpen(() => {
|
||||||
|
const hello: ClientMessage = { type: 'hello', protocol: PROTOCOL_VERSION };
|
||||||
|
socket.send(JSON.stringify(hello));
|
||||||
|
});
|
||||||
|
socket.onText((text) => this.handleText(text));
|
||||||
|
socket.onBinary((data) => this.handleBinary(data));
|
||||||
|
socket.onClose(() => this.handleClose(socket));
|
||||||
|
socket.onError((err) => this.opts.log?.(`ws error: ${err.message}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleClose(socket: RawSocket): void {
|
||||||
|
if (this.socket !== socket) return;
|
||||||
|
this.socket = null;
|
||||||
|
this.ready = false;
|
||||||
|
this.byChannel.clear();
|
||||||
|
this.awaitingAttached = [];
|
||||||
|
for (const att of this.attachments) {
|
||||||
|
att.channel = -1;
|
||||||
|
att.epoch += 1;
|
||||||
|
if (att.trailingAckTimer) {
|
||||||
|
clearTimeout(att.trailingAckTimer);
|
||||||
|
att.trailingAckTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this.stopped) {
|
||||||
|
this.setStatus('idle');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.setStatus('reconnecting');
|
||||||
|
this.scheduleReconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleReconnect(): void {
|
||||||
|
this.clearReconnectTimer();
|
||||||
|
this.reconnectTimer = setTimeout(() => {
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
if (!this.stopped) this.openSocket();
|
||||||
|
}, this.backoffMs);
|
||||||
|
this.backoffMs = Math.min(this.backoffMs * 2, BACKOFF_MAX_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
private clearReconnectTimer(): void {
|
||||||
|
if (this.reconnectTimer !== null) {
|
||||||
|
clearTimeout(this.reconnectTimer);
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sendAttach(att: Attachment): void {
|
||||||
|
this.awaitingAttached.push(att);
|
||||||
|
this.sendControl({ type: 'attach', sessionId: att.sessionId, mode: att.mode, cols: att.cols, rows: att.rows });
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleText(text: string): void {
|
||||||
|
let msg: ServerMessage;
|
||||||
|
try {
|
||||||
|
msg = JSON.parse(text) as ServerMessage;
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.handleServerMessage(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleBinary(data: Uint8Array): void {
|
||||||
|
if (data.byteLength < BINARY_FRAME.HEADER_BYTES) return;
|
||||||
|
const frame = decodeBinaryFrame(data);
|
||||||
|
const att = this.byChannel.get(frame.channel);
|
||||||
|
if (!att || att.closed) return;
|
||||||
|
|
||||||
|
if (frame.type === BINARY_FRAME.RESYNC) {
|
||||||
|
// le serveur repart de sentBytes=0 : reset terminal, replay, compteurs à zéro (le replay ne compte pas)
|
||||||
|
att.epoch += 1;
|
||||||
|
att.processedBytes = 0;
|
||||||
|
att.lastAckBytes = 0;
|
||||||
|
att.sink.reset();
|
||||||
|
if (frame.payload.byteLength > 0) att.sink.data(frame.payload);
|
||||||
|
this.scheduleTrailingAck(att, att.epoch);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.type !== BINARY_FRAME.OUTPUT) return;
|
||||||
|
|
||||||
|
// Émission synchrone vers le sink (onDidWrite) → on ACK directement les octets remis.
|
||||||
|
const length = frame.payload.byteLength;
|
||||||
|
att.sink.data(frame.payload);
|
||||||
|
if (att.channel < 0) return;
|
||||||
|
att.processedBytes += length;
|
||||||
|
if (att.processedBytes - att.lastAckBytes >= FLOW.ACK_EVERY_BYTES) {
|
||||||
|
att.lastAckBytes = att.processedBytes;
|
||||||
|
this.sendControl({ type: 'ack', channel: att.channel, bytes: att.processedBytes });
|
||||||
|
}
|
||||||
|
// Filet : flushe le reliquat < ACK_EVERY_BYTES pour que le serveur sorte toujours de pause.
|
||||||
|
this.scheduleTrailingAck(att, att.epoch);
|
||||||
|
}
|
||||||
|
|
||||||
|
private scheduleTrailingAck(att: Attachment, epoch: number): void {
|
||||||
|
if (att.trailingAckTimer) clearTimeout(att.trailingAckTimer);
|
||||||
|
att.trailingAckTimer = setTimeout(() => {
|
||||||
|
att.trailingAckTimer = null;
|
||||||
|
if (att.closed || att.epoch !== epoch || att.channel < 0) return;
|
||||||
|
if (att.processedBytes > att.lastAckBytes) {
|
||||||
|
att.lastAckBytes = att.processedBytes;
|
||||||
|
this.sendControl({ type: 'ack', channel: att.channel, bytes: att.processedBytes });
|
||||||
|
}
|
||||||
|
}, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
private handleServerMessage(msg: ServerMessage): void {
|
||||||
|
switch (msg.type) {
|
||||||
|
case 'hello_ok': {
|
||||||
|
this.ready = true;
|
||||||
|
this.backoffMs = BACKOFF_MIN_MS;
|
||||||
|
this.setStatus('open');
|
||||||
|
this.sendControl({ type: 'sub', topics: ['sessions', 'worktrees', 'groups'] });
|
||||||
|
for (const att of this.attachments) {
|
||||||
|
if (!att.closed) this.sendAttach(att);
|
||||||
|
}
|
||||||
|
this.opts.onReady?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'attached': {
|
||||||
|
const att = this.awaitingAttached.shift();
|
||||||
|
if (!att) return;
|
||||||
|
if (att.closed) {
|
||||||
|
this.sendControl({ type: 'detach', channel: msg.channel });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const wasControlling = att.controlling;
|
||||||
|
att.channel = msg.channel;
|
||||||
|
att.controlling = msg.controlling;
|
||||||
|
this.byChannel.set(msg.channel, att);
|
||||||
|
if (att.pending) {
|
||||||
|
att.pending.resolve(att);
|
||||||
|
att.pending = null;
|
||||||
|
} else if (wasControlling !== msg.controlling) {
|
||||||
|
att.sink.controlChanged(msg.controlling);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'detached': {
|
||||||
|
const att = this.byChannel.get(msg.channel);
|
||||||
|
if (!att) return;
|
||||||
|
this.byChannel.delete(msg.channel);
|
||||||
|
att.channel = -1;
|
||||||
|
if (msg.reason === 'client') return;
|
||||||
|
att.closed = true;
|
||||||
|
this.attachments.delete(att);
|
||||||
|
att.sink.detached(msg.reason);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'control_changed': {
|
||||||
|
const att = this.byChannel.get(msg.channel);
|
||||||
|
if (!att || att.closed) return;
|
||||||
|
att.controlling = msg.controlling;
|
||||||
|
att.sink.controlChanged(msg.controlling);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'session_update':
|
||||||
|
case 'session_exit':
|
||||||
|
this.opts.onSession?.(msg);
|
||||||
|
return;
|
||||||
|
case 'session_archived':
|
||||||
|
this.opts.onSessionArchived?.(msg.sessionId);
|
||||||
|
return;
|
||||||
|
case 'repo_update':
|
||||||
|
case 'repo_removed':
|
||||||
|
case 'worktree_update':
|
||||||
|
case 'worktree_removed':
|
||||||
|
this.opts.onWorktree?.(msg);
|
||||||
|
return;
|
||||||
|
case 'group_update':
|
||||||
|
case 'group_removed':
|
||||||
|
this.opts.onGroup?.(msg);
|
||||||
|
return;
|
||||||
|
case 'error': {
|
||||||
|
if (msg.channel !== undefined) {
|
||||||
|
this.opts.log?.(`channel ${msg.channel}: ${msg.code} — ${msg.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ((msg.code === 'NOT_FOUND' || msg.code === 'SESSION_EXITED') && this.awaitingAttached.length > 0) {
|
||||||
|
const att = this.awaitingAttached.shift();
|
||||||
|
if (!att) return;
|
||||||
|
this.attachments.delete(att);
|
||||||
|
if (att.pending) {
|
||||||
|
att.pending.reject(new Error(msg.code));
|
||||||
|
att.pending = null;
|
||||||
|
} else if (!att.closed) {
|
||||||
|
att.closed = true;
|
||||||
|
att.sink.detached('session_exit');
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.opts.log?.(`${msg.code} — ${msg.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case 'pong':
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
33
packages/vscode/src/api/ws-socket.ts
Normal file
33
packages/vscode/src/api/ws-socket.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// Implémentation par défaut du transport RawSocket, basée sur le paquet `ws` (Node).
|
||||||
|
// L'auth se fait en posant `Authorization: Bearer <token>` dans les en-têtes de l'upgrade HTTP
|
||||||
|
// (un navigateur enverrait le cookie ; un client Node passe le token ici). Isolé du cœur ws-client
|
||||||
|
// pour que celui-ci reste injectable et testable sans réseau.
|
||||||
|
import WebSocket, { type RawData } from 'ws';
|
||||||
|
import type { RawSocket, SocketFactory } from './ws-client.js';
|
||||||
|
|
||||||
|
/** Normalise un RawData (Buffer | ArrayBuffer | Buffer[]) en Uint8Array copiée (offset 0). */
|
||||||
|
function toUint8(data: RawData): Uint8Array {
|
||||||
|
if (Array.isArray(data)) return new Uint8Array(Buffer.concat(data));
|
||||||
|
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
||||||
|
// Buffer (sous-classe de Uint8Array) : copie pour ne pas dépendre du buffer poolé réutilisé par ws.
|
||||||
|
return new Uint8Array(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const wsSocketFactory: SocketFactory = (wsUrl: string, token: string): RawSocket => {
|
||||||
|
const socket = new WebSocket(wsUrl, { headers: { Authorization: `Bearer ${token}` } });
|
||||||
|
return {
|
||||||
|
send: (d) => socket.send(d),
|
||||||
|
close: () => socket.close(),
|
||||||
|
onOpen: (cb) => socket.on('open', cb),
|
||||||
|
onText: (cb) =>
|
||||||
|
socket.on('message', (data: RawData, isBinary: boolean) => {
|
||||||
|
if (!isBinary) cb(toUint8(data).toString());
|
||||||
|
}),
|
||||||
|
onBinary: (cb) =>
|
||||||
|
socket.on('message', (data: RawData, isBinary: boolean) => {
|
||||||
|
if (isBinary) cb(toUint8(data));
|
||||||
|
}),
|
||||||
|
onClose: (cb) => socket.on('close', () => cb()),
|
||||||
|
onError: (cb) => socket.on('error', (err: Error) => cb(err)),
|
||||||
|
};
|
||||||
|
};
|
||||||
22
packages/vscode/src/auth/auth.ts
Normal file
22
packages/vscode/src/auth/auth.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
// Stockage du token dans le SecretStorage de VS Code (chiffré par l'hôte). Les tokens du daemon sont
|
||||||
|
// stockés hashés côté serveur et le bootstrap ne s'affiche qu'une fois → on ne peut pas « lire » un
|
||||||
|
// token existant : l'utilisateur le saisit une fois (commande Sign In), on le conserve ici.
|
||||||
|
import type { SecretStorage } from 'vscode';
|
||||||
|
|
||||||
|
const TOKEN_KEY = 'arboretum.token';
|
||||||
|
|
||||||
|
export class Auth {
|
||||||
|
constructor(private readonly secrets: SecretStorage) {}
|
||||||
|
|
||||||
|
getToken(): Thenable<string | undefined> {
|
||||||
|
return this.secrets.get(TOKEN_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
|
storeToken(token: string): Thenable<void> {
|
||||||
|
return this.secrets.store(TOKEN_KEY, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
clearToken(): Thenable<void> {
|
||||||
|
return this.secrets.delete(TOKEN_KEY);
|
||||||
|
}
|
||||||
|
}
|
||||||
333
packages/vscode/src/commands.ts
Normal file
333
packages/vscode/src/commands.ts
Normal file
@@ -0,0 +1,333 @@
|
|||||||
|
// Enregistrement de toutes les commandes de l'extension. Les handlers contextuels reçoivent le nœud
|
||||||
|
// d'arbre cliqué (ou via menu) et narrowent dessus ; les mutations passent par le RestClient et l'état
|
||||||
|
// se met à jour via les events WS (pas de refetch manuel, sauf hide qui sort la session de la liste).
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { GroupSummary, RepoSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import { RestError, type RestClient } from './api/rest-client.js';
|
||||||
|
import { workspaceUrl } from './config.js';
|
||||||
|
import type { ArbWsClient, AttachmentSink } from './api/ws-client.js';
|
||||||
|
import type { Store } from './state/store.js';
|
||||||
|
import type { SessionTerminalManager } from './terminal/session-pty.js';
|
||||||
|
import type { WorkspaceMapper } from './workspace.js';
|
||||||
|
import type { AnyNode } from './views/nodes.js';
|
||||||
|
|
||||||
|
export interface CommandDeps {
|
||||||
|
store: Store;
|
||||||
|
rest: RestClient;
|
||||||
|
ws: ArbWsClient;
|
||||||
|
terminals: SessionTerminalManager;
|
||||||
|
workspace: WorkspaceMapper;
|
||||||
|
signIn(): Promise<void>;
|
||||||
|
signOut(): Promise<void>;
|
||||||
|
reseed(): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- extraction des nœuds ----
|
||||||
|
function asSession(node: AnyNode | undefined): SessionSummary | undefined {
|
||||||
|
return node && (node.kind === 'session' || node.kind === 'group-session') ? node.session : undefined;
|
||||||
|
}
|
||||||
|
function asWorktree(node: AnyNode | undefined): { repoId: string; worktree: WorktreeSummary } | undefined {
|
||||||
|
return node?.kind === 'worktree' ? { repoId: node.repoId, worktree: node.worktree } : undefined;
|
||||||
|
}
|
||||||
|
function asRepo(node: AnyNode | undefined): RepoSummary | undefined {
|
||||||
|
return node?.kind === 'repo' ? node.repo : undefined;
|
||||||
|
}
|
||||||
|
function asGroup(node: AnyNode | undefined): GroupSummary | undefined {
|
||||||
|
return node?.kind === 'group' ? node.group : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exécute une action en affichant proprement une erreur REST (code + message serveur). */
|
||||||
|
async function run(label: string, fn: () => Promise<void>): Promise<void> {
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err instanceof RestError ? `${err.code}: ${err.message}` : (err as Error).message;
|
||||||
|
void vscode.window.showErrorMessage(`Arboretum — ${label}: ${msg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Répond à un dialogue : via le terminal ouvert si présent, sinon par une attache éphémère. */
|
||||||
|
export async function answerSession(
|
||||||
|
deps: CommandDeps,
|
||||||
|
session: SessionSummary,
|
||||||
|
action: 'select' | 'confirm' | 'deny',
|
||||||
|
optionN?: number,
|
||||||
|
): Promise<void> {
|
||||||
|
const open = deps.terminals.getBridge(session.id);
|
||||||
|
if (open) {
|
||||||
|
open.answer(action, optionN);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const noop: AttachmentSink = { data: () => {}, reset: () => {}, detached: () => {}, controlChanged: () => {} };
|
||||||
|
const att = await deps.ws.attach({ sessionId: session.id, mode: 'interactive', cols: 80, rows: 24, sink: noop });
|
||||||
|
att.answer(action, optionN);
|
||||||
|
setTimeout(() => att.detach(), 600); // laisse le serveur traiter avant de fermer le canal éphémère
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerCommands(context: vscode.ExtensionContext, deps: CommandDeps): void {
|
||||||
|
const { store, rest, terminals, workspace } = deps;
|
||||||
|
|
||||||
|
const cmd = (id: string, handler: (...args: unknown[]) => unknown): void => {
|
||||||
|
context.subscriptions.push(vscode.commands.registerCommand(id, handler));
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- auth / global ----
|
||||||
|
cmd('arboretum.signIn', () => deps.signIn());
|
||||||
|
cmd('arboretum.signOut', () => deps.signOut());
|
||||||
|
cmd('arboretum.refresh', () => run('refresh', () => deps.reseed()));
|
||||||
|
cmd('arboretum.openDashboard', () => {
|
||||||
|
void vscode.env.openExternal(vscode.Uri.parse(rest.url));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- terminaux (Phase B) ----
|
||||||
|
cmd('arboretum.attachSession', (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (s) terminals.open(s, 'interactive');
|
||||||
|
});
|
||||||
|
cmd('arboretum.observeSession', (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (s) terminals.open(s, 'observer');
|
||||||
|
});
|
||||||
|
cmd('arboretum.showWaiting', async () => {
|
||||||
|
const waiting = store.waitingSessions();
|
||||||
|
if (waiting.length === 0) {
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: no session waiting.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const pick = await vscode.window.showQuickPick(
|
||||||
|
waiting.map((s) => ({ label: s.title?.trim() || s.command, description: s.waitingFor ?? s.cwd, session: s })),
|
||||||
|
{ placeHolder: 'Sessions waiting for input' },
|
||||||
|
);
|
||||||
|
if (pick) terminals.open(pick.session, 'interactive');
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- answer (Phase C) ----
|
||||||
|
cmd('arboretum.answerSession', async (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (!s) return;
|
||||||
|
const dialogOptions = s.dialog?.options ?? [];
|
||||||
|
if (dialogOptions.length > 0) {
|
||||||
|
const pick = await vscode.window.showQuickPick(
|
||||||
|
dialogOptions.map((o) => ({ label: o.label, option: o })),
|
||||||
|
{ placeHolder: s.dialog?.waitingFor ?? 'Choose an option' },
|
||||||
|
);
|
||||||
|
if (pick) await run('answer', () => answerSession(deps, s, 'select', pick.option.n));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const pick = await vscode.window.showQuickPick(['Yes', 'No'], { placeHolder: s.waitingFor ?? 'Answer the prompt' });
|
||||||
|
if (pick) await run('answer', () => answerSession(deps, s, pick === 'Yes' ? 'confirm' : 'deny'));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- sessions ----
|
||||||
|
cmd('arboretum.killSession', async (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (!s) return;
|
||||||
|
const ok = await vscode.window.showWarningMessage(`Kill session "${s.title?.trim() || s.command}"?`, { modal: true }, 'Kill');
|
||||||
|
if (ok === 'Kill') await run('kill', async () => void (await rest.killSession(s.id)));
|
||||||
|
});
|
||||||
|
cmd('arboretum.hideSession', (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (!s) return;
|
||||||
|
void run('hide', async () => {
|
||||||
|
await rest.hideSession(s.id);
|
||||||
|
await deps.reseed(); // la session masquée sort de la liste (listSessions sans includeHidden)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
cmd('arboretum.resumeSession', (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (!s) return;
|
||||||
|
void run('resume', async () => {
|
||||||
|
const res = await rest.resumeSession(s.id);
|
||||||
|
terminals.open(res.session, 'interactive');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
cmd('arboretum.forkSession', (node) => {
|
||||||
|
const s = asSession(node as AnyNode);
|
||||||
|
if (!s) return;
|
||||||
|
void run('fork', async () => {
|
||||||
|
const res = await rest.forkSession(s.id);
|
||||||
|
terminals.open(res.session, 'interactive');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- worktrees (Phase C) ----
|
||||||
|
cmd('arboretum.createWorktree', (node) => {
|
||||||
|
const repo = asRepo(node as AnyNode);
|
||||||
|
if (repo) void createWorktreeFlow(deps, repo.id);
|
||||||
|
});
|
||||||
|
cmd('arboretum.commitWorktree', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (!wt) return;
|
||||||
|
void run('commit', async () => {
|
||||||
|
const message = await vscode.window.showInputBox({ prompt: 'Commit message', placeHolder: 'Describe your changes' });
|
||||||
|
if (!message) return;
|
||||||
|
await rest.commitWorktree(wt.repoId, { path: wt.worktree.path, message });
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: committed.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
cmd('arboretum.pushWorktree', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (!wt) return;
|
||||||
|
void vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Arboretum: pushing…' }, () =>
|
||||||
|
run('push', async () => {
|
||||||
|
await rest.pushWorktree(wt.repoId, { path: wt.worktree.path });
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: pushed.');
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
cmd('arboretum.fetchWorktree', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (!wt) return;
|
||||||
|
void vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Arboretum: fetching…' }, () =>
|
||||||
|
run('fetch', async () => {
|
||||||
|
await rest.fetchWorktree(wt.repoId, { path: wt.worktree.path });
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: fetched.');
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
cmd('arboretum.pullWorktree', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (!wt) return;
|
||||||
|
void run('pull', async () => {
|
||||||
|
const mode = await vscode.window.showQuickPick(
|
||||||
|
[
|
||||||
|
{ label: 'Fast-forward only', mode: 'ff-only' as const },
|
||||||
|
{ label: 'Rebase', mode: 'rebase' as const },
|
||||||
|
],
|
||||||
|
{ placeHolder: 'Pull strategy' },
|
||||||
|
);
|
||||||
|
if (!mode) return;
|
||||||
|
await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Arboretum: pulling…' }, async () => {
|
||||||
|
await rest.pullWorktree(wt.repoId, { path: wt.worktree.path, mode: mode.mode });
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: pulled.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
cmd('arboretum.promoteWorktree', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (wt) void promoteWorktreeFlow(deps, wt.repoId, wt.worktree);
|
||||||
|
});
|
||||||
|
cmd('arboretum.openWorktreeIde', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (!wt) return;
|
||||||
|
void vscode.env.openExternal(vscode.Uri.parse(workspaceUrl(rest.url, wt.repoId, wt.worktree.path)));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- démarrage de session ----
|
||||||
|
cmd('arboretum.startSession', (node) => {
|
||||||
|
const wt = asWorktree(node as AnyNode);
|
||||||
|
if (wt) {
|
||||||
|
void run('start session', async () => {
|
||||||
|
const res = await rest.createSession({ cwd: wt.worktree.path, command: 'claude' });
|
||||||
|
terminals.open(res.session, 'interactive');
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const repo = asRepo(node as AnyNode);
|
||||||
|
if (repo) {
|
||||||
|
void run('start session', async () => {
|
||||||
|
const res = await rest.startRepoSession(repo.id, { command: 'claude' });
|
||||||
|
terminals.open(res.session, 'interactive');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
cmd('arboretum.startGroupSession', (node) => {
|
||||||
|
const group = asGroup(node as AnyNode);
|
||||||
|
if (group) void startGroupSessionFlow(deps, group);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- conscience du workspace (Phase D) ----
|
||||||
|
cmd('arboretum.startSessionHere', () => {
|
||||||
|
const repoId = workspace.currentRepoId();
|
||||||
|
if (!repoId) {
|
||||||
|
void vscode.window.showWarningMessage('Arboretum: the current folder is not a known repo/worktree.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const folder = vscode.workspace.workspaceFolders?.[0];
|
||||||
|
if (!folder) return;
|
||||||
|
void run('start session', async () => {
|
||||||
|
const res = await rest.createSession({ cwd: folder.uri.fsPath, command: 'claude' });
|
||||||
|
terminals.open(res.session, 'interactive');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
cmd('arboretum.createWorktreeHere', () => {
|
||||||
|
const repoId = workspace.currentRepoId();
|
||||||
|
if (!repoId) {
|
||||||
|
void vscode.window.showWarningMessage('Arboretum: the current folder is not a known repo.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void createWorktreeFlow(deps, repoId);
|
||||||
|
});
|
||||||
|
cmd('arboretum.revealWorktree', () => workspace.revealCurrent());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- flows interactifs ----
|
||||||
|
|
||||||
|
async function createWorktreeFlow(deps: CommandDeps, repoId: string): Promise<void> {
|
||||||
|
await run('create worktree', async () => {
|
||||||
|
const branches = await deps.rest.getBranches(repoId);
|
||||||
|
const existing = [...new Set([...branches.local, ...branches.remote.map((b) => b.replace(/^origin\//, ''))])].sort();
|
||||||
|
const NEW = '$(add) New branch…';
|
||||||
|
const items = [NEW, ...existing];
|
||||||
|
const choice = await vscode.window.showQuickPick(items, { placeHolder: 'Branch for the new worktree (auto: checkout if exists, else create)' });
|
||||||
|
if (!choice) return;
|
||||||
|
let branch = choice;
|
||||||
|
if (choice === NEW) {
|
||||||
|
const input = await vscode.window.showInputBox({ prompt: 'New branch name' });
|
||||||
|
if (!input) return;
|
||||||
|
branch = input.trim();
|
||||||
|
}
|
||||||
|
if (!branch) return;
|
||||||
|
const res = await deps.rest.createWorktree(repoId, { branch, mode: 'auto' });
|
||||||
|
void vscode.window.showInformationMessage(`Arboretum: worktree ${res.action} for "${branch}".`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function promoteWorktreeFlow(deps: CommandDeps, repoId: string, worktree: WorktreeSummary): Promise<void> {
|
||||||
|
const label = worktree.branch ?? worktree.path;
|
||||||
|
const confirm = await vscode.window.showWarningMessage(
|
||||||
|
`Promote "${label}" to the repo's main checkout? The worktree is removed (branch kept).`,
|
||||||
|
{ modal: true },
|
||||||
|
'Promote',
|
||||||
|
);
|
||||||
|
if (confirm !== 'Promote') return;
|
||||||
|
try {
|
||||||
|
await deps.rest.promoteWorktree(repoId, { path: worktree.path });
|
||||||
|
void vscode.window.showInformationMessage(`Arboretum: "${label}" promoted to main.`);
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof RestError && err.status === 409) {
|
||||||
|
const force = await vscode.window.showWarningMessage(
|
||||||
|
`Arboretum: working tree is dirty (${err.message}). Promote anyway?`,
|
||||||
|
{ modal: true },
|
||||||
|
'Force promote',
|
||||||
|
);
|
||||||
|
if (force === 'Force promote') {
|
||||||
|
await run('promote', async () => {
|
||||||
|
await deps.rest.promoteWorktree(repoId, { path: worktree.path, force: true });
|
||||||
|
void vscode.window.showInformationMessage(`Arboretum: "${label}" promoted (forced).`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const msg = err instanceof RestError ? `${err.code}: ${err.message}` : (err as Error).message;
|
||||||
|
void vscode.window.showErrorMessage(`Arboretum — promote: ${msg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startGroupSessionFlow(deps: CommandDeps, group: GroupSummary): Promise<void> {
|
||||||
|
await run('start group session', async () => {
|
||||||
|
const branch = await vscode.window.showInputBox({
|
||||||
|
prompt: `Branch to cover in each repo of "${group.label}" (leave empty for the main checkouts)`,
|
||||||
|
placeHolder: 'feature/cross-repo (optional)',
|
||||||
|
});
|
||||||
|
if (branch === undefined) return; // annulé (chaîne vide = checkouts principaux)
|
||||||
|
const body = branch.trim() ? { command: 'claude' as const, branch: branch.trim() } : { command: 'claude' as const };
|
||||||
|
const res = await deps.rest.createGroupSession(group.id, body);
|
||||||
|
deps.terminals.open(res.session, 'interactive');
|
||||||
|
if (res.skipped.length > 0) {
|
||||||
|
void vscode.window.showWarningMessage(
|
||||||
|
`Arboretum: ${res.skipped.length} repo(s) skipped — ${res.skipped.map((s) => s.reason).join('; ')}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
31
packages/vscode/src/config.ts
Normal file
31
packages/vscode/src/config.ts
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
// Lecture des réglages `arboretum.*` — module pur (aucun import vscode) pour rester testable.
|
||||||
|
// L'extension fournit un `ConfigSnapshot` lu depuis workspace.getConfiguration ; ce module
|
||||||
|
// normalise/dérive les valeurs (notamment l'URL WebSocket à partir de l'URL HTTP).
|
||||||
|
|
||||||
|
export interface ConfigSnapshot {
|
||||||
|
url: string;
|
||||||
|
showExternalSessions: boolean;
|
||||||
|
showArchivedSessions: boolean;
|
||||||
|
notifyOnWaiting: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Base REST normalisée (sans slash final) ; `http://127.0.0.1:7317` par défaut. */
|
||||||
|
export function normalizeBaseUrl(url: string): string {
|
||||||
|
const trimmed = (url || '').trim().replace(/\/+$/, '');
|
||||||
|
return trimmed || 'http://127.0.0.1:7317';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dérive l'URL du endpoint WebSocket `/ws` (http→ws, https→wss). */
|
||||||
|
export function wsUrlFromBase(baseUrl: string): string {
|
||||||
|
const base = normalizeBaseUrl(baseUrl);
|
||||||
|
return `${base.replace(/^http/, 'ws')}/ws`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Construit l'URL de la vue IDE web d'un worktree — deep-link vers la route `/workspace/:repoId/:wt`
|
||||||
|
* (le routeur web est en history mode). `repoId` et le chemin du worktree sont encodés par segment.
|
||||||
|
*/
|
||||||
|
export function workspaceUrl(baseUrl: string, repoId: string, worktreePath: string): string {
|
||||||
|
const base = normalizeBaseUrl(baseUrl);
|
||||||
|
return `${base}/workspace/${encodeURIComponent(repoId)}/${encodeURIComponent(worktreePath)}`;
|
||||||
|
}
|
||||||
161
packages/vscode/src/extension.ts
Normal file
161
packages/vscode/src/extension.ts
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
// Point d'entrée de l'extension : câble auth ↔ REST ↔ WS ↔ store ↔ surfaces natives (arbres, terminaux,
|
||||||
|
// status bar, notifications, workspace). C'est le SEUL gros consommateur de l'API vscode avec les vues ;
|
||||||
|
// toute la logique réutilisable (protocole, état) vit dans des modules purs testables.
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import { Auth } from './auth/auth.js';
|
||||||
|
import { RestClient } from './api/rest-client.js';
|
||||||
|
import { ArbWsClient } from './api/ws-client.js';
|
||||||
|
import { wsSocketFactory } from './api/ws-socket.js';
|
||||||
|
import { Store } from './state/store.js';
|
||||||
|
import { SessionTerminalManager } from './terminal/session-pty.js';
|
||||||
|
import { ReposTreeProvider } from './views/repos-tree.js';
|
||||||
|
import { GroupsTreeProvider } from './views/groups-tree.js';
|
||||||
|
import { StatusBar } from './status-bar.js';
|
||||||
|
import { WaitingNotifier } from './notifications.js';
|
||||||
|
import { WorkspaceMapper } from './workspace.js';
|
||||||
|
import { answerSession, registerCommands } from './commands.js';
|
||||||
|
|
||||||
|
function readUrl(): string {
|
||||||
|
return vscode.workspace.getConfiguration('arboretum').get<string>('url', 'http://127.0.0.1:7317');
|
||||||
|
}
|
||||||
|
function readShowExternal(): boolean {
|
||||||
|
return vscode.workspace.getConfiguration('arboretum').get<boolean>('showExternalSessions', false);
|
||||||
|
}
|
||||||
|
function readShowArchived(): boolean {
|
||||||
|
return vscode.workspace.getConfiguration('arboretum').get<boolean>('showArchivedSessions', false);
|
||||||
|
}
|
||||||
|
function readNotify(): boolean {
|
||||||
|
return vscode.workspace.getConfiguration('arboretum').get<boolean>('notifyOnWaiting', true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setConnectedContext(connected: boolean): Promise<void> {
|
||||||
|
await vscode.commands.executeCommand('setContext', 'arboretum.connected', connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function activate(context: vscode.ExtensionContext): Promise<void> {
|
||||||
|
const log = vscode.window.createOutputChannel('Arboretum');
|
||||||
|
context.subscriptions.push(log);
|
||||||
|
|
||||||
|
const auth = new Auth(context.secrets);
|
||||||
|
const store = new Store();
|
||||||
|
store.showExternalSessions = readShowExternal();
|
||||||
|
store.showArchivedSessions = readShowArchived();
|
||||||
|
const rest = new RestClient({ baseUrl: readUrl() });
|
||||||
|
|
||||||
|
const reseed = async (): Promise<void> => {
|
||||||
|
try {
|
||||||
|
await store.seed(rest);
|
||||||
|
} catch (err) {
|
||||||
|
log.appendLine(`seed failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusBar = new StatusBar(store);
|
||||||
|
context.subscriptions.push(statusBar);
|
||||||
|
|
||||||
|
const ws = new ArbWsClient({
|
||||||
|
socketFactory: wsSocketFactory,
|
||||||
|
onSession: (e) => store.applySession(e),
|
||||||
|
onWorktree: (e) => store.applyWorktree(e),
|
||||||
|
onGroup: (e) => store.applyGroup(e),
|
||||||
|
onSessionArchived: (id) => store.archiveSession(id),
|
||||||
|
onReady: () => void reseed(),
|
||||||
|
onStatus: (s) => {
|
||||||
|
const connected = s === 'open';
|
||||||
|
statusBar.setConnected(connected);
|
||||||
|
void setConnectedContext(connected);
|
||||||
|
},
|
||||||
|
log: (m) => log.appendLine(m),
|
||||||
|
});
|
||||||
|
|
||||||
|
const terminals = new SessionTerminalManager(ws);
|
||||||
|
context.subscriptions.push({ dispose: () => terminals.dispose() });
|
||||||
|
|
||||||
|
const reposProvider = new ReposTreeProvider(store);
|
||||||
|
const groupsProvider = new GroupsTreeProvider(store);
|
||||||
|
const reposView = vscode.window.createTreeView('arboretum.repos', { treeDataProvider: reposProvider, showCollapseAll: true });
|
||||||
|
const groupsView = vscode.window.createTreeView('arboretum.groups', { treeDataProvider: groupsProvider, showCollapseAll: true });
|
||||||
|
context.subscriptions.push(reposView, groupsView);
|
||||||
|
|
||||||
|
const workspace = new WorkspaceMapper(store, reposView, reposProvider);
|
||||||
|
context.subscriptions.push(workspace);
|
||||||
|
|
||||||
|
const signIn = async (): Promise<void> => {
|
||||||
|
const token = await vscode.window.showInputBox({
|
||||||
|
prompt: `Arboretum token for ${rest.url}`,
|
||||||
|
password: true,
|
||||||
|
ignoreFocusOut: true,
|
||||||
|
placeHolder: 'arb_… (printed once on first daemon start, or created in Settings → Tokens)',
|
||||||
|
});
|
||||||
|
if (!token) return;
|
||||||
|
// valide le token avant de le stocker (sonde isolée pour ne pas polluer le client principal).
|
||||||
|
const probe = new RestClient({ baseUrl: rest.url, token });
|
||||||
|
try {
|
||||||
|
await probe.me();
|
||||||
|
} catch (err) {
|
||||||
|
void vscode.window.showErrorMessage(`Arboretum: sign in failed — ${(err as Error).message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await auth.storeToken(token);
|
||||||
|
rest.setToken(token);
|
||||||
|
ws.configure(rest.url, token);
|
||||||
|
ws.connect();
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: connected.');
|
||||||
|
};
|
||||||
|
|
||||||
|
const signOut = async (): Promise<void> => {
|
||||||
|
await auth.clearToken();
|
||||||
|
rest.setToken(null);
|
||||||
|
ws.disconnect();
|
||||||
|
store.clear();
|
||||||
|
await setConnectedContext(false);
|
||||||
|
void vscode.window.showInformationMessage('Arboretum: signed out.');
|
||||||
|
};
|
||||||
|
|
||||||
|
registerCommands(context, { store, rest, ws, terminals, workspace, signIn, signOut, reseed });
|
||||||
|
|
||||||
|
// Notifications : ouvrir le terminal ou répondre Yes/No (réutilise le helper transient-attach).
|
||||||
|
const notifier = new WaitingNotifier(store, {
|
||||||
|
notifyEnabled: () => readNotify(),
|
||||||
|
openTerminal: (session) => terminals.open(session, 'interactive'),
|
||||||
|
answer: (session, action) => {
|
||||||
|
void answerSession({ store, rest, ws, terminals, workspace, signIn, signOut, reseed }, session, action).catch((err: Error) =>
|
||||||
|
log.appendLine(`answer failed: ${err.message}`),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
context.subscriptions.push(notifier);
|
||||||
|
|
||||||
|
// Réglages à chaud : URL (reconfigure REST+WS), sessions externes (refiltre), notif (lu à la volée).
|
||||||
|
context.subscriptions.push(
|
||||||
|
vscode.workspace.onDidChangeConfiguration(async (e) => {
|
||||||
|
if (e.affectsConfiguration('arboretum.url')) {
|
||||||
|
rest.setBaseUrl(readUrl());
|
||||||
|
const token = await auth.getToken();
|
||||||
|
if (token) ws.configure(rest.url, token);
|
||||||
|
}
|
||||||
|
if (e.affectsConfiguration('arboretum.showExternalSessions')) {
|
||||||
|
store.setShowExternalSessions(readShowExternal());
|
||||||
|
}
|
||||||
|
if (e.affectsConfiguration('arboretum.showArchivedSessions')) {
|
||||||
|
store.setShowArchivedSessions(readShowArchived());
|
||||||
|
await reseed(); // recharge la liste avec/sans les sessions archivées (includeArchived)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Connexion initiale si un token est déjà mémorisé.
|
||||||
|
await setConnectedContext(false);
|
||||||
|
const token = await auth.getToken();
|
||||||
|
if (token) {
|
||||||
|
rest.setToken(token);
|
||||||
|
ws.configure(rest.url, token);
|
||||||
|
ws.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
context.subscriptions.push({ dispose: () => ws.disconnect() });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deactivate(): void {
|
||||||
|
// tout est enregistré dans context.subscriptions → disposé par VS Code.
|
||||||
|
}
|
||||||
57
packages/vscode/src/notifications.ts
Normal file
57
packages/vscode/src/notifications.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
// Notifications natives sur front montant d'une session vers `waiting` (doublonne utilement le Web
|
||||||
|
// Push, ici dans l'éditeur). Suit l'activité précédente par session pour ne notifier qu'à la transition,
|
||||||
|
// pas à chaque mise à jour. Actions : ouvrir le terminal, ou répondre Yes/No via la commande WS `answer`.
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { SessionSummary } from '@arboretum/shared';
|
||||||
|
import type { Store } from './state/store.js';
|
||||||
|
|
||||||
|
export interface NotificationHooks {
|
||||||
|
notifyEnabled(): boolean;
|
||||||
|
openTerminal(session: SessionSummary): void;
|
||||||
|
answer(session: SessionSummary, action: 'confirm' | 'deny'): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WaitingNotifier implements vscode.Disposable {
|
||||||
|
/** dernière activité connue par session → détection du front montant vers 'waiting'. */
|
||||||
|
private readonly lastActivity = new Map<string, string | null | undefined>();
|
||||||
|
private readonly unsubscribe: () => void;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly store: Store,
|
||||||
|
private readonly hooks: NotificationHooks,
|
||||||
|
) {
|
||||||
|
this.unsubscribe = store.onDidChange(() => this.check());
|
||||||
|
}
|
||||||
|
|
||||||
|
private check(): void {
|
||||||
|
const sessions = this.store.allSessions();
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const s of sessions) {
|
||||||
|
seen.add(s.id);
|
||||||
|
const prev = this.lastActivity.get(s.id);
|
||||||
|
const cur = s.live ? s.activity : null;
|
||||||
|
this.lastActivity.set(s.id, cur);
|
||||||
|
if (cur === 'waiting' && prev !== 'waiting' && prev !== undefined && this.hooks.notifyEnabled()) {
|
||||||
|
this.notify(s);
|
||||||
|
}
|
||||||
|
// prev === undefined : première observation (au seed) → on n'annonce pas l'historique.
|
||||||
|
}
|
||||||
|
for (const id of [...this.lastActivity.keys()]) if (!seen.has(id)) this.lastActivity.delete(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private notify(session: SessionSummary): void {
|
||||||
|
const title = session.title?.trim() || session.command;
|
||||||
|
const detail = session.waitingFor ? ` — ${session.waitingFor}` : '';
|
||||||
|
void vscode.window
|
||||||
|
.showInformationMessage(`Arboretum: "${title}" is waiting for input${detail}`, 'Open Terminal', 'Yes', 'No')
|
||||||
|
.then((choice) => {
|
||||||
|
if (choice === 'Open Terminal') this.hooks.openTerminal(session);
|
||||||
|
else if (choice === 'Yes') this.hooks.answer(session, 'confirm');
|
||||||
|
else if (choice === 'No') this.hooks.answer(session, 'deny');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.unsubscribe();
|
||||||
|
}
|
||||||
|
}
|
||||||
215
packages/vscode/src/state/store.ts
Normal file
215
packages/vscode/src/state/store.ts
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
// État mémoire de l'extension — module pur (aucun import vscode), testable.
|
||||||
|
// Seedé via REST au (re)connect, puis patché par les events WS. Émet onDidChange à chaque mutation ;
|
||||||
|
// les arbres / status bar / notifications s'y abonnent. Principe « groupe léger » : on ne corrèle pas
|
||||||
|
// les worktrees aux sessions via la liste embarquée (potentiellement périmée) mais par `cwd`, exactement
|
||||||
|
// comme `sessionsForCwd` côté serveur.
|
||||||
|
import type {
|
||||||
|
GroupSummary,
|
||||||
|
RepoSummary,
|
||||||
|
SessionSummary,
|
||||||
|
WorktreeSummary,
|
||||||
|
} from '@arboretum/shared';
|
||||||
|
import type { GroupEvent, SessionEvent, WorktreeEvent } from '../api/ws-client.js';
|
||||||
|
import type { RestClient } from '../api/rest-client.js';
|
||||||
|
|
||||||
|
/** Normalise un chemin absolu pour la corrélation (retire le slash final). */
|
||||||
|
function normPath(p: string): string {
|
||||||
|
return p.replace(/\/+$/, '') || '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Store {
|
||||||
|
private readonly repos = new Map<string, RepoSummary>();
|
||||||
|
/** worktrees par repo, indexés par chemin (clé stable). */
|
||||||
|
private readonly worktrees = new Map<string, Map<string, WorktreeSummary>>();
|
||||||
|
private readonly sessions = new Map<string, SessionSummary>();
|
||||||
|
private readonly groups = new Map<string, GroupSummary>();
|
||||||
|
private readonly listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
/** affiche aussi les sessions externes (découvertes hors Arboretum). */
|
||||||
|
showExternalSessions = false;
|
||||||
|
/** affiche aussi les sessions managées auto-archivées par ancienneté (P10). */
|
||||||
|
showArchivedSessions = false;
|
||||||
|
|
||||||
|
onDidChange(cb: () => void): () => void {
|
||||||
|
this.listeners.add(cb);
|
||||||
|
return () => this.listeners.delete(cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bascule l'affichage des sessions externes et notifie les abonnés (refiltre les arbres). */
|
||||||
|
setShowExternalSessions(value: boolean): void {
|
||||||
|
if (this.showExternalSessions === value) return;
|
||||||
|
this.showExternalSessions = value;
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bascule l'affichage des sessions archivées (le re-seed REST est piloté par l'extension). */
|
||||||
|
setShowArchivedSessions(value: boolean): void {
|
||||||
|
if (this.showArchivedSessions === value) return;
|
||||||
|
this.showArchivedSessions = value;
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
private emit(): void {
|
||||||
|
for (const cb of this.listeners) cb();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Charge tout l'état depuis le daemon (au premier hello_ok et à chaque reconnexion). */
|
||||||
|
async seed(rest: RestClient): Promise<void> {
|
||||||
|
const [repos, worktrees, sessions, groups] = await Promise.all([
|
||||||
|
rest.listRepos(),
|
||||||
|
rest.listWorktrees(),
|
||||||
|
rest.listSessions({ includeArchived: this.showArchivedSessions }),
|
||||||
|
rest.listGroups(),
|
||||||
|
]);
|
||||||
|
this.repos.clear();
|
||||||
|
this.worktrees.clear();
|
||||||
|
this.sessions.clear();
|
||||||
|
this.groups.clear();
|
||||||
|
for (const r of repos.repos) this.repos.set(r.id, r);
|
||||||
|
for (const w of worktrees.worktrees) this.putWorktree(w);
|
||||||
|
for (const s of sessions.sessions) this.sessions.set(s.id, s);
|
||||||
|
for (const g of groups.groups) this.groups.set(g.id, g);
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this.repos.clear();
|
||||||
|
this.worktrees.clear();
|
||||||
|
this.sessions.clear();
|
||||||
|
this.groups.clear();
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
private putWorktree(w: WorktreeSummary): void {
|
||||||
|
let byPath = this.worktrees.get(w.repoId);
|
||||||
|
if (!byPath) {
|
||||||
|
byPath = new Map();
|
||||||
|
this.worktrees.set(w.repoId, byPath);
|
||||||
|
}
|
||||||
|
byPath.set(normPath(w.path), w);
|
||||||
|
// les sessions embarquées dans le worktree alimentent aussi la map sessions (état initial).
|
||||||
|
for (const s of w.sessions) if (!this.sessions.has(s.id)) this.sessions.set(s.id, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- réducteurs d'events WS ----
|
||||||
|
|
||||||
|
applySession(e: SessionEvent): void {
|
||||||
|
if (e.type === 'session_update') {
|
||||||
|
this.sessions.set(e.session.id, e.session);
|
||||||
|
} else {
|
||||||
|
// session_exit : marque morte si connue (sinon ignore).
|
||||||
|
const prev = this.sessions.get(e.sessionId);
|
||||||
|
if (prev) this.sessions.set(e.sessionId, { ...prev, live: false, status: 'exited', exitCode: e.exitCode });
|
||||||
|
}
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** P10 : une session managée terminée vient d'être auto-archivée (message WS `session_archived`). */
|
||||||
|
archiveSession(sessionId: string): void {
|
||||||
|
const prev = this.sessions.get(sessionId);
|
||||||
|
if (!prev) return;
|
||||||
|
this.sessions.set(sessionId, { ...prev, archived: true });
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
applyWorktree(e: WorktreeEvent): void {
|
||||||
|
switch (e.type) {
|
||||||
|
case 'repo_update':
|
||||||
|
this.repos.set(e.repo.id, e.repo);
|
||||||
|
break;
|
||||||
|
case 'repo_removed':
|
||||||
|
this.repos.delete(e.repoId);
|
||||||
|
this.worktrees.delete(e.repoId);
|
||||||
|
break;
|
||||||
|
case 'worktree_update':
|
||||||
|
this.putWorktree(e.worktree);
|
||||||
|
break;
|
||||||
|
case 'worktree_removed':
|
||||||
|
this.worktrees.get(e.repoId)?.delete(normPath(e.path));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
applyGroup(e: GroupEvent): void {
|
||||||
|
if (e.type === 'group_update') this.groups.set(e.group.id, e.group);
|
||||||
|
else this.groups.delete(e.groupId);
|
||||||
|
this.emit();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- lecture ----
|
||||||
|
|
||||||
|
listRepos(): RepoSummary[] {
|
||||||
|
return [...this.repos.values()]
|
||||||
|
.filter((r) => !r.hidden && r.valid)
|
||||||
|
.sort((a, b) => a.label.localeCompare(b.label));
|
||||||
|
}
|
||||||
|
|
||||||
|
getRepo(id: string): RepoSummary | undefined {
|
||||||
|
return this.repos.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
listWorktrees(repoId: string): WorktreeSummary[] {
|
||||||
|
const byPath = this.worktrees.get(repoId);
|
||||||
|
if (!byPath) return [];
|
||||||
|
// worktree principal en tête, puis tri par branche/chemin.
|
||||||
|
return [...byPath.values()].sort((a, b) => {
|
||||||
|
if (a.isMain !== b.isMain) return a.isMain ? -1 : 1;
|
||||||
|
return (a.branch ?? a.path).localeCompare(b.branch ?? b.path);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getWorktree(repoId: string, path: string): WorktreeSummary | undefined {
|
||||||
|
return this.worktrees.get(repoId)?.get(normPath(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** sessions corrélées à un worktree par cwd (comme le serveur) ; filtre les externes selon le réglage. */
|
||||||
|
sessionsForWorktree(path: string): SessionSummary[] {
|
||||||
|
const wp = normPath(path);
|
||||||
|
return [...this.sessions.values()]
|
||||||
|
.filter((s) => normPath(s.cwd) === wp)
|
||||||
|
.filter((s) => this.showExternalSessions || s.source === 'managed')
|
||||||
|
.filter((s) => this.showArchivedSessions || !s.archived)
|
||||||
|
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
getSession(id: string): SessionSummary | undefined {
|
||||||
|
return this.sessions.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
listGroups(): GroupSummary[] {
|
||||||
|
return [...this.groups.values()].sort((a, b) => a.label.localeCompare(b.label));
|
||||||
|
}
|
||||||
|
|
||||||
|
getGroup(id: string): GroupSummary | undefined {
|
||||||
|
return this.groups.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** sessions de groupe (couvrant plusieurs repos) attachées à un groupe donné. */
|
||||||
|
sessionsForGroup(groupId: string): SessionSummary[] {
|
||||||
|
return [...this.sessions.values()]
|
||||||
|
.filter((s) => s.groupId === groupId)
|
||||||
|
.filter((s) => this.showExternalSessions || s.source === 'managed')
|
||||||
|
.filter((s) => this.showArchivedSessions || !s.archived)
|
||||||
|
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** sessions en attente d'input (activity === 'waiting') — pour la status bar et les notifications. */
|
||||||
|
waitingSessions(): SessionSummary[] {
|
||||||
|
return [...this.sessions.values()].filter((s) => s.live && s.activity === 'waiting');
|
||||||
|
}
|
||||||
|
|
||||||
|
allSessions(): SessionSummary[] {
|
||||||
|
return [...this.sessions.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** trouve le worktree dont le chemin == folderPath (mapping workspace). */
|
||||||
|
findWorktreeByPath(folderPath: string): { repoId: string; worktree: WorktreeSummary } | undefined {
|
||||||
|
const target = normPath(folderPath);
|
||||||
|
for (const [repoId, byPath] of this.worktrees) {
|
||||||
|
const wt = byPath.get(target);
|
||||||
|
if (wt) return { repoId, worktree: wt };
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
40
packages/vscode/src/status-bar.ts
Normal file
40
packages/vscode/src/status-bar.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
// Status bar : compteur des sessions Claude en attente d'input (`activity === 'waiting'`).
|
||||||
|
// Clic → quick-pick des sessions en attente (commande arboretum.showWaiting). Masqué si déconnecté
|
||||||
|
// ou s'il n'y a rien en attente.
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { Store } from './state/store.js';
|
||||||
|
|
||||||
|
export class StatusBar implements vscode.Disposable {
|
||||||
|
private readonly item: vscode.StatusBarItem;
|
||||||
|
private connected = false;
|
||||||
|
private readonly unsubscribe: () => void;
|
||||||
|
|
||||||
|
constructor(private readonly store: Store) {
|
||||||
|
this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100);
|
||||||
|
this.item.command = 'arboretum.showWaiting';
|
||||||
|
this.unsubscribe = store.onDidChange(() => this.update());
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
setConnected(connected: boolean): void {
|
||||||
|
this.connected = connected;
|
||||||
|
this.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
private update(): void {
|
||||||
|
const count = this.connected ? this.store.waitingSessions().length : 0;
|
||||||
|
if (count === 0) {
|
||||||
|
this.item.hide();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.item.text = `$(bell-dot) ${count}`;
|
||||||
|
this.item.tooltip = `Arboretum: ${count} session(s) waiting for input`;
|
||||||
|
this.item.color = new vscode.ThemeColor('statusBarItem.warningForeground');
|
||||||
|
this.item.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
this.unsubscribe();
|
||||||
|
this.item.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
85
packages/vscode/src/terminal/session-bridge.ts
Normal file
85
packages/vscode/src/terminal/session-bridge.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
// Pont d'une session vers un terminal — module pur (aucun import vscode), testable.
|
||||||
|
// Le ws-client remet des octets BRUTS (un chunk PTY peut couper un caractère UTF-8 en frontière de
|
||||||
|
// frame, exactement comme côté web où xterm.write(Uint8Array) gérait le décodage). Ici la cible est
|
||||||
|
// un Pseudoterminal qui veut des `string` → on décode en streaming avec un TextDecoder, et on recrée
|
||||||
|
// le décodeur à chaque RESYNC pour ne pas traîner une séquence partielle au-delà d'un reset.
|
||||||
|
import type { ArbWsClient, Attachment, AttachmentSink, DetachReason } from '../api/ws-client.js';
|
||||||
|
|
||||||
|
/** Décodeur UTF-8 incrémental : conserve l'octet partiel d'une frontière de frame jusqu'au suivant. */
|
||||||
|
export class StreamingUtf8Decoder {
|
||||||
|
private decoder = new TextDecoder('utf-8');
|
||||||
|
|
||||||
|
decode(chunk: Uint8Array): string {
|
||||||
|
return this.decoder.decode(chunk, { stream: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vide l'état partiel et repart à neuf (appelé sur RESYNC). */
|
||||||
|
reset(): void {
|
||||||
|
this.decoder = new TextDecoder('utf-8');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionBridgeCallbacks {
|
||||||
|
/** texte décodé à écrire dans le terminal. */
|
||||||
|
onText(text: string): void;
|
||||||
|
/** RESYNC reçu : le terminal doit se réinitialiser (le texte de replay suit via onText). */
|
||||||
|
onReset(): void;
|
||||||
|
onDetached(reason: DetachReason): void;
|
||||||
|
onControlChanged(controlling: boolean): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relie une session Arboretum à un terminal via le ws-client. Instancié par l'adaptateur
|
||||||
|
* Pseudoterminal ; reste pur pour être testable avec un faux ws-client.
|
||||||
|
*/
|
||||||
|
export class SessionBridge {
|
||||||
|
private attachment: Attachment | null = null;
|
||||||
|
private readonly decoder = new StreamingUtf8Decoder();
|
||||||
|
private detached = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly ws: ArbWsClient,
|
||||||
|
private readonly sessionId: string,
|
||||||
|
private readonly mode: 'interactive' | 'observer',
|
||||||
|
private readonly cb: SessionBridgeCallbacks,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** Ouvre l'attache ; résout quand le canal est établi. Rejette si la session est introuvable. */
|
||||||
|
async open(cols: number, rows: number): Promise<void> {
|
||||||
|
const sink: AttachmentSink = {
|
||||||
|
data: (payload) => {
|
||||||
|
if (this.detached) return;
|
||||||
|
const text = this.decoder.decode(payload);
|
||||||
|
if (text.length > 0) this.cb.onText(text);
|
||||||
|
},
|
||||||
|
reset: () => {
|
||||||
|
this.decoder.reset();
|
||||||
|
this.cb.onReset();
|
||||||
|
},
|
||||||
|
detached: (reason) => {
|
||||||
|
this.detached = true;
|
||||||
|
this.cb.onDetached(reason);
|
||||||
|
},
|
||||||
|
controlChanged: (c) => this.cb.onControlChanged(c),
|
||||||
|
};
|
||||||
|
this.attachment = await this.ws.attach({ sessionId: this.sessionId, mode: this.mode, cols, rows, sink });
|
||||||
|
}
|
||||||
|
|
||||||
|
sendStdin(data: string): void {
|
||||||
|
this.attachment?.sendStdin(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
resize(cols: number, rows: number): void {
|
||||||
|
this.attachment?.resize(cols, rows);
|
||||||
|
}
|
||||||
|
|
||||||
|
answer(action: 'select' | 'confirm' | 'deny', optionN?: number): void {
|
||||||
|
this.attachment?.answer(action, optionN);
|
||||||
|
}
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
this.detached = true;
|
||||||
|
this.attachment?.detach();
|
||||||
|
this.attachment = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
86
packages/vscode/src/terminal/session-pty.ts
Normal file
86
packages/vscode/src/terminal/session-pty.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
// Adaptateur vscode.Pseudoterminal : expose une session Arboretum comme un terminal NATIF de VS Code
|
||||||
|
// (rendu, scrollback, copier/coller, liens gratuits). C'est la pièce maîtresse de l'intégration —
|
||||||
|
// pas de xterm-in-webview. Le pont WS/décodage vit dans SessionBridge (pur) ; cet adaptateur ne fait
|
||||||
|
// que relier les events Pseudoterminal ↔ bridge.
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { SessionSummary } from '@arboretum/shared';
|
||||||
|
import type { ArbWsClient } from '../api/ws-client.js';
|
||||||
|
import { SessionBridge } from './session-bridge.js';
|
||||||
|
|
||||||
|
const ANSI_RESET = '\x1bc'; // RIS : réinitialisation complète du terminal (avant le replay d'un RESYNC)
|
||||||
|
|
||||||
|
export class SessionTerminalManager {
|
||||||
|
private readonly terminals = new Map<string, vscode.Terminal>();
|
||||||
|
private readonly bridges = new Map<string, SessionBridge>();
|
||||||
|
|
||||||
|
constructor(private readonly ws: ArbWsClient) {}
|
||||||
|
|
||||||
|
/** Bridge d'une session si un terminal est ouvert (pour répondre à un dialogue sans ré-attacher). */
|
||||||
|
getBridge(sessionId: string): SessionBridge | undefined {
|
||||||
|
return this.bridges.get(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ouvre (ou ré-affiche) un terminal natif attaché à la session. */
|
||||||
|
open(session: SessionSummary, mode: 'interactive' | 'observer'): void {
|
||||||
|
const existing = this.terminals.get(session.id);
|
||||||
|
if (existing) {
|
||||||
|
existing.show();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const writeEmitter = new vscode.EventEmitter<string>();
|
||||||
|
const closeEmitter = new vscode.EventEmitter<number | void>();
|
||||||
|
let bridge: SessionBridge | null = null;
|
||||||
|
|
||||||
|
const pty: vscode.Pseudoterminal = {
|
||||||
|
onDidWrite: writeEmitter.event,
|
||||||
|
onDidClose: closeEmitter.event,
|
||||||
|
open: (dims) => {
|
||||||
|
bridge = new SessionBridge(this.ws, session.id, mode, {
|
||||||
|
onText: (text) => writeEmitter.fire(text),
|
||||||
|
onReset: () => writeEmitter.fire(ANSI_RESET),
|
||||||
|
onDetached: () => {
|
||||||
|
writeEmitter.fire('\r\n\x1b[2m[arboretum: session ended]\x1b[0m\r\n');
|
||||||
|
closeEmitter.fire();
|
||||||
|
},
|
||||||
|
onControlChanged: (controlling) => {
|
||||||
|
if (!controlling && mode === 'interactive') {
|
||||||
|
writeEmitter.fire('\r\n\x1b[33m[arboretum: control lost — now observing]\x1b[0m\r\n');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.bridges.set(session.id, bridge);
|
||||||
|
bridge.open(dims?.columns ?? 80, dims?.rows ?? 24).catch((err: Error) => {
|
||||||
|
writeEmitter.fire(`\r\n\x1b[31m[arboretum: cannot attach — ${err.message}]\x1b[0m\r\n`);
|
||||||
|
closeEmitter.fire();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
close: () => {
|
||||||
|
bridge?.close();
|
||||||
|
this.bridges.delete(session.id);
|
||||||
|
this.terminals.delete(session.id);
|
||||||
|
},
|
||||||
|
handleInput: (data) => {
|
||||||
|
if (mode === 'interactive') bridge?.sendStdin(data);
|
||||||
|
},
|
||||||
|
setDimensions: (dims) => bridge?.resize(dims.columns, dims.rows),
|
||||||
|
};
|
||||||
|
|
||||||
|
const name = this.terminalName(session, mode);
|
||||||
|
const terminal = vscode.window.createTerminal({ name, pty, iconPath: new vscode.ThemeIcon('comment-discussion') });
|
||||||
|
this.terminals.set(session.id, terminal);
|
||||||
|
terminal.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
private terminalName(session: SessionSummary, mode: 'interactive' | 'observer'): string {
|
||||||
|
const base = session.title?.trim() || session.cwd.split('/').pop() || session.command;
|
||||||
|
const prefix = mode === 'observer' ? '👁 ' : '';
|
||||||
|
return `${prefix}${base}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
for (const t of this.terminals.values()) t.dispose();
|
||||||
|
this.terminals.clear();
|
||||||
|
this.bridges.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
64
packages/vscode/src/views/groups-tree.ts
Normal file
64
packages/vscode/src/views/groups-tree.ts
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
// Arbre Groups → repos membres → worktrees/sessions, plus les sessions de groupe (multi-repo, --add-dir)
|
||||||
|
// rattachées directement au groupe. Rafraîchi en temps réel (store.onDidChange).
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { Store } from '../state/store.js';
|
||||||
|
import type { GroupsNode } from './nodes.js';
|
||||||
|
import { groupTreeItem, repoTreeItem, sessionTreeItem, worktreeTreeItem } from './tree-items.js';
|
||||||
|
|
||||||
|
export class GroupsTreeProvider implements vscode.TreeDataProvider<GroupsNode> {
|
||||||
|
private readonly changeEmitter = new vscode.EventEmitter<GroupsNode | undefined>();
|
||||||
|
readonly onDidChangeTreeData = this.changeEmitter.event;
|
||||||
|
|
||||||
|
constructor(private readonly store: Store) {
|
||||||
|
store.onDidChange(() => this.changeEmitter.fire(undefined));
|
||||||
|
}
|
||||||
|
|
||||||
|
getTreeItem(node: GroupsNode): vscode.TreeItem {
|
||||||
|
switch (node.kind) {
|
||||||
|
case 'group':
|
||||||
|
return groupTreeItem(node.group);
|
||||||
|
case 'repo':
|
||||||
|
return repoTreeItem(node.repo);
|
||||||
|
case 'worktree':
|
||||||
|
return worktreeTreeItem(node.worktree);
|
||||||
|
case 'group-session':
|
||||||
|
case 'session': {
|
||||||
|
const item = sessionTreeItem(node.session);
|
||||||
|
if (node.session.live) {
|
||||||
|
item.command = { command: 'arboretum.attachSession', title: 'Attach', arguments: [node] };
|
||||||
|
}
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getChildren(node?: GroupsNode): GroupsNode[] {
|
||||||
|
if (!node) {
|
||||||
|
return this.store.listGroups().map((group) => ({ kind: 'group', group }));
|
||||||
|
}
|
||||||
|
if (node.kind === 'group') {
|
||||||
|
const children: GroupsNode[] = [];
|
||||||
|
// sessions de groupe (couvrant plusieurs repos) en tête
|
||||||
|
for (const session of this.store.sessionsForGroup(node.group.id)) {
|
||||||
|
children.push({ kind: 'group-session', session, groupId: node.group.id });
|
||||||
|
}
|
||||||
|
// puis les repos membres
|
||||||
|
for (const repoId of node.group.repoIds) {
|
||||||
|
const repo = this.store.getRepo(repoId);
|
||||||
|
if (repo) children.push({ kind: 'repo', repo });
|
||||||
|
}
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
if (node.kind === 'repo') {
|
||||||
|
return this.store
|
||||||
|
.listWorktrees(node.repo.id)
|
||||||
|
.map((worktree) => ({ kind: 'worktree', repoId: node.repo.id, worktree }));
|
||||||
|
}
|
||||||
|
if (node.kind === 'worktree') {
|
||||||
|
return this.store
|
||||||
|
.sessionsForWorktree(node.worktree.path)
|
||||||
|
.map((session) => ({ kind: 'session', session, repoId: node.repoId, worktreePath: node.worktree.path }));
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
33
packages/vscode/src/views/nodes.ts
Normal file
33
packages/vscode/src/views/nodes.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
// Types de nœuds des arbres. Les handlers de commandes reçoivent un nœud (clic ou menu contextuel) et
|
||||||
|
// narrowent sur `kind`. Volontairement plats (données + discriminant) ; la hiérarchie parent/enfant est
|
||||||
|
// tenue par les providers (maps indexées) pour que reveal()/getParent fonctionnent.
|
||||||
|
import type { GroupSummary, RepoSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
|
||||||
|
export interface RepoNode {
|
||||||
|
kind: 'repo';
|
||||||
|
repo: RepoSummary;
|
||||||
|
}
|
||||||
|
export interface WorktreeNode {
|
||||||
|
kind: 'worktree';
|
||||||
|
repoId: string;
|
||||||
|
worktree: WorktreeSummary;
|
||||||
|
}
|
||||||
|
export interface SessionNode {
|
||||||
|
kind: 'session';
|
||||||
|
session: SessionSummary;
|
||||||
|
repoId: string;
|
||||||
|
worktreePath: string;
|
||||||
|
}
|
||||||
|
export interface GroupNode {
|
||||||
|
kind: 'group';
|
||||||
|
group: GroupSummary;
|
||||||
|
}
|
||||||
|
export interface GroupSessionNode {
|
||||||
|
kind: 'group-session';
|
||||||
|
session: SessionSummary;
|
||||||
|
groupId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ReposNode = RepoNode | WorktreeNode | SessionNode;
|
||||||
|
export type GroupsNode = GroupNode | RepoNode | WorktreeNode | SessionNode | GroupSessionNode;
|
||||||
|
export type AnyNode = ReposNode | GroupsNode;
|
||||||
BIN
packages/vscode/src/views/repos-tree.ts
Normal file
BIN
packages/vscode/src/views/repos-tree.ts
Normal file
Binary file not shown.
116
packages/vscode/src/views/tree-items.ts
Normal file
116
packages/vscode/src/views/tree-items.ts
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
// Helpers de construction des TreeItem (icônes d'état, labels, contextValue) partagés par les deux
|
||||||
|
// arbres (Repositories & Groups). Les `contextValue` pilotent les menus contextuels (cf. package.json) ;
|
||||||
|
// les regex y matchent des sous-chaînes → format stable `arboretum:session:<live|dead>[:discovered][:waiting]`.
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { GroupSummary, RepoSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
|
||||||
|
export function repoTreeItem(repo: RepoSummary): vscode.TreeItem {
|
||||||
|
const item = new vscode.TreeItem(repo.label, vscode.TreeItemCollapsibleState.Expanded);
|
||||||
|
item.id = `repo:${repo.id}`;
|
||||||
|
item.contextValue = 'arboretum:repo';
|
||||||
|
item.iconPath = new vscode.ThemeIcon('repo');
|
||||||
|
item.description = repo.defaultBranch ?? '';
|
||||||
|
item.tooltip = repo.path;
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function worktreeTreeItem(worktree: WorktreeSummary): vscode.TreeItem {
|
||||||
|
const label = worktree.branch ?? (worktree.detached ? '(detached)' : worktree.head.slice(0, 8));
|
||||||
|
const item = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.Expanded);
|
||||||
|
item.id = `wt:${worktree.path}`;
|
||||||
|
item.contextValue = 'arboretum:worktree';
|
||||||
|
item.iconPath = new vscode.ThemeIcon(worktree.isMain ? 'star-full' : 'git-branch');
|
||||||
|
item.description = worktreeStatus(worktree);
|
||||||
|
item.tooltip = worktreeTooltip(worktree);
|
||||||
|
item.resourceUri = vscode.Uri.file(worktree.path);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
function worktreeStatus(w: WorktreeSummary): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
if (w.isMain) parts.push('main');
|
||||||
|
if (w.git.ahead > 0) parts.push(`↑${w.git.ahead}`);
|
||||||
|
if (w.git.behind > 0) parts.push(`↓${w.git.behind}`);
|
||||||
|
if (w.git.dirtyCount > 0) parts.push(`●${w.git.dirtyCount}`);
|
||||||
|
// Compteurs fins (P7, additifs) : staged/conflits surfacés directement dans l'arbre.
|
||||||
|
if (w.git.stagedCount && w.git.stagedCount > 0) parts.push(`+${w.git.stagedCount}`);
|
||||||
|
if (w.git.conflictCount && w.git.conflictCount > 0) parts.push(`!${w.git.conflictCount}`);
|
||||||
|
return parts.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tooltip détaillé : chemin + statut git fin (P7) + dernier commit. */
|
||||||
|
function worktreeTooltip(w: WorktreeSummary): vscode.MarkdownString {
|
||||||
|
const md = new vscode.MarkdownString();
|
||||||
|
md.appendMarkdown(`\`${w.path}\`\n\n`);
|
||||||
|
const g = w.git;
|
||||||
|
const status: string[] = [];
|
||||||
|
if (g.stagedCount && g.stagedCount > 0) status.push(`${g.stagedCount} staged`);
|
||||||
|
if (g.unstagedCount && g.unstagedCount > 0) status.push(`${g.unstagedCount} unstaged`);
|
||||||
|
if (g.conflictCount && g.conflictCount > 0) status.push(`${g.conflictCount} conflicts`);
|
||||||
|
if (status.length === 0 && g.dirtyCount > 0) status.push(`${g.dirtyCount} changed`);
|
||||||
|
md.appendMarkdown(status.length > 0 ? status.join(' · ') : 'clean');
|
||||||
|
if (g.ahead > 0 || g.behind > 0) md.appendMarkdown(` (↑${g.ahead} ↓${g.behind})`);
|
||||||
|
if (g.lastCommitSubject) md.appendMarkdown(`\n\n_${g.lastCommitSubject}_`);
|
||||||
|
return md;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sessionContextValue(s: SessionSummary): string {
|
||||||
|
let v = `arboretum:session:${s.live ? 'live' : 'dead'}`;
|
||||||
|
if (s.source === 'discovered') v += ':discovered';
|
||||||
|
if (s.live && s.activity === 'waiting') v += ':waiting';
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sessionTreeItem(s: SessionSummary): vscode.TreeItem {
|
||||||
|
const label = s.title?.trim() || s.command;
|
||||||
|
const item = new vscode.TreeItem(label, vscode.TreeItemCollapsibleState.None);
|
||||||
|
item.id = `session:${s.id}`;
|
||||||
|
item.contextValue = sessionContextValue(s);
|
||||||
|
item.iconPath = sessionIcon(s);
|
||||||
|
item.description = sessionDescription(s);
|
||||||
|
item.tooltip = sessionTooltip(s);
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionIcon(s: SessionSummary): vscode.ThemeIcon {
|
||||||
|
if (!s.live) return new vscode.ThemeIcon('circle-slash');
|
||||||
|
switch (s.activity) {
|
||||||
|
case 'waiting':
|
||||||
|
return new vscode.ThemeIcon('bell-dot', new vscode.ThemeColor('charts.yellow'));
|
||||||
|
case 'busy':
|
||||||
|
return new vscode.ThemeIcon('loading~spin');
|
||||||
|
case 'idle':
|
||||||
|
return new vscode.ThemeIcon('pass', new vscode.ThemeColor('charts.green'));
|
||||||
|
default:
|
||||||
|
return new vscode.ThemeIcon('terminal');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionDescription(s: SessionSummary): string {
|
||||||
|
const parts: string[] = [];
|
||||||
|
// Affiche 'available' pour idle (cohérent avec le libellé web) ; l'enum reste 'idle' côté protocole.
|
||||||
|
if (s.live && s.activity) parts.push(s.activity === 'idle' ? 'available' : s.activity);
|
||||||
|
else if (!s.live) parts.push('exited');
|
||||||
|
if (s.archived) parts.push('archived');
|
||||||
|
if (s.source === 'discovered') parts.push('external');
|
||||||
|
if (s.groupId) parts.push('group');
|
||||||
|
if (s.waitingFor) parts.push(`— ${s.waitingFor}`);
|
||||||
|
return parts.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionTooltip(s: SessionSummary): string {
|
||||||
|
const lines = [`${s.command} — ${s.cwd}`, `status: ${s.status}${s.live ? ' (live)' : ''}`];
|
||||||
|
if (s.activity) lines.push(`activity: ${s.activity}`);
|
||||||
|
if (s.addedDirs && s.addedDirs.length > 0) lines.push(`added dirs: ${s.addedDirs.length}`);
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupTreeItem(group: GroupSummary): vscode.TreeItem {
|
||||||
|
const item = new vscode.TreeItem(group.label, vscode.TreeItemCollapsibleState.Collapsed);
|
||||||
|
item.id = `group:${group.id}`;
|
||||||
|
item.contextValue = 'arboretum:group';
|
||||||
|
item.iconPath = new vscode.ThemeIcon('folder-library');
|
||||||
|
item.description = `${group.repoIds.length} repos`;
|
||||||
|
if (group.description) item.tooltip = group.description;
|
||||||
|
return item;
|
||||||
|
}
|
||||||
57
packages/vscode/src/workspace.ts
Normal file
57
packages/vscode/src/workspace.ts
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
// Conscience du workspace (Phase D) : mappe les dossiers ouverts dans VS Code aux repos/worktrees
|
||||||
|
// Arboretum par égalité de chemin, met en évidence le worktree correspondant dans l'arbre, et fournit
|
||||||
|
// le repoId courant aux commandes contextuelles (« start session here », « create worktree here »).
|
||||||
|
import * as vscode from 'vscode';
|
||||||
|
import type { Store } from './state/store.js';
|
||||||
|
import type { ReposNode } from './views/nodes.js';
|
||||||
|
import type { ReposTreeProvider } from './views/repos-tree.js';
|
||||||
|
|
||||||
|
function normPath(p: string): string {
|
||||||
|
return p.replace(/\/+$/, '') || '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
export class WorkspaceMapper implements vscode.Disposable {
|
||||||
|
private readonly disposables: vscode.Disposable[] = [];
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly store: Store,
|
||||||
|
private readonly treeView: vscode.TreeView<ReposNode>,
|
||||||
|
private readonly provider: ReposTreeProvider,
|
||||||
|
) {
|
||||||
|
this.disposables.push(vscode.workspace.onDidChangeWorkspaceFolders(() => this.revealCurrent()));
|
||||||
|
// re-tente après chaque rafraîchissement de l'état (les worktrees arrivent après la connexion).
|
||||||
|
this.disposables.push({ dispose: store.onDidChange(() => this.revealCurrent()) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** repoId correspondant à un dossier ouvert (via worktree ou racine de repo), pour les actions contextuelles. */
|
||||||
|
currentRepoId(): string | undefined {
|
||||||
|
for (const folder of vscode.workspace.workspaceFolders ?? []) {
|
||||||
|
const p = normPath(folder.uri.fsPath);
|
||||||
|
const match = this.store.findWorktreeByPath(p);
|
||||||
|
if (match) return match.repoId;
|
||||||
|
const repo = this.store.listRepos().find((r) => normPath(r.path) === p);
|
||||||
|
if (repo) return repo.id;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Met en évidence dans l'arbre le worktree du premier dossier ouvert qui matche. */
|
||||||
|
revealCurrent(): void {
|
||||||
|
if (!this.treeView.visible) return;
|
||||||
|
for (const folder of vscode.workspace.workspaceFolders ?? []) {
|
||||||
|
const match = this.store.findWorktreeByPath(normPath(folder.uri.fsPath));
|
||||||
|
if (!match) continue;
|
||||||
|
const node = this.provider.worktreeNode(match.repoId, match.worktree.path);
|
||||||
|
if (node) {
|
||||||
|
void this.treeView.reveal(node, { select: false, focus: false, expand: true }).then(undefined, () => {
|
||||||
|
/* reveal est best-effort : un échec (nœud pas encore matérialisé) n'est pas bloquant */
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dispose(): void {
|
||||||
|
for (const d of this.disposables) d.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
22
packages/vscode/test/config.test.ts
Normal file
22
packages/vscode/test/config.test.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { normalizeBaseUrl, workspaceUrl, wsUrlFromBase } from '../src/config.js';
|
||||||
|
|
||||||
|
describe('config', () => {
|
||||||
|
it('normalise la base URL (slash final, défaut)', () => {
|
||||||
|
expect(normalizeBaseUrl('http://127.0.0.1:7317/')).toBe('http://127.0.0.1:7317');
|
||||||
|
expect(normalizeBaseUrl(' http://host:8080// ')).toBe('http://host:8080');
|
||||||
|
expect(normalizeBaseUrl('')).toBe('http://127.0.0.1:7317');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dérive l’URL WebSocket (/ws, http→ws, https→wss)', () => {
|
||||||
|
expect(wsUrlFromBase('http://127.0.0.1:7317')).toBe('ws://127.0.0.1:7317/ws');
|
||||||
|
expect(wsUrlFromBase('https://box.ts.net')).toBe('wss://box.ts.net/ws');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('construit l’URL de la vue IDE web (workspaceUrl, encodage par segment)', () => {
|
||||||
|
expect(workspaceUrl('http://127.0.0.1:7317', 'repo id', '/home/user/wt')).toBe(
|
||||||
|
'http://127.0.0.1:7317/workspace/repo%20id/%2Fhome%2Fuser%2Fwt',
|
||||||
|
);
|
||||||
|
expect(workspaceUrl('https://box.ts.net/', 'r', '/a/b')).toBe('https://box.ts.net/workspace/r/%2Fa%2Fb');
|
||||||
|
});
|
||||||
|
});
|
||||||
78
packages/vscode/test/rest-client.test.ts
Normal file
78
packages/vscode/test/rest-client.test.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import { RestClient, RestError } from '../src/api/rest-client.js';
|
||||||
|
|
||||||
|
type Captured = { url: string; init: RequestInit };
|
||||||
|
|
||||||
|
function fakeFetch(response: { ok: boolean; status: number; body: unknown }, captured: Captured[]) {
|
||||||
|
return vi.fn(async (url: string, init: RequestInit) => {
|
||||||
|
captured.push({ url, init });
|
||||||
|
return {
|
||||||
|
ok: response.ok,
|
||||||
|
status: response.status,
|
||||||
|
json: async () => response.body,
|
||||||
|
} as unknown as Response;
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RestClient', () => {
|
||||||
|
it('appelle /api/v1/auth/me avec le header Bearer', async () => {
|
||||||
|
const captured: Captured[] = [];
|
||||||
|
const rest = new RestClient(
|
||||||
|
{ baseUrl: 'http://127.0.0.1:7317/', token: 'arb_secret' },
|
||||||
|
fakeFetch({ ok: true, status: 200, body: { ok: true, tokenId: 't', tokenLabel: 'l', serverVersion: '1.8.0' } }, captured),
|
||||||
|
);
|
||||||
|
const me = await rest.me();
|
||||||
|
expect(me.serverVersion).toBe('1.8.0');
|
||||||
|
expect(captured[0]?.url).toBe('http://127.0.0.1:7317/api/v1/auth/me');
|
||||||
|
const headers = captured[0]?.init.headers as Record<string, string>;
|
||||||
|
expect(headers.Authorization).toBe('Bearer arb_secret');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalise les erreurs serveur en RestError (code + status)', async () => {
|
||||||
|
const rest = new RestClient(
|
||||||
|
{ baseUrl: 'http://127.0.0.1:7317', token: 'bad' },
|
||||||
|
fakeFetch({ ok: false, status: 401, body: { error: { code: 'BAD_TOKEN', message: 'invalid token' } } }, []),
|
||||||
|
);
|
||||||
|
await expect(rest.me()).rejects.toMatchObject({ code: 'BAD_TOKEN', status: 401 });
|
||||||
|
await expect(rest.me()).rejects.toBeInstanceOf(RestError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encode les ids dans les chemins et envoie le corps JSON', async () => {
|
||||||
|
const captured: Captured[] = [];
|
||||||
|
const rest = new RestClient(
|
||||||
|
{ baseUrl: 'http://h:1', token: 't' },
|
||||||
|
fakeFetch({ ok: true, status: 200, body: { worktree: {} } }, captured),
|
||||||
|
);
|
||||||
|
await rest.commitWorktree('repo id', { path: '/w', message: 'msg' });
|
||||||
|
expect(captured[0]?.url).toBe('http://h:1/api/v1/repos/repo%20id/worktrees/commit');
|
||||||
|
expect(captured[0]?.init.method).toBe('POST');
|
||||||
|
expect(JSON.parse(String(captured[0]?.init.body))).toEqual({ path: '/w', message: 'msg' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetch/pull worktree : chemins et corps', async () => {
|
||||||
|
const captured: Captured[] = [];
|
||||||
|
const rest = new RestClient(
|
||||||
|
{ baseUrl: 'http://h:1', token: 't' },
|
||||||
|
fakeFetch({ ok: true, status: 200, body: { worktree: {} } }, captured),
|
||||||
|
);
|
||||||
|
await rest.fetchWorktree('r', { path: '/w' });
|
||||||
|
await rest.pullWorktree('r', { path: '/w', mode: 'rebase' });
|
||||||
|
expect(captured[0]?.url).toBe('http://h:1/api/v1/repos/r/worktrees/fetch');
|
||||||
|
expect(captured[1]?.url).toBe('http://h:1/api/v1/repos/r/worktrees/pull');
|
||||||
|
expect(JSON.parse(String(captured[1]?.init.body))).toEqual({ path: '/w', mode: 'rebase' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('listSessions construit la query includeHidden/includeArchived', async () => {
|
||||||
|
const captured: Captured[] = [];
|
||||||
|
const rest = new RestClient(
|
||||||
|
{ baseUrl: 'http://h:1', token: 't' },
|
||||||
|
fakeFetch({ ok: true, status: 200, body: { sessions: [] } }, captured),
|
||||||
|
);
|
||||||
|
await rest.listSessions();
|
||||||
|
await rest.listSessions({ includeArchived: true });
|
||||||
|
await rest.listSessions({ includeHidden: true, includeArchived: true });
|
||||||
|
expect(captured[0]?.url).toBe('http://h:1/api/v1/sessions');
|
||||||
|
expect(captured[1]?.url).toBe('http://h:1/api/v1/sessions?includeArchived=true');
|
||||||
|
expect(captured[2]?.url).toBe('http://h:1/api/v1/sessions?includeHidden=true&includeArchived=true');
|
||||||
|
});
|
||||||
|
});
|
||||||
24
packages/vscode/test/session-bridge.test.ts
Normal file
24
packages/vscode/test/session-bridge.test.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { StreamingUtf8Decoder } from '../src/terminal/session-bridge.js';
|
||||||
|
|
||||||
|
describe('StreamingUtf8Decoder', () => {
|
||||||
|
it('recompose un caractère UTF-8 coupé en frontière de frame', () => {
|
||||||
|
const dec = new StreamingUtf8Decoder();
|
||||||
|
// 'é' = 0xC3 0xA9, coupé en deux frames
|
||||||
|
expect(dec.decode(new Uint8Array([0xc3]))).toBe('');
|
||||||
|
expect(dec.decode(new Uint8Array([0xa9]))).toBe('é');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('décode l’ASCII normalement', () => {
|
||||||
|
const dec = new StreamingUtf8Decoder();
|
||||||
|
expect(dec.decode(new Uint8Array([0x6c, 0x73, 0x0a]))).toBe('ls\n');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reset() vide l’état partiel', () => {
|
||||||
|
const dec = new StreamingUtf8Decoder();
|
||||||
|
expect(dec.decode(new Uint8Array([0xe2, 0x9c]))).toBe(''); // début d’un ✓ (3 octets)
|
||||||
|
dec.reset();
|
||||||
|
// après reset, l’octet partiel est oublié → un nouveau caractère complet décode proprement
|
||||||
|
expect(dec.decode(new Uint8Array([0x41]))).toBe('A');
|
||||||
|
});
|
||||||
|
});
|
||||||
103
packages/vscode/test/store.test.ts
Normal file
103
packages/vscode/test/store.test.ts
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { RepoSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import { Store } from '../src/state/store.js';
|
||||||
|
|
||||||
|
function repo(id: string): RepoSummary {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
path: `/code/${id}`,
|
||||||
|
label: id,
|
||||||
|
defaultBranch: 'main',
|
||||||
|
postCreateHooks: [],
|
||||||
|
preTrust: false,
|
||||||
|
createdAt: '2026-01-01T00:00:00Z',
|
||||||
|
valid: true,
|
||||||
|
hidden: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function worktree(repoId: string, path: string, branch: string): WorktreeSummary {
|
||||||
|
return {
|
||||||
|
repoId,
|
||||||
|
path,
|
||||||
|
branch,
|
||||||
|
head: 'abcdef0',
|
||||||
|
detached: false,
|
||||||
|
locked: false,
|
||||||
|
prunable: false,
|
||||||
|
isMain: branch === 'main',
|
||||||
|
git: { ahead: 0, behind: 0, dirtyCount: 0, upstream: null },
|
||||||
|
sessions: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function session(id: string, cwd: string, over: Partial<SessionSummary> = {}): SessionSummary {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
cwd,
|
||||||
|
command: 'claude',
|
||||||
|
title: null,
|
||||||
|
status: 'running',
|
||||||
|
live: true,
|
||||||
|
createdAt: '2026-01-01T00:00:00Z',
|
||||||
|
endedAt: null,
|
||||||
|
exitCode: null,
|
||||||
|
clients: 0,
|
||||||
|
source: 'managed',
|
||||||
|
claudeSessionId: null,
|
||||||
|
pid: 123,
|
||||||
|
resumable: false,
|
||||||
|
attachable: true,
|
||||||
|
registryStatus: null,
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Store', () => {
|
||||||
|
it('corrèle les sessions au worktree par cwd et filtre les externes', () => {
|
||||||
|
const store = new Store();
|
||||||
|
store.applyWorktree({ type: 'repo_update', repo: repo('app') });
|
||||||
|
store.applyWorktree({ type: 'worktree_update', repoId: 'app', worktree: worktree('app', '/code/app', 'main') });
|
||||||
|
|
||||||
|
store.applySession({ type: 'session_update', session: session('s1', '/code/app') });
|
||||||
|
store.applySession({ type: 'session_update', session: session('s2', '/code/app', { source: 'discovered' }) });
|
||||||
|
|
||||||
|
// externes masquées par défaut
|
||||||
|
expect(store.sessionsForWorktree('/code/app').map((s) => s.id)).toEqual(['s1']);
|
||||||
|
store.setShowExternalSessions(true);
|
||||||
|
expect(store.sessionsForWorktree('/code/app').map((s) => s.id).sort()).toEqual(['s1', 's2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('liste les repos visibles, triés', () => {
|
||||||
|
const store = new Store();
|
||||||
|
store.applyWorktree({ type: 'repo_update', repo: { ...repo('b'), label: 'beta' } });
|
||||||
|
store.applyWorktree({ type: 'repo_update', repo: { ...repo('a'), label: 'alpha' } });
|
||||||
|
store.applyWorktree({ type: 'repo_update', repo: { ...repo('h'), label: 'hidden', hidden: true } });
|
||||||
|
expect(store.listRepos().map((r) => r.label)).toEqual(['alpha', 'beta']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('session_exit marque la session morte', () => {
|
||||||
|
const store = new Store();
|
||||||
|
store.applySession({ type: 'session_update', session: session('s1', '/x') });
|
||||||
|
store.applySession({ type: 'session_exit', sessionId: 's1', exitCode: 0, signal: null });
|
||||||
|
expect(store.getSession('s1')?.live).toBe(false);
|
||||||
|
expect(store.getSession('s1')?.status).toBe('exited');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waitingSessions ne retient que les sessions live en attente', () => {
|
||||||
|
const store = new Store();
|
||||||
|
store.applySession({ type: 'session_update', session: session('s1', '/x', { activity: 'waiting' }) });
|
||||||
|
store.applySession({ type: 'session_update', session: session('s2', '/y', { activity: 'busy' }) });
|
||||||
|
store.applySession({ type: 'session_update', session: session('s3', '/z', { activity: 'waiting', live: false, status: 'exited' }) });
|
||||||
|
expect(store.waitingSessions().map((s) => s.id)).toEqual(['s1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('worktree_removed retire le worktree', () => {
|
||||||
|
const store = new Store();
|
||||||
|
store.applyWorktree({ type: 'repo_update', repo: repo('app') });
|
||||||
|
store.applyWorktree({ type: 'worktree_update', repoId: 'app', worktree: worktree('app', '/code/app-wt', 'feat') });
|
||||||
|
expect(store.listWorktrees('app')).toHaveLength(1);
|
||||||
|
store.applyWorktree({ type: 'worktree_removed', repoId: 'app', path: '/code/app-wt' });
|
||||||
|
expect(store.listWorktrees('app')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user