Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc8c7c9534 | ||
|
|
bdec8d6ad0 | ||
|
|
8aea0ae32d | ||
|
|
9390b62249 | ||
|
|
c6deded0c6 | ||
|
|
ce224fd470 |
@@ -2,10 +2,10 @@
|
|||||||
# daemon qui écoute v*, et du VSIX qui écoute vscode-v*).
|
# daemon qui écoute v*, et du VSIX qui écoute vscode-v*).
|
||||||
#
|
#
|
||||||
# Linux (AppImage + deb) : toujours automatisé.
|
# Linux (AppImage + deb) : toujours automatisé.
|
||||||
# Windows (NSIS + portable) : job dédié, ACTIVÉ par la variable de dépôt ENABLE_WINDOWS_BUILD=true une
|
# Windows (NSIS + portable) : job RETIRÉ tant qu'aucun runner `windows-latest` n'est enregistré sur le
|
||||||
# fois qu'un runner labellisé `windows-latest` est enregistré sur le forge. Procédure complète dans
|
# forge. Un job conditionné par une variable de dépôt ne suffisait pas : la release entière tombait
|
||||||
# docs/CI_RUNNERS.md. Tant que la variable est absente, le job est sauté et la release Linux part
|
# en erreur. Le repli est un build manuel attaché à la release. Pour le rétablir : enregistrer un
|
||||||
# normalement ; le repli reste un build manuel attaché à la release.
|
# runner (docs/CI_RUNNERS.md) puis restaurer le job depuis l'historique git (tag desktop-v0.2.3).
|
||||||
# Le cross-build depuis Linux est IMPOSSIBLE : node-pty ne copie conpty.dll / OpenConsole.exe que si
|
# Le cross-build depuis Linux est IMPOSSIBLE : node-pty ne copie conpty.dll / OpenConsole.exe que si
|
||||||
# l'hôte de build est Windows, et son tarball ne contient que les prebuilds linux.
|
# l'hôte de build est Windows, et son tarball ne contient que les prebuilds linux.
|
||||||
# macOS (dmg + zip) : non automatisé (aucun runner) ; build manuel documenté dans le README desktop.
|
# macOS (dmg + zip) : non automatisé (aucun runner) ; build manuel documenté dans le README desktop.
|
||||||
@@ -86,65 +86,12 @@ jobs:
|
|||||||
packages/desktop/release/latest-linux.yml \
|
packages/desktop/release/latest-linux.yml \
|
||||||
packages/desktop/release/SHA256SUMS-linux.txt
|
packages/desktop/release/SHA256SUMS-linux.txt
|
||||||
|
|
||||||
windows:
|
# Le job Windows (NSIS + portable) est RETIRÉ pour le moment : aucun runner Windows n'est
|
||||||
name: Build Windows (NSIS + portable)
|
# enregistré sur ce Gitea, et `runs-on: windows-latest` fait échouer la release entière au lieu
|
||||||
# Activé par la variable de dépôt ENABLE_WINDOWS_BUILD (voir docs/CI_RUNNERS.md). Sans runner
|
# d'être simplement ignoré. Le job complet reste dans l'historique git (dernier état : tag
|
||||||
# Windows enregistré, un job non conditionné resterait en attente indéfiniment et bloquerait la
|
# desktop-v0.2.3) et la procédure d'enregistrement d'un runner est dans docs/CI_RUNNERS.md : le
|
||||||
# release entière.
|
# rétablir revient à restaurer ce job, puis à réactiver le téléchargement de son artefact et ses
|
||||||
if: vars.ENABLE_WINDOWS_BUILD == 'true'
|
# assets dans le canal flottant ci-dessous.
|
||||||
runs-on: windows-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: ${{ env.NODE_VERSION }}
|
|
||||||
- name: Verify tag matches desktop version
|
|
||||||
if: github.event_name == 'push'
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
pkg=$(node -p "require('./packages/desktop/package.json').version")
|
|
||||||
tag="${GITHUB_REF_NAME#desktop-v}"
|
|
||||||
if [ "$pkg" != "$tag" ]; then
|
|
||||||
echo "ERREUR: tag '$tag' != version desktop '$pkg'"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "OK: tag $tag == version $pkg"
|
|
||||||
- run: npm ci
|
|
||||||
- name: Install desktop deps
|
|
||||||
shell: bash
|
|
||||||
run: cd packages/desktop && npm ci
|
|
||||||
# `dist:win` sur hôte Windows : c'est le SEUL chemin qui produit un node-pty utilisable (ConPTY,
|
|
||||||
# conpty.dll + OpenConsole.exe copiés par le post-install de node-pty).
|
|
||||||
- name: Build installers
|
|
||||||
shell: bash
|
|
||||||
run: cd packages/desktop && npm run dist:win
|
|
||||||
- name: Compute checksums
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
cd packages/desktop/release
|
|
||||||
sha256sum *.exe > SHA256SUMS-windows.txt
|
|
||||||
cat SHA256SUMS-windows.txt
|
|
||||||
- uses: actions/upload-artifact@v3
|
|
||||||
with:
|
|
||||||
name: desktop-windows
|
|
||||||
path: |
|
|
||||||
packages/desktop/release/*.exe
|
|
||||||
packages/desktop/release/*.blockmap
|
|
||||||
packages/desktop/release/latest.yml
|
|
||||||
packages/desktop/release/SHA256SUMS-windows.txt
|
|
||||||
# Pas de continue-on-error : cf. la note du job Linux.
|
|
||||||
- name: Attach installers to the tag release
|
|
||||||
if: github.event_name == 'push'
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
RELEASE_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
||||||
run: |
|
|
||||||
version=$(node -p "require('./packages/desktop/package.json').version")
|
|
||||||
bash .gitea/scripts/attach-release-assets.sh "${GITHUB_REF_NAME}" "Arboretum Desktop ${version}" \
|
|
||||||
packages/desktop/release/*.exe \
|
|
||||||
packages/desktop/release/*.blockmap \
|
|
||||||
packages/desktop/release/latest.yml \
|
|
||||||
packages/desktop/release/SHA256SUMS-windows.txt
|
|
||||||
|
|
||||||
# Canal d'auto-update : electron-updater interroge une URL FIXE
|
# Canal d'auto-update : electron-updater interroge une URL FIXE
|
||||||
# (.../releases/download/desktop-latest, cf. electron-builder.yml). Ce tag flottant doit donc exister
|
# (.../releases/download/desktop-latest, cf. electron-builder.yml). Ce tag flottant doit donc exister
|
||||||
@@ -164,13 +111,6 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
name: desktop-linux
|
name: desktop-linux
|
||||||
path: dl
|
path: dl
|
||||||
# Les artefacts Windows n'existent que si le job correspondant a tourné : téléchargement toléré
|
|
||||||
# en échec pour ne jamais bloquer la publication du canal Linux.
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
continue-on-error: true
|
|
||||||
with:
|
|
||||||
name: desktop-windows
|
|
||||||
path: dl
|
|
||||||
# On repart d'une release flottante VIERGE : sinon les assets de la version précédente y
|
# On repart d'une release flottante VIERGE : sinon les assets de la version précédente y
|
||||||
# restent (mêmes noms de fichiers uniquement remplacés, un ancien numéro de version subsisterait).
|
# restent (mêmes noms de fichiers uniquement remplacés, un ancien numéro de version subsisterait).
|
||||||
# La recréation est faite par le script suivant, via l'API (Gitea crée le tag au besoin).
|
# La recréation est faite par le script suivant, via l'API (Gitea crée le tag au besoin).
|
||||||
@@ -196,4 +136,4 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
version=$(node -p "require('./packages/desktop/package.json').version")
|
version=$(node -p "require('./packages/desktop/package.json').version")
|
||||||
bash .gitea/scripts/attach-release-assets.sh desktop-latest "Arboretum Desktop (latest, ${version})" \
|
bash .gitea/scripts/attach-release-assets.sh desktop-latest "Arboretum Desktop (latest, ${version})" \
|
||||||
dl/*.AppImage dl/*.deb dl/*.exe dl/*.blockmap dl/latest-linux.yml dl/latest.yml dl/SHA256SUMS-*.txt
|
dl/*.AppImage dl/*.deb dl/*.blockmap dl/latest-linux.yml dl/SHA256SUMS-*.txt
|
||||||
|
|||||||
@@ -34,3 +34,6 @@ CLAUDE.md
|
|||||||
# Spike scratch output
|
# Spike scratch output
|
||||||
spikes/**/tmp/
|
spikes/**/tmp/
|
||||||
spikes/**/captures/
|
spikes/**/captures/
|
||||||
|
|
||||||
|
# captures des scripts de verification visuelle (verify-ui.mjs)
|
||||||
|
.ui-shots/
|
||||||
|
|||||||
@@ -333,6 +333,7 @@ Variables d'environnement :
|
|||||||
| `ARBORETUM_EMIT_TOKEN_FD` | daemon | Écrit le jeton d'accès sur ce descripteur de fichier au démarrage. Utilisé par l'app de bureau pour s'auto-connecter ; pas destiné à un usage manuel. |
|
| `ARBORETUM_EMIT_TOKEN_FD` | daemon | Écrit le jeton d'accès sur ce descripteur de fichier au démarrage. Utilisé par l'app de bureau pour s'auto-connecter ; pas destiné à un usage manuel. |
|
||||||
| `XDG_DATA_HOME` | daemon | Racine du répertoire de données (voir ci-dessus). |
|
| `XDG_DATA_HOME` | daemon | Racine du répertoire de données (voir ci-dessus). |
|
||||||
| `ARBORETUM_SHELL` | daemon (Windows) | Shell utilisé pour les commandes de projet. Défaut `powershell.exe`. |
|
| `ARBORETUM_SHELL` | daemon (Windows) | Shell utilisé pour les commandes de projet. Défaut `powershell.exe`. |
|
||||||
|
| `ARBORETUM_DESKTOP_PORT` | app de bureau | Port sur lequel l'app de bureau lance son propre daemon. Défaut `7317`. À définir quand un autre Arboretum occupe ce port en permanence (service installé par `arboretum install`, ou daemon lancé en terminal). |
|
||||||
|
|
||||||
Les réglages au-delà des flags CLI (les répertoires qu'Arboretum scanne pour trouver des repos et à quelle fréquence, le chemin et le home du binaire `claude`, et les fenêtres de rétention / purge des sessions) vivent dans les **Réglages** de l'UI. Ils sont diffusés via le WebSocket, donc chaque navigateur connecté reflète un changement en temps réel, sans rechargement.
|
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.
|
||||||
|
|
||||||
|
|||||||
@@ -333,6 +333,7 @@ Environment variables:
|
|||||||
| `ARBORETUM_EMIT_TOKEN_FD` | daemon | Write the access token to this file descriptor at start-up. Used by the desktop app to sign itself in; not meant for manual use. |
|
| `ARBORETUM_EMIT_TOKEN_FD` | daemon | Write the access token to this file descriptor at start-up. Used by the desktop app to sign itself in; not meant for manual use. |
|
||||||
| `XDG_DATA_HOME` | daemon | Root of the data directory (see above). |
|
| `XDG_DATA_HOME` | daemon | Root of the data directory (see above). |
|
||||||
| `ARBORETUM_SHELL` | daemon (Windows) | Shell used to run project commands. Default `powershell.exe`. |
|
| `ARBORETUM_SHELL` | daemon (Windows) | Shell used to run project commands. Default `powershell.exe`. |
|
||||||
|
| `ARBORETUM_DESKTOP_PORT` | desktop app | Port the desktop app starts its own daemon on. Default `7317`. Set it when another Arboretum permanently holds that port (a service installed with `arboretum install`, or one you run in a terminal). |
|
||||||
|
|
||||||
Settings beyond CLI flags (the directories Arboretum scans for repos and how often, the `claude` binary path and home, and the session retention / purge windows) live in **Settings** in the UI. They are broadcast over the WebSocket, so every connected browser reflects a change in real time, no reload needed.
|
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.
|
||||||
|
|
||||||
|
|||||||
+8
-4
@@ -22,12 +22,16 @@ Un build produit sous Wine serait donc installable mais inutilisable. C'est pour
|
|||||||
| Plateforme | Runner | Build |
|
| Plateforme | Runner | Build |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Linux | `ubuntu-latest` (déjà en place) | automatique à chaque tag `desktop-v*` |
|
| Linux | `ubuntu-latest` (déjà en place) | automatique à chaque tag `desktop-v*` |
|
||||||
| Windows | **à enregistrer** | job `windows`, activé par la variable `ENABLE_WINDOWS_BUILD` |
|
| Windows | **à enregistrer** | job **retiré** du workflow ; manuel (`npm run dist:win` sur Windows) |
|
||||||
| macOS | aucun | manuel (`npm run dist:mac` sur un Mac) |
|
| macOS | aucun | manuel (`npm run dist:mac` sur un Mac) |
|
||||||
|
|
||||||
Le job Windows est conditionné par `if: vars.ENABLE_WINDOWS_BUILD == 'true'`. Tant que la variable
|
Le job Windows a d'abord été gardé dans le workflow, conditionné par
|
||||||
n'existe pas, le job est **sauté** : la release Linux part normalement. Sans cette condition, un job
|
`if: vars.ENABLE_WINDOWS_BUILD == 'true'`. Cela **n'a pas suffi** : sans runner labellisé
|
||||||
`runs-on: windows-latest` sans runner disponible resterait en attente et bloquerait la release entière.
|
`windows-latest`, la release entière tombait en erreur au lieu de sauter le job. Il est donc
|
||||||
|
**retiré** de `.gitea/workflows/desktop-release.yml`. Son dernier état complet est dans l'historique
|
||||||
|
git (tag `desktop-v0.2.3`) : après avoir enregistré le runner ci-dessous, restaurer ce job, puis
|
||||||
|
remettre dans `latest-channel` le `download-artifact` de `desktop-windows` ainsi que
|
||||||
|
`dl/*.exe dl/latest.yml` dans la liste d'assets du canal flottant.
|
||||||
|
|
||||||
## 1. Préparer la machine Windows
|
## 1. Préparer la machine Windows
|
||||||
|
|
||||||
|
|||||||
Generated
+1
-1
@@ -7933,7 +7933,7 @@
|
|||||||
},
|
},
|
||||||
"packages/server": {
|
"packages/server": {
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "3.5.1",
|
"version": "3.7.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/cookie": "^11.0.0",
|
"@fastify/cookie": "^11.0.0",
|
||||||
|
|||||||
@@ -4,6 +4,36 @@ Notable changes to the Arboretum desktop app (`packages/desktop`). The daemon an
|
|||||||
extension keep their own changelogs in `packages/server/CHANGELOG.md` and
|
extension keep their own changelogs in `packages/server/CHANGELOG.md` and
|
||||||
`packages/vscode/CHANGELOG.md`.
|
`packages/vscode/CHANGELOG.md`.
|
||||||
|
|
||||||
|
## 0.2.4
|
||||||
|
|
||||||
|
Ships the daemon 3.7.0: terminals no longer go black, they can sit side by side in resizable columns,
|
||||||
|
and the Changes view follows the terminal you are working in. This release also carries the start-up
|
||||||
|
fixes below, which is what makes an update installed over a running app recover on its own.
|
||||||
|
|
||||||
|
- **The app could refuse to start after an update, silently.** Installing a new version replaces the
|
||||||
|
files on disk but leaves the running app alone: its daemon kept port 7317, so the version you just
|
||||||
|
installed hit `EADDRINUSE`, its daemon died before the handshake, and the shell logged the failure to a
|
||||||
|
console nobody sees and quit. Clicking the launcher appeared to do nothing at all. Three fixes:
|
||||||
|
- **Every start-up failure now opens a dialog** with *Retry / Show log / Quit* instead of vanishing,
|
||||||
|
and the daemon's output is kept in `<userData>/logs/daemon.log`. A daemon that dies *after* start-up
|
||||||
|
is reported too, with an offer to restart it, instead of leaving a dead window on screen.
|
||||||
|
- **A busy port is diagnosed, not just fatal** (`src/main/port-guard.ts`). The daemon we spawn is
|
||||||
|
recorded in `<userData>/daemon/daemon.json`, so an *orphaned* daemon (its Electron gone after a
|
||||||
|
crash, a `kill -9` or an upgrade) is reclaimed - SIGTERM then SIGKILL, waiting for the port to be
|
||||||
|
effectively free - while a live sibling instance or third-party server is reported with the action
|
||||||
|
that unblocks it, and never killed.
|
||||||
|
- **An update installed while the app runs is announced** (`src/main/upgrade-watch.ts`). Until now the
|
||||||
|
single-instance lock quietly routed you back to the old version's window; the shell now notices its
|
||||||
|
own binary changed on disk and offers *Restart now*, which stops the daemon before relaunching.
|
||||||
|
- **`ARBORETUM_DESKTOP_PORT`** picks another port, for machines where a service or terminal daemon owns
|
||||||
|
7317 permanently.
|
||||||
|
|
||||||
|
## 0.2.3
|
||||||
|
|
||||||
|
Ships the daemon 3.6.0. Files open again (the editor area could stay blank), and uncommitted work
|
||||||
|
gets a real surface in the centre of the IDE: one block per project, with staging, commit and push.
|
||||||
|
The Electron shell itself is unchanged.
|
||||||
|
|
||||||
## 0.2.2
|
## 0.2.2
|
||||||
|
|
||||||
- **Clipboard bridge.** The renderer cannot use `navigator.clipboard` (Electron rejects it with
|
- **Clipboard bridge.** The renderer cannot use `navigator.clipboard` (Electron rejects it with
|
||||||
|
|||||||
@@ -91,6 +91,44 @@ then "Open", or run `xattr -dr com.apple.quarantine /Applications/Arboretum.app`
|
|||||||
`/usr/local/bin`, `/opt/homebrew/bin`, `~/.local/bin`; on Windows `%LOCALAPPDATA%\Programs` and
|
`/usr/local/bin`, `/opt/homebrew/bin`, `~/.local/bin`; on Windows `%LOCALAPPDATA%\Programs` and
|
||||||
`%APPDATA%\npm`, where the Claude CLI and global npm binaries actually live.
|
`%APPDATA%\npm`, where the Claude CLI and global npm binaries actually live.
|
||||||
|
|
||||||
|
## Startup, and what happens when it fails
|
||||||
|
|
||||||
|
The shell owns the daemon: it spawns it on **port 7317** (`ARBORETUM_DESKTOP_PORT` overrides), waits for
|
||||||
|
the handshake on fd 3, seeds the session cookie, then loads the SPA. Since a fixed port is easy to hold
|
||||||
|
hostage, the port is checked *before* spawning (`src/main/port-guard.ts`) and the outcome decides:
|
||||||
|
|
||||||
|
| Who holds the port | What the app does |
|
||||||
|
| --- | --- |
|
||||||
|
| Nobody | Starts normally. |
|
||||||
|
| **Our own daemon, orphaned** (its Electron died: crash, `kill -9`, package upgrade) | Reclaims it: SIGTERM, then SIGKILL, waiting for the port to be *effectively* free, then starts. |
|
||||||
|
| **Another live instance** of the app | Says so, and points at the tray where that window is hiding. Never kills it. |
|
||||||
|
| A third party (`arboretum install` service, `npx @johanleroy/git-arboretum`, unrelated software) | Says so, and suggests stopping it or setting `ARBORETUM_DESKTOP_PORT`. |
|
||||||
|
|
||||||
|
Ownership is recorded in `<userData>/daemon/daemon.json` (`{pid, ownerPid, port}`): a live daemon whose
|
||||||
|
`ownerPid` is gone is an orphan, one whose owner is alive is another instance. Every failure now opens a
|
||||||
|
dialog with **Retry / Show log / Quit** instead of quitting silently, and the daemon's output is kept in
|
||||||
|
`<userData>/logs/daemon.log`. If the daemon dies *after* startup, the app offers to restart it rather
|
||||||
|
than leaving a dead window on screen.
|
||||||
|
|
||||||
|
`<userData>` is `~/.config/Arboretum` (Linux), `~/Library/Application Support/Arboretum` (macOS),
|
||||||
|
`%APPDATA%\Arboretum` (Windows).
|
||||||
|
|
||||||
|
## Installing a new version
|
||||||
|
|
||||||
|
Installers replace the files on disk; they never touch the running process. So after a `dpkg -i` (or an
|
||||||
|
NSIS run) **the open window keeps serving the old version**, and its daemon keeps port 7317 - which used
|
||||||
|
to make the freshly installed version unable to start at all.
|
||||||
|
|
||||||
|
The recommended order is therefore either one of:
|
||||||
|
|
||||||
|
1. Quit Arboretum from the tray, then install, then launch. Clean, nothing to think about.
|
||||||
|
2. Install while it runs, then click the launcher or the tray icon: the shell notices that its own
|
||||||
|
binary changed on disk (`src/main/upgrade-watch.ts`) and offers **Restart now**, which stops the
|
||||||
|
daemon before relaunching, so the new version finds its port free.
|
||||||
|
|
||||||
|
Answering *Later* keeps the old window; the prompt comes back only if yet another version is installed.
|
||||||
|
The check is inert in dev (`app.isPackaged` is false).
|
||||||
|
|
||||||
## Auto-update
|
## Auto-update
|
||||||
|
|
||||||
electron-builder emits `latest*.yml` next to the artifacts and `electron-updater` reads them from a
|
electron-builder emits `latest*.yml` next to the artifacts and `electron-updater` reads them from a
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@arboretum/desktop",
|
"name": "@arboretum/desktop",
|
||||||
"version": "0.2.2",
|
"version": "0.2.4",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@arboretum/desktop",
|
"name": "@arboretum/desktop",
|
||||||
"version": "0.2.2",
|
"version": "0.2.4",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.10.0",
|
"@types/node": "^22.10.0",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@arboretum/desktop",
|
"name": "@arboretum/desktop",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.2.2",
|
"version": "0.2.4",
|
||||||
"description": "Self-hosted multi-project AI IDE for git worktrees and Claude Code sessions",
|
"description": "Self-hosted multi-project AI IDE for git worktrees and Claude Code sessions",
|
||||||
"homepage": "https://git-arboretum.com",
|
"homepage": "https://git-arboretum.com",
|
||||||
"repository": {
|
"repository": {
|
||||||
|
|||||||
@@ -1,11 +1,31 @@
|
|||||||
import { spawn, type ChildProcess } from 'node:child_process';
|
import { spawn, type ChildProcess } from 'node:child_process';
|
||||||
import { join } from 'node:path';
|
import { createWriteStream, mkdirSync, statSync, truncateSync, type WriteStream } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
import { resolveNodeBin, resolveServerEntry } from './paths';
|
import { resolveNodeBin, resolveServerEntry } from './paths';
|
||||||
import { buildChildEnv } from './env';
|
import { buildChildEnv } from './env';
|
||||||
|
import {
|
||||||
|
classifyPortConflict,
|
||||||
|
clearDaemonRecord,
|
||||||
|
isOurDaemonProcess,
|
||||||
|
isPortFree,
|
||||||
|
processAlive,
|
||||||
|
readDaemonRecord,
|
||||||
|
reclaimOrphanDaemon,
|
||||||
|
writeDaemonRecord,
|
||||||
|
} from './port-guard';
|
||||||
|
import { DaemonStartError } from './start-failure';
|
||||||
|
|
||||||
|
const HANDSHAKE_TIMEOUT_MS = 30_000;
|
||||||
|
/** Lignes de sortie conservées pour le diagnostic affiché en cas d'échec. */
|
||||||
|
const LOG_TAIL_LINES = 40;
|
||||||
|
/** Au-delà, le journal est tronqué au démarrage (fichier de dépannage, pas d'archive). */
|
||||||
|
const MAX_LOG_BYTES = 2_000_000;
|
||||||
|
|
||||||
export interface DaemonHandle {
|
export interface DaemonHandle {
|
||||||
url: string;
|
url: string;
|
||||||
token: string;
|
token: string;
|
||||||
|
/** Dernières lignes de sortie du daemon (diagnostic). */
|
||||||
|
logTail(): string;
|
||||||
stop(): Promise<void>;
|
stop(): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14,19 +34,31 @@ interface Handshake {
|
|||||||
url: string;
|
url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface StartDaemonOptions {
|
||||||
|
dataDir: string;
|
||||||
|
port: number;
|
||||||
|
/** Empreinte du daemon lancé, pour récupérer un orphelin au démarrage suivant. */
|
||||||
|
pidfile?: string;
|
||||||
|
/** Journal persistant du daemon (dépannage hors terminal). */
|
||||||
|
logFile?: string;
|
||||||
|
onLog?: (line: string) => void;
|
||||||
|
/** Appelé si le daemon s'arrête APRÈS le handshake (mort inattendue). */
|
||||||
|
onExit?: (code: number | null) => void;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lance le daemon en process enfant (Node bundlé) et attend son handshake sur le fd 3
|
* Lance le daemon en process enfant (Node bundlé) et attend son handshake sur le fd 3
|
||||||
* (ARBORETUM_EMIT_TOKEN_FD=3 côté serveur) : la réception du JSON {token,url} prouve que le
|
* (ARBORETUM_EMIT_TOKEN_FD=3 côté serveur) : la réception du JSON {token,url} prouve que le
|
||||||
* serveur écoute (le handshake est écrit après app.listen). Arrêt propre : SIGTERM puis SIGKILL.
|
* serveur écoute (le handshake est écrit après app.listen). Arrêt propre : SIGTERM puis SIGKILL.
|
||||||
|
*
|
||||||
|
* Le port est vérifié AVANT le spawn : sans ça, un daemon resté seul après un crash ou une mise à
|
||||||
|
* jour rendait l'app définitivement inutilisable (EADDRINUSE, enfant mort, aucun message).
|
||||||
*/
|
*/
|
||||||
export function startDaemon(opts: {
|
export async function startDaemon(opts: StartDaemonOptions): Promise<DaemonHandle> {
|
||||||
dataDir: string;
|
|
||||||
port: number;
|
|
||||||
onLog?: (line: string) => void;
|
|
||||||
onExit?: (code: number | null) => void;
|
|
||||||
}): Promise<DaemonHandle> {
|
|
||||||
const node = resolveNodeBin();
|
const node = resolveNodeBin();
|
||||||
const entry = resolveServerEntry();
|
const entry = resolveServerEntry();
|
||||||
|
await ensurePortAvailable(opts.port, entry, opts.pidfile);
|
||||||
|
|
||||||
const dbPath = join(opts.dataDir, 'arboretum.db');
|
const dbPath = join(opts.dataDir, 'arboretum.db');
|
||||||
const env = buildChildEnv({ XDG_DATA_HOME: opts.dataDir, ARBORETUM_EMIT_TOKEN_FD: '3' });
|
const env = buildChildEnv({ XDG_DATA_HOME: opts.dataDir, ARBORETUM_EMIT_TOKEN_FD: '3' });
|
||||||
|
|
||||||
@@ -35,18 +67,41 @@ export function startDaemon(opts: {
|
|||||||
stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
|
stdio: ['ignore', 'pipe', 'pipe', 'pipe'],
|
||||||
});
|
});
|
||||||
|
|
||||||
child.stdout?.on('data', (d: Buffer) => opts.onLog?.(d.toString()));
|
const logSink = opts.logFile ? openLogFile(opts.logFile) : null;
|
||||||
child.stderr?.on('data', (d: Buffer) => opts.onLog?.(d.toString()));
|
const tail: string[] = [];
|
||||||
|
const collect = (chunk: Buffer): void => {
|
||||||
|
const text = chunk.toString();
|
||||||
|
opts.onLog?.(text);
|
||||||
|
logSink?.write(text);
|
||||||
|
for (const line of text.split('\n')) {
|
||||||
|
if (!line.trim()) continue;
|
||||||
|
tail.push(line);
|
||||||
|
if (tail.length > LOG_TAIL_LINES) tail.shift();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const logTail = (): string => tail.join('\n');
|
||||||
|
|
||||||
|
child.stdout?.on('data', collect);
|
||||||
|
child.stderr?.on('data', collect);
|
||||||
|
|
||||||
|
if (child.pid !== undefined && opts.pidfile) {
|
||||||
|
writeDaemonRecord(opts.pidfile, { pid: child.pid, ownerPid: process.pid, port: opts.port });
|
||||||
|
}
|
||||||
|
|
||||||
let stopped = false;
|
let stopped = false;
|
||||||
const stop = (): Promise<void> =>
|
const stop = (): Promise<void> =>
|
||||||
new Promise((resolve) => {
|
new Promise((resolve) => {
|
||||||
if (stopped || child.exitCode !== null) return resolve();
|
const done = (): void => {
|
||||||
|
if (opts.pidfile) clearDaemonRecord(opts.pidfile);
|
||||||
|
logSink?.end();
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
if (stopped || child.exitCode !== null) return done();
|
||||||
stopped = true;
|
stopped = true;
|
||||||
const killTimer = setTimeout(() => child.kill('SIGKILL'), 3000);
|
const killTimer = setTimeout(() => child.kill('SIGKILL'), 3000);
|
||||||
child.once('exit', () => {
|
child.once('exit', () => {
|
||||||
clearTimeout(killTimer);
|
clearTimeout(killTimer);
|
||||||
resolve();
|
done();
|
||||||
});
|
});
|
||||||
child.kill('SIGTERM');
|
child.kill('SIGTERM');
|
||||||
});
|
});
|
||||||
@@ -59,16 +114,28 @@ export function startDaemon(opts: {
|
|||||||
if (settled) return;
|
if (settled) return;
|
||||||
settled = true;
|
settled = true;
|
||||||
void stop();
|
void stop();
|
||||||
reject(new Error('daemon handshake timeout'));
|
reject(new DaemonStartError('handshake', 'daemon handshake timeout', logTail()));
|
||||||
}, 30000);
|
}, HANDSHAKE_TIMEOUT_MS);
|
||||||
|
|
||||||
child.once('exit', (code) => {
|
child.once('exit', (code) => {
|
||||||
|
if (settled) {
|
||||||
|
// Mort après le handshake : l'empreinte ne décrit plus rien de vivant.
|
||||||
|
if (opts.pidfile) clearDaemonRecord(opts.pidfile);
|
||||||
opts.onExit?.(code);
|
opts.onExit?.(code);
|
||||||
if (!settled) {
|
return;
|
||||||
|
}
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
reject(new Error(`daemon exited before handshake (code ${code ?? 'null'})`));
|
if (opts.pidfile) clearDaemonRecord(opts.pidfile);
|
||||||
}
|
logSink?.end();
|
||||||
|
// Course perdue entre la vérification du port et le bind du daemon : le motif reste « port pris »,
|
||||||
|
// pas un échec de handshake opaque.
|
||||||
|
const busy = /EADDRINUSE/.test(logTail());
|
||||||
|
reject(
|
||||||
|
busy
|
||||||
|
? new DaemonStartError('port-busy-foreign', `port ${opts.port} is already in use`, logTail())
|
||||||
|
: new DaemonStartError('handshake', `daemon exited before handshake (code ${code ?? 'null'})`, logTail()),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
fd3?.on('data', (chunk: Buffer) => {
|
fd3?.on('data', (chunk: Buffer) => {
|
||||||
@@ -80,11 +147,45 @@ export function startDaemon(opts: {
|
|||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
try {
|
try {
|
||||||
const hs = JSON.parse(buf.slice(0, nl)) as Handshake;
|
const hs = JSON.parse(buf.slice(0, nl)) as Handshake;
|
||||||
resolve({ url: hs.url, token: hs.token, stop });
|
resolve({ url: hs.url, token: hs.token, logTail, stop });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
void stop();
|
void stop();
|
||||||
reject(err instanceof Error ? err : new Error(String(err)));
|
reject(new DaemonStartError('handshake', err instanceof Error ? err.message : String(err), logTail()));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Libère le port si l'occupant est un daemon à nous devenu orphelin ; sinon échoue avec un motif que
|
||||||
|
* le dialogue sait traduire en action (autre instance dans le tray, service, daemon en terminal).
|
||||||
|
*/
|
||||||
|
async function ensurePortAvailable(port: number, serverEntry: string, pidfile?: string): Promise<void> {
|
||||||
|
if (await isPortFree(port)) return;
|
||||||
|
|
||||||
|
const conflict = classifyPortConflict(pidfile ? readDaemonRecord(pidfile) : null, processAlive, port);
|
||||||
|
// La reprise exige DEUX preuves : l'empreinte désigne un daemon sans pilote, et le pid exécute
|
||||||
|
// effectivement notre serveur (un pid recyclé ne doit jamais être tué à sa place).
|
||||||
|
if (conflict.kind === 'orphan' && isOurDaemonProcess(conflict.pid, serverEntry)) {
|
||||||
|
// Daemon survivant à son Electron (crash, kill -9, paquet mis à jour) : plus personne ne le
|
||||||
|
// pilote et il tient la base ET le port. On le récupère au lieu de condamner l'app.
|
||||||
|
await reclaimOrphanDaemon(conflict.pid, port);
|
||||||
|
if (await isPortFree(port)) return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new DaemonStartError(
|
||||||
|
conflict.kind === 'other-instance' ? 'port-busy-instance' : 'port-busy-foreign',
|
||||||
|
`port ${port} is already in use`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openLogFile(path: string): WriteStream | null {
|
||||||
|
try {
|
||||||
|
mkdirSync(dirname(path), { recursive: true });
|
||||||
|
const size = statSync(path, { throwIfNoEntry: false })?.size ?? 0;
|
||||||
|
if (size > MAX_LOG_BYTES) truncateSync(path, 0);
|
||||||
|
return createWriteStream(path, { flags: 'a' });
|
||||||
|
} catch {
|
||||||
|
return null; // un journal indisponible ne doit pas empêcher le démarrage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,4 +1,13 @@
|
|||||||
import { app, BrowserWindow, session, shell, type BrowserWindowConstructorOptions, type Tray } from 'electron';
|
import {
|
||||||
|
app,
|
||||||
|
BrowserWindow,
|
||||||
|
dialog,
|
||||||
|
session,
|
||||||
|
shell,
|
||||||
|
type BrowserWindowConstructorOptions,
|
||||||
|
type Tray,
|
||||||
|
} from 'electron';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { startDaemon, type DaemonHandle } from './daemon';
|
import { startDaemon, type DaemonHandle } from './daemon';
|
||||||
import { seedSessionCookie } from './auth';
|
import { seedSessionCookie } from './auth';
|
||||||
@@ -8,6 +17,8 @@ import { installAppMenu } from './app-menu';
|
|||||||
import { registerClipboardBridge } from './clipboard';
|
import { registerClipboardBridge } from './clipboard';
|
||||||
import { initUpdater } from './updater';
|
import { initUpdater } from './updater';
|
||||||
import { resolveIconPath } from './paths';
|
import { resolveIconPath } from './paths';
|
||||||
|
import { describeStartFailure } from './start-failure';
|
||||||
|
import { installChanged, readInstallStamp, type InstallStamp } from './upgrade-watch';
|
||||||
|
|
||||||
// WM_CLASS / app_id déterministe, posé AVANT app.whenReady(). Sous Wayland (défaut Debian/GNOME)
|
// WM_CLASS / app_id déterministe, posé AVANT app.whenReady(). Sous Wayland (défaut Debian/GNOME)
|
||||||
// l'option `icon:` de BrowserWindow est ignorée : l'icône de fenêtre/dock vient du fichier .desktop
|
// l'option `icon:` de BrowserWindow est ignorée : l'icône de fenêtre/dock vient du fichier .desktop
|
||||||
@@ -17,47 +28,226 @@ import { resolveIconPath } from './paths';
|
|||||||
app.setName('Arboretum');
|
app.setName('Arboretum');
|
||||||
|
|
||||||
const PARTITION = 'persist:arboretum';
|
const PARTITION = 'persist:arboretum';
|
||||||
const PORT = 7317;
|
const DEFAULT_PORT = 7317;
|
||||||
|
const PORT = resolvePort();
|
||||||
|
|
||||||
let daemon: DaemonHandle | null = null;
|
let daemon: DaemonHandle | null = null;
|
||||||
let win: BrowserWindow | null = null;
|
let win: BrowserWindow | null = null;
|
||||||
let tray: Tray | null = null;
|
let tray: Tray | null = null;
|
||||||
let isQuitting = false;
|
let isQuitting = false;
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
|
let relaunchAfterQuit = false;
|
||||||
|
let bridgeRegistered = false;
|
||||||
|
/** Le daemon a passé son handshake : sa mort devient un incident à signaler. */
|
||||||
|
let serverReady = false;
|
||||||
|
/** Empreinte du binaire au lancement, comparée plus tard pour repérer une mise à jour installée. */
|
||||||
|
const bootStamp = readInstallStamp(process.execPath);
|
||||||
|
let dismissedStamp: InstallStamp | null = null;
|
||||||
|
let restartPromptOpen = false;
|
||||||
|
|
||||||
// Instance unique : deux instances = deux daemons/ports en conflit.
|
// Instance unique : deux instances = deux daemons/ports en conflit.
|
||||||
if (!app.requestSingleInstanceLock()) {
|
if (!app.requestSingleInstanceLock()) {
|
||||||
app.quit();
|
app.quit();
|
||||||
} else {
|
} else {
|
||||||
app.on('second-instance', showWindow);
|
app.on('second-instance', showWindow);
|
||||||
app.whenReady().then(bootstrap).catch((err: unknown) => {
|
void app.whenReady()
|
||||||
console.error('[arboretum-desktop] bootstrap failed:', err);
|
.then(startWithRetry)
|
||||||
app.quit();
|
.catch((err: unknown) => {
|
||||||
|
console.error('[arboretum-desktop] fatal:', err);
|
||||||
|
app.exit(1);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Port du daemon local. Surcharge par variable d'env pour cohabiter avec un Arboretum déjà installé
|
||||||
|
* en service (ou lancé en terminal) qui tient 7317 en permanence.
|
||||||
|
*/
|
||||||
|
function resolvePort(): number {
|
||||||
|
const n = Number(process.env.ARBORETUM_DESKTOP_PORT);
|
||||||
|
return Number.isInteger(n) && n >= 1024 && n <= 65535 ? n : DEFAULT_PORT;
|
||||||
|
}
|
||||||
|
|
||||||
|
function logFilePath(): string {
|
||||||
|
return join(app.getPath('userData'), 'logs', 'daemon.log');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Démarre l'app, et en cas d'échec propose une action au lieu de disparaître : un « rien ne se passe »
|
||||||
|
* au clic sur l'icône était le pire symptôme possible (port occupé, Node absent, base verrouillée).
|
||||||
|
*/
|
||||||
|
async function startWithRetry(): Promise<void> {
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
await bootstrap();
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[arboretum-desktop] bootstrap failed:', err);
|
||||||
|
await stopDaemonQuietly();
|
||||||
|
if ((await promptStartFailure(err)) === 'quit') {
|
||||||
|
isQuitting = true;
|
||||||
|
app.exit(1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function bootstrap(): Promise<void> {
|
async function bootstrap(): Promise<void> {
|
||||||
const dataDir = join(app.getPath('userData'), 'daemon');
|
await startServer();
|
||||||
daemon = await startDaemon({ dataDir, port: PORT, onLog: (l) => process.stdout.write(l) });
|
// Idempotent : un « Retry » après échec ne doit pas réenregistrer le pont IPC ni empiler un tray.
|
||||||
await seedSessionCookie(PARTITION, daemon.url, daemon.token);
|
if (!bridgeRegistered) {
|
||||||
registerClipboardBridge();
|
registerClipboardBridge();
|
||||||
createWindow(daemon.url);
|
bridgeRegistered = true;
|
||||||
installAppMenu({ url: daemon.url, onQuit: quitApp });
|
}
|
||||||
tray = createTray({ show: showWindow, quit: quitApp });
|
if (!win) createWindow(daemonUrl());
|
||||||
|
installAppMenu({ url: daemonUrl(), onQuit: quitApp });
|
||||||
|
if (!tray) tray = createTray({ show: showWindow, quit: quitApp });
|
||||||
initUpdater();
|
initUpdater();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Daemon + cookie de session : le strict nécessaire pour charger la SPA (aussi utilisé au redémarrage). */
|
||||||
|
async function startServer(): Promise<void> {
|
||||||
|
const dataDir = join(app.getPath('userData'), 'daemon');
|
||||||
|
daemon = await startDaemon({
|
||||||
|
dataDir,
|
||||||
|
port: PORT,
|
||||||
|
pidfile: join(dataDir, 'daemon.json'),
|
||||||
|
logFile: logFilePath(),
|
||||||
|
onLog: (l) => process.stdout.write(l),
|
||||||
|
onExit: handleDaemonExit,
|
||||||
|
});
|
||||||
|
serverReady = true;
|
||||||
|
await seedSessionCookie(PARTITION, daemon.url, daemon.token);
|
||||||
|
}
|
||||||
|
|
||||||
|
function daemonUrl(): string {
|
||||||
|
return daemon?.url ?? `http://127.0.0.1:${PORT}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function stopDaemonQuietly(): Promise<void> {
|
||||||
|
serverReady = false;
|
||||||
|
const handle = daemon;
|
||||||
|
daemon = null;
|
||||||
|
await handle?.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dialogue d'échec : motif traduit en action, avec accès au journal du daemon. */
|
||||||
|
async function promptStartFailure(err: unknown): Promise<'retry' | 'quit'> {
|
||||||
|
const { message, detail } = describeStartFailure(err, PORT);
|
||||||
|
const log = logFilePath();
|
||||||
|
for (;;) {
|
||||||
|
const buttons = existsSync(log) ? ['Retry', 'Show log', 'Quit'] : ['Retry', 'Quit'];
|
||||||
|
const { response } = await dialog.showMessageBox({
|
||||||
|
type: 'error',
|
||||||
|
title: 'Arboretum',
|
||||||
|
message,
|
||||||
|
detail,
|
||||||
|
buttons,
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: buttons.length - 1,
|
||||||
|
noLink: true,
|
||||||
|
});
|
||||||
|
if (buttons[response] === 'Show log') {
|
||||||
|
void shell.openPath(log);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return buttons[response] === 'Retry' ? 'retry' : 'quit';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mort inattendue du daemon : la fenêtre resterait affichée sur une SPA qui ne répond plus. On le dit
|
||||||
|
* et on propose de le relancer (le token change, donc cookie re-semé et fenêtre rechargée).
|
||||||
|
*/
|
||||||
|
function handleDaemonExit(code: number | null): void {
|
||||||
|
if (!serverReady || isQuitting || shuttingDown) return;
|
||||||
|
serverReady = false;
|
||||||
|
const tail = daemon?.logTail() ?? '';
|
||||||
|
daemon = null;
|
||||||
|
void promptServerStopped(code, tail);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function promptServerStopped(code: number | null, tail: string): Promise<void> {
|
||||||
|
const { response } = await dialog.showMessageBox({
|
||||||
|
type: 'error',
|
||||||
|
title: 'Arboretum',
|
||||||
|
message: 'The Arboretum server stopped',
|
||||||
|
detail: [`The local server exited (code ${code ?? 'null'}).`, tail && `Server output:\n${tail}`]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join('\n\n'),
|
||||||
|
buttons: ['Restart server', 'Quit'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 1,
|
||||||
|
noLink: true,
|
||||||
|
});
|
||||||
|
if (response !== 0) {
|
||||||
|
quitApp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (;;) {
|
||||||
|
try {
|
||||||
|
await startServer();
|
||||||
|
await win?.loadURL(`${daemonUrl()}/`);
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
await stopDaemonQuietly();
|
||||||
|
if ((await promptStartFailure(err)) === 'quit') {
|
||||||
|
quitApp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// macOS : la fenêtre est cachée (pas détruite) à la fermeture. Sans ce handler, cliquer l'icône du
|
// macOS : la fenêtre est cachée (pas détruite) à la fermeture. Sans ce handler, cliquer l'icône du
|
||||||
// Dock ne la ramenait jamais et l'app paraissait bloquée en arrière-plan.
|
// Dock ne la ramenait jamais et l'app paraissait bloquée en arrière-plan.
|
||||||
app.on('activate', showWindow);
|
app.on('activate', showWindow);
|
||||||
|
|
||||||
function showWindow(): void {
|
function showWindow(): void {
|
||||||
|
// Tray, second-instance et Dock passent tous ici : c'est le moment où l'utilisateur redemande
|
||||||
|
// l'app, donc le bon moment pour signaler une mise à jour installée entre-temps.
|
||||||
|
void maybePromptRestartAfterUpgrade();
|
||||||
if (!win) return;
|
if (!win) return;
|
||||||
if (win.isMinimized()) win.restore();
|
if (win.isMinimized()) win.restore();
|
||||||
win.show();
|
win.show();
|
||||||
win.focus();
|
win.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mise à jour installée pendant que l'app tournait : le lock d'instance unique renvoie les lancements
|
||||||
|
* suivants sur la fenêtre de l'ANCIENNE version, sans un mot, et l'utilisateur croit avoir migré.
|
||||||
|
*/
|
||||||
|
async function maybePromptRestartAfterUpgrade(): Promise<void> {
|
||||||
|
if (restartPromptOpen || isQuitting || !app.isPackaged) return;
|
||||||
|
const current = readInstallStamp(process.execPath);
|
||||||
|
if (!installChanged(bootStamp, current)) return;
|
||||||
|
if (dismissedStamp && !installChanged(dismissedStamp, current)) return;
|
||||||
|
|
||||||
|
restartPromptOpen = true;
|
||||||
|
try {
|
||||||
|
const { response } = await dialog.showMessageBox({
|
||||||
|
type: 'info',
|
||||||
|
title: 'Arboretum',
|
||||||
|
message: 'A new version of Arboretum has been installed',
|
||||||
|
detail:
|
||||||
|
`This window still runs version ${app.getVersion()}, started before the update. ` +
|
||||||
|
'Restart to load the installed version. Running sessions will be stopped.',
|
||||||
|
buttons: ['Restart now', 'Later'],
|
||||||
|
defaultId: 0,
|
||||||
|
cancelId: 1,
|
||||||
|
noLink: true,
|
||||||
|
});
|
||||||
|
if (response === 0) {
|
||||||
|
relaunchAfterQuit = true;
|
||||||
|
quitApp();
|
||||||
|
} else {
|
||||||
|
dismissedStamp = current;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
restartPromptOpen = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function quitApp(): void {
|
function quitApp(): void {
|
||||||
isQuitting = true;
|
isQuitting = true;
|
||||||
app.quit();
|
app.quit();
|
||||||
@@ -138,8 +328,12 @@ async function shutdown(): Promise<void> {
|
|||||||
await daemon?.stop();
|
await daemon?.stop();
|
||||||
} finally {
|
} finally {
|
||||||
daemon = null;
|
daemon = null;
|
||||||
|
serverReady = false;
|
||||||
tray?.destroy();
|
tray?.destroy();
|
||||||
tray = null;
|
tray = null;
|
||||||
|
// Relance demandée après une mise à jour : l'enregistrer une fois le daemon arrêté, sinon le
|
||||||
|
// nouveau process retrouverait le port occupé par l'ancien.
|
||||||
|
if (relaunchAfterQuit) app.relaunch();
|
||||||
app.quit();
|
app.quit();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { createServer } from 'node:net';
|
||||||
|
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { dirname } from 'node:path';
|
||||||
|
|
||||||
|
// Le daemon écoute sur un port FIXE (7317) : c'est ce qui rend l'URL locale mémorisable, mais aussi
|
||||||
|
// ce qui rend le démarrage fragile dès qu'un autre process le tient. Ce module répond à la seule
|
||||||
|
// question qui compte alors : qui l'occupe, et avons-nous le droit de le reprendre ?
|
||||||
|
|
||||||
|
/** Empreinte du daemon lancé par cette app : de quoi reconnaître un orphelin au démarrage suivant. */
|
||||||
|
export interface DaemonRecord {
|
||||||
|
/** pid du process Node du daemon. */
|
||||||
|
pid: number;
|
||||||
|
/** pid du process Electron qui l'a lancé : s'il est mort, le daemon n'a plus de pilote. */
|
||||||
|
ownerPid: number;
|
||||||
|
port: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type PortConflict =
|
||||||
|
/** Notre daemon, dont l'Electron parent est mort : récupérable. */
|
||||||
|
| { kind: 'orphan'; pid: number }
|
||||||
|
/** Une autre instance vivante de l'app (fenêtre probablement dans le tray). */
|
||||||
|
| { kind: 'other-instance'; pid: number }
|
||||||
|
/** Un tiers : service `arboretum install`, `npx @johanleroy/git-arboretum`, autre logiciel. */
|
||||||
|
| { kind: 'foreign' };
|
||||||
|
|
||||||
|
const RECLAIM_GRACE_MS = 3_000;
|
||||||
|
const RECLAIM_POLL_MS = 100;
|
||||||
|
|
||||||
|
/** Le port est-il libre ? Bind réel sur l'interface exacte du daemon (aucune heuristique). */
|
||||||
|
export function isPortFree(port: number, host = '127.0.0.1'): Promise<boolean> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const probe = createServer();
|
||||||
|
probe.once('error', () => resolve(false));
|
||||||
|
probe.once('listening', () => probe.close(() => resolve(true)));
|
||||||
|
probe.listen({ port, host, exclusive: true });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vivacité d'un pid. `EPERM` = process existant mais hors de notre portée, donc vivant. */
|
||||||
|
export function processAlive(pid: number): boolean {
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
||||||
|
try {
|
||||||
|
process.kill(pid, 0);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
return (err as NodeJS.ErrnoException).code === 'EPERM';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readDaemonRecord(file: string): DaemonRecord | null {
|
||||||
|
try {
|
||||||
|
const raw = JSON.parse(readFileSync(file, 'utf8')) as Partial<DaemonRecord>;
|
||||||
|
const { pid, ownerPid, port } = raw;
|
||||||
|
if (!Number.isInteger(pid) || !Number.isInteger(ownerPid) || !Number.isInteger(port)) return null;
|
||||||
|
return { pid: pid as number, ownerPid: ownerPid as number, port: port as number };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// L'empreinte est un confort de diagnostic : son écriture ne doit jamais faire échouer un démarrage.
|
||||||
|
export function writeDaemonRecord(file: string, rec: DaemonRecord): void {
|
||||||
|
try {
|
||||||
|
mkdirSync(dirname(file), { recursive: true });
|
||||||
|
writeFileSync(file, JSON.stringify(rec), 'utf8');
|
||||||
|
} catch {
|
||||||
|
/* best-effort */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearDaemonRecord(file: string): void {
|
||||||
|
try {
|
||||||
|
rmSync(file, { force: true });
|
||||||
|
} catch {
|
||||||
|
/* best-effort */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Qui tient le port ? Fonction pure (vivacité injectée) : l'empreinte du dernier daemon lancé est le
|
||||||
|
* seul élément qui distingue notre propre orphelin d'une autre instance ou d'un logiciel tiers.
|
||||||
|
* À n'appeler que sur un port déjà constaté occupé.
|
||||||
|
*/
|
||||||
|
export function classifyPortConflict(
|
||||||
|
record: DaemonRecord | null,
|
||||||
|
alive: (pid: number) => boolean,
|
||||||
|
port: number,
|
||||||
|
): PortConflict {
|
||||||
|
if (!record || record.port !== port || !alive(record.pid)) return { kind: 'foreign' };
|
||||||
|
return alive(record.ownerPid) ? { kind: 'other-instance', pid: record.pid } : { kind: 'orphan', pid: record.pid };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ligne de commande d'un pid, ou `null` si on ne peut pas la lire. Sert de preuve d'identité avant de
|
||||||
|
* tuer quoi que ce soit ; l'absence de preuve vaut refus.
|
||||||
|
*/
|
||||||
|
export function processCommandLine(pid: number): string | null {
|
||||||
|
if (!Number.isInteger(pid) || pid <= 0) return null;
|
||||||
|
try {
|
||||||
|
const res =
|
||||||
|
process.platform === 'win32'
|
||||||
|
? spawnSync(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`],
|
||||||
|
{ encoding: 'utf8', timeout: 5_000, windowsHide: true },
|
||||||
|
)
|
||||||
|
: // -ww : sortie NON tronquée. Les chemins en jeu (node bundlé + entrée du serveur dans les
|
||||||
|
// ressources de l'app) dépassent largement la largeur d'écran par défaut de ps.
|
||||||
|
spawnSync('ps', ['-ww', '-o', 'command=', '-p', String(pid)], { encoding: 'utf8', timeout: 5_000 });
|
||||||
|
const out = (res.stdout ?? '').trim();
|
||||||
|
return out.length > 0 ? out : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le pid exécute-t-il BIEN notre daemon ? Un pidfile périmé peut désigner un pid recyclé entre-temps
|
||||||
|
* par n'importe quel programme de l'utilisateur : sans cette vérification, la reprise du port se
|
||||||
|
* changerait en « tuer un process innocent ». Pas de preuve lisible = pas de reprise.
|
||||||
|
*/
|
||||||
|
export function isOurDaemonProcess(pid: number, serverEntry: string): boolean {
|
||||||
|
const cmd = processCommandLine(pid);
|
||||||
|
return cmd !== null && cmd.includes(serverEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Termine un daemon orphelin et attend la libération EFFECTIVE du port (SIGTERM, puis SIGKILL) :
|
||||||
|
* le pid disparu ne suffit pas, seul un bind réussi prouve que la voie est libre.
|
||||||
|
*/
|
||||||
|
export async function reclaimOrphanDaemon(pid: number, port: number, host = '127.0.0.1'): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
process.kill(pid, 'SIGTERM');
|
||||||
|
} catch {
|
||||||
|
return isPortFree(port, host);
|
||||||
|
}
|
||||||
|
if (await waitForPortFree(port, RECLAIM_GRACE_MS, host)) return true;
|
||||||
|
try {
|
||||||
|
process.kill(pid, 'SIGKILL');
|
||||||
|
} catch {
|
||||||
|
/* déjà parti */
|
||||||
|
}
|
||||||
|
return waitForPortFree(port, RECLAIM_GRACE_MS, host);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function waitForPortFree(port: number, timeoutMs: number, host = '127.0.0.1'): Promise<boolean> {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
for (;;) {
|
||||||
|
if (await isPortFree(port, host)) return true;
|
||||||
|
if (Date.now() >= deadline) return false;
|
||||||
|
await sleep(RECLAIM_POLL_MS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
// Un démarrage raté doit se VOIR. Avant, l'échec du bootstrap se résumait à un console.error suivi
|
||||||
|
// d'un app.quit() : depuis le lanceur du bureau, l'utilisateur cliquait et « rien ne se passait ».
|
||||||
|
|
||||||
|
export type DaemonStartFailureKind = 'port-busy-instance' | 'port-busy-foreign' | 'handshake';
|
||||||
|
|
||||||
|
/** Échec de démarrage du daemon, porteur d'un motif exploitable par le dialogue utilisateur. */
|
||||||
|
export class DaemonStartError extends Error {
|
||||||
|
constructor(
|
||||||
|
readonly kind: DaemonStartFailureKind,
|
||||||
|
message: string,
|
||||||
|
readonly logTail = '',
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'DaemonStartError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface StartFailureText {
|
||||||
|
message: string;
|
||||||
|
detail: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Texte du dialogue d'échec (en anglais : convention des messages utilisateur). Chaque motif porte
|
||||||
|
* l'action concrète qui débloque, jamais la seule trace technique.
|
||||||
|
*/
|
||||||
|
export function describeStartFailure(err: unknown, port: number): StartFailureText {
|
||||||
|
const kind = err instanceof DaemonStartError ? err.kind : 'handshake';
|
||||||
|
const tail = err instanceof DaemonStartError ? err.logTail : '';
|
||||||
|
const raw = err instanceof Error ? err.message : String(err);
|
||||||
|
|
||||||
|
if (kind === 'port-busy-instance') {
|
||||||
|
return {
|
||||||
|
message: 'Arboretum is already running',
|
||||||
|
detail:
|
||||||
|
`Another Arboretum instance is using port ${port}. Its window is probably hidden: ` +
|
||||||
|
'click the Arboretum icon in the system tray to bring it back, or quit it from there and retry. ' +
|
||||||
|
'If you just installed an update, quitting and retrying loads the new version.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kind === 'port-busy-foreign') {
|
||||||
|
return {
|
||||||
|
message: `Port ${port} is already in use`,
|
||||||
|
detail: join([
|
||||||
|
`Another program is listening on 127.0.0.1:${port}, typically an Arboretum daemon started ` +
|
||||||
|
'from a terminal (npx @johanleroy/git-arboretum) or installed as a service (arboretum install).',
|
||||||
|
`Stop it and retry, or set ARBORETUM_DESKTOP_PORT to a free port before launching the app.`,
|
||||||
|
tail && `Server output:\n${tail}`,
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: 'Arboretum could not start its local server',
|
||||||
|
detail: join([raw, tail && `Server output:\n${tail}`]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function join(parts: (string | false)[]): string {
|
||||||
|
return parts.filter((p): p is string => typeof p === 'string' && p.length > 0).join('\n\n');
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { statSync } from 'node:fs';
|
||||||
|
|
||||||
|
// Une mise à jour installée pendant que l'app tourne (dpkg -i, installeur nsis, .app remplacée)
|
||||||
|
// remplace le binaire sur disque sans toucher au process en cours. Le lock d'instance unique renvoie
|
||||||
|
// alors les lancements suivants vers la fenêtre de l'ANCIENNE version, silencieusement : l'utilisateur
|
||||||
|
// croit utiliser la nouvelle. Comparer une empreinte du binaire suffit à le détecter.
|
||||||
|
|
||||||
|
/** Empreinte du binaire installé. Un remplacement de fichier change l'inode (et souvent mtime/taille). */
|
||||||
|
export interface InstallStamp {
|
||||||
|
ino: number;
|
||||||
|
mtimeMs: number;
|
||||||
|
size: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readInstallStamp(path: string): InstallStamp | null {
|
||||||
|
try {
|
||||||
|
const st = statSync(path);
|
||||||
|
return { ino: Number(st.ino), mtimeMs: Math.floor(st.mtimeMs), size: st.size };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** L'installation a-t-elle changé sous nos pieds ? Une empreinte illisible ne conclut rien. */
|
||||||
|
export function installChanged(boot: InstallStamp | null, current: InstallStamp | null): boolean {
|
||||||
|
if (!boot || !current) return false;
|
||||||
|
return boot.ino !== current.ino || boot.mtimeMs !== current.mtimeMs || boot.size !== current.size;
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { createServer } from 'node:net';
|
||||||
|
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import {
|
||||||
|
classifyPortConflict,
|
||||||
|
clearDaemonRecord,
|
||||||
|
isOurDaemonProcess,
|
||||||
|
isPortFree,
|
||||||
|
processAlive,
|
||||||
|
readDaemonRecord,
|
||||||
|
reclaimOrphanDaemon,
|
||||||
|
waitForPortFree,
|
||||||
|
writeDaemonRecord,
|
||||||
|
type DaemonRecord,
|
||||||
|
} from '../src/main/port-guard';
|
||||||
|
|
||||||
|
const rec = (over: Partial<DaemonRecord> = {}): DaemonRecord => ({ pid: 111, ownerPid: 222, port: 7317, ...over });
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réserve un port libre HORS de la plage éphémère du noyau (32768+). Un `listen(0)` rendu puis
|
||||||
|
* réutilisé peut être réattribué entre-temps à un autre worker vitest : le test échouait alors une
|
||||||
|
* fois sur N. Ici le port est choisi dans une plage que personne n'obtient par tirage.
|
||||||
|
*/
|
||||||
|
async function reservePort(): Promise<number> {
|
||||||
|
for (let i = 0; i < 40; i++) {
|
||||||
|
const port = 7400 + Math.floor(Math.random() * 600);
|
||||||
|
if (await isPortFree(port)) return port;
|
||||||
|
}
|
||||||
|
throw new Error('aucun port libre dans 7400-7999');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Attend que le squatteur ait RÉELLEMENT bind (un spawn met quelques dizaines de ms à écouter). */
|
||||||
|
async function waitUntilBusy(port: number, timeoutMs = 5_000): Promise<boolean> {
|
||||||
|
const deadline = Date.now() + timeoutMs;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (!(await isPortFree(port))) return true;
|
||||||
|
await new Promise((r) => setTimeout(r, 25));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('classifyPortConflict', () => {
|
||||||
|
it('sans empreinte, le port est tenu par un tiers', () => {
|
||||||
|
expect(classifyPortConflict(null, () => true, 7317)).toEqual({ kind: 'foreign' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('empreinte sur un AUTRE port : sans rapport avec le conflit courant', () => {
|
||||||
|
expect(classifyPortConflict(rec({ port: 7400 }), () => true, 7317)).toEqual({ kind: 'foreign' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('daemon de l’empreinte mort : le port est tenu par autre chose', () => {
|
||||||
|
expect(classifyPortConflict(rec(), () => false, 7317)).toEqual({ kind: 'foreign' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('daemon vivant + Electron parent vivant : autre instance de l’app', () => {
|
||||||
|
expect(classifyPortConflict(rec(), () => true, 7317)).toEqual({ kind: 'other-instance', pid: 111 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('daemon vivant mais Electron parent mort : orphelin récupérable', () => {
|
||||||
|
const alive = (pid: number): boolean => pid === 111;
|
||||||
|
expect(classifyPortConflict(rec(), alive, 7317)).toEqual({ kind: 'orphan', pid: 111 });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('empreinte du daemon', () => {
|
||||||
|
it('écrit, relit et efface', () => {
|
||||||
|
const file = join(mkdtempSync(join(tmpdir(), 'arb-pidfile-')), 'daemon.json');
|
||||||
|
writeDaemonRecord(file, rec());
|
||||||
|
expect(readDaemonRecord(file)).toEqual(rec());
|
||||||
|
clearDaemonRecord(file);
|
||||||
|
expect(readDaemonRecord(file)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejette un contenu illisible ou incomplet plutôt que de deviner', () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'arb-pidfile-'));
|
||||||
|
const bad = join(dir, 'bad.json');
|
||||||
|
writeFileSync(bad, 'pas du json', 'utf8');
|
||||||
|
expect(readDaemonRecord(bad)).toBeNull();
|
||||||
|
const partial = join(dir, 'partial.json');
|
||||||
|
writeFileSync(partial, JSON.stringify({ pid: 12 }), 'utf8');
|
||||||
|
expect(readDaemonRecord(partial)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('n’échoue pas si le chemin est inécrivable (diagnostic best-effort)', () => {
|
||||||
|
// Un fichier régulier en guise de répertoire parent : mkdir/write échouent (ENOTDIR) et
|
||||||
|
// l'écriture de l'empreinte doit rester silencieuse, jamais bloquer un démarrage.
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'arb-pidfile-'));
|
||||||
|
const blocker = join(dir, 'pas-un-dossier');
|
||||||
|
writeFileSync(blocker, 'x', 'utf8');
|
||||||
|
expect(() => writeDaemonRecord(join(blocker, 'daemon.json'), rec())).not.toThrow();
|
||||||
|
expect(readDaemonRecord(join(blocker, 'daemon.json'))).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('processAlive', () => {
|
||||||
|
it('reconnaît le process courant et refuse les pid invalides', () => {
|
||||||
|
expect(processAlive(process.pid)).toBe(true);
|
||||||
|
expect(processAlive(0)).toBe(false);
|
||||||
|
expect(processAlive(-1)).toBe(false);
|
||||||
|
expect(processAlive(Number.NaN)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isPortFree', () => {
|
||||||
|
it('distingue un port libre d’un port occupé', async () => {
|
||||||
|
const port = await reservePort();
|
||||||
|
expect(await isPortFree(port)).toBe(true);
|
||||||
|
const srv = createServer();
|
||||||
|
await new Promise<void>((resolve) => srv.listen(port, '127.0.0.1', resolve));
|
||||||
|
expect(await isPortFree(port)).toBe(false);
|
||||||
|
await new Promise<void>((resolve) => srv.close(() => resolve()));
|
||||||
|
expect(await isPortFree(port)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waitForPortFree rend la main sur expiration sans boucler indéfiniment', async () => {
|
||||||
|
const port = await reservePort();
|
||||||
|
const srv = createServer();
|
||||||
|
await new Promise<void>((resolve) => srv.listen(port, '127.0.0.1', resolve));
|
||||||
|
expect(await waitForPortFree(port, 250)).toBe(false);
|
||||||
|
await new Promise<void>((resolve) => srv.close(() => resolve()));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('isOurDaemonProcess', () => {
|
||||||
|
it('reconnaît un process dont la commande porte l’entrée du serveur', async () => {
|
||||||
|
const marker = join(mkdtempSync(join(tmpdir(), 'arb-entry-')), 'server-entry-marker.js');
|
||||||
|
writeFileSync(marker, 'setInterval(()=>{},1000)', 'utf8');
|
||||||
|
const child = spawn(process.execPath, [marker]);
|
||||||
|
await new Promise((r) => setTimeout(r, 400));
|
||||||
|
expect(isOurDaemonProcess(child.pid as number, marker)).toBe(true);
|
||||||
|
// Un pid recyclé par un programme quelconque ne doit PAS passer pour notre daemon.
|
||||||
|
expect(isOurDaemonProcess(child.pid as number, '/opt/ailleurs/dist/index.js')).toBe(false);
|
||||||
|
child.kill('SIGKILL');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('refuse quand la commande est illisible (pid absent, pid invalide)', () => {
|
||||||
|
expect(isOurDaemonProcess(2_147_483_600, '/quelconque')).toBe(false);
|
||||||
|
expect(isOurDaemonProcess(0, '/quelconque')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('reclaimOrphanDaemon', () => {
|
||||||
|
it('termine le squatteur et attend la libération EFFECTIVE du port', async () => {
|
||||||
|
const port = await reservePort();
|
||||||
|
const child = spawn(process.execPath, [
|
||||||
|
'-e',
|
||||||
|
`require('net').createServer().listen(${port},'127.0.0.1');setInterval(()=>{},1000)`,
|
||||||
|
]);
|
||||||
|
expect(await waitUntilBusy(port)).toBe(true); // l'enfant a bien pris le port
|
||||||
|
expect(await reclaimOrphanDaemon(child.pid as number, port)).toBe(true);
|
||||||
|
expect(await isPortFree(port)).toBe(true);
|
||||||
|
}, 12_000);
|
||||||
|
|
||||||
|
it('un pid déjà mort ne bloque rien', async () => {
|
||||||
|
const port = await reservePort();
|
||||||
|
const child = spawn(process.execPath, ['-e', 'process.exit(0)']);
|
||||||
|
await new Promise<void>((resolve) => child.once('exit', () => resolve()));
|
||||||
|
expect(await reclaimOrphanDaemon(child.pid as number, port)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('SIGKILL en dernier recours quand SIGTERM est ignoré', async () => {
|
||||||
|
const port = await reservePort();
|
||||||
|
const child = spawn(process.execPath, [
|
||||||
|
'-e',
|
||||||
|
`process.on('SIGTERM',()=>{});require('net').createServer().listen(${port},'127.0.0.1');setInterval(()=>{},1000)`,
|
||||||
|
]);
|
||||||
|
expect(await waitUntilBusy(port)).toBe(true);
|
||||||
|
expect(await reclaimOrphanDaemon(child.pid as number, port)).toBe(true);
|
||||||
|
expect(await isPortFree(port)).toBe(true);
|
||||||
|
}, 12_000);
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { DaemonStartError, describeStartFailure } from '../src/main/start-failure';
|
||||||
|
|
||||||
|
describe('describeStartFailure', () => {
|
||||||
|
it('port tenu par une autre instance : renvoie vers le tray, pas vers une trace technique', () => {
|
||||||
|
const err = new DaemonStartError('port-busy-instance', 'port 7317 is already in use');
|
||||||
|
const { message, detail } = describeStartFailure(err, 7317);
|
||||||
|
expect(message).toBe('Arboretum is already running');
|
||||||
|
expect(detail).toContain('7317');
|
||||||
|
expect(detail).toContain('system tray');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('port tenu par un tiers : nomme les suspects et l’échappatoire (variable d’env)', () => {
|
||||||
|
const err = new DaemonStartError('port-busy-foreign', 'port 7317 is already in use', 'EADDRINUSE');
|
||||||
|
const { message, detail } = describeStartFailure(err, 7317);
|
||||||
|
expect(message).toBe('Port 7317 is already in use');
|
||||||
|
expect(detail).toContain('arboretum install');
|
||||||
|
expect(detail).toContain('ARBORETUM_DESKTOP_PORT');
|
||||||
|
expect(detail).toContain('EADDRINUSE');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('échec de handshake : conserve le message et la queue de journal', () => {
|
||||||
|
const err = new DaemonStartError('handshake', 'daemon exited before handshake (code 1)', 'boom\nbadaboum');
|
||||||
|
const { message, detail } = describeStartFailure(err, 7317);
|
||||||
|
expect(message).toBe('Arboretum could not start its local server');
|
||||||
|
expect(detail).toContain('daemon exited before handshake (code 1)');
|
||||||
|
expect(detail).toContain('badaboum');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('erreur quelconque (hors DaemonStartError) reste affichable', () => {
|
||||||
|
expect(describeStartFailure(new Error('ENOENT node'), 7317).detail).toContain('ENOENT node');
|
||||||
|
expect(describeStartFailure('cassé', 7317).detail).toContain('cassé');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sans queue de journal, aucun bloc « Server output » vide', () => {
|
||||||
|
const detail = describeStartFailure(new DaemonStartError('handshake', 'nope'), 7317).detail;
|
||||||
|
expect(detail).not.toContain('Server output');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { mkdtempSync, utimesSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { installChanged, readInstallStamp } from '../src/main/upgrade-watch';
|
||||||
|
|
||||||
|
describe('upgrade-watch', () => {
|
||||||
|
it('lit une empreinte de fichier, et rien pour un chemin absent', () => {
|
||||||
|
const file = join(mkdtempSync(join(tmpdir(), 'arb-stamp-')), 'bin');
|
||||||
|
writeFileSync(file, 'v1', 'utf8');
|
||||||
|
const stamp = readInstallStamp(file);
|
||||||
|
expect(stamp?.size).toBe(2);
|
||||||
|
expect(readInstallStamp(join(file, 'nulle-part'))).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détecte le remplacement du binaire (mtime/taille)', () => {
|
||||||
|
const file = join(mkdtempSync(join(tmpdir(), 'arb-stamp-')), 'bin');
|
||||||
|
writeFileSync(file, 'v1', 'utf8');
|
||||||
|
const boot = readInstallStamp(file);
|
||||||
|
expect(installChanged(boot, readInstallStamp(file))).toBe(false);
|
||||||
|
|
||||||
|
writeFileSync(file, 'version deux', 'utf8');
|
||||||
|
utimesSync(file, new Date(), new Date(Date.now() + 5_000)); // dpkg pose un mtime plus récent
|
||||||
|
expect(installChanged(boot, readInstallStamp(file))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('une empreinte illisible ne conclut jamais à une mise à jour', () => {
|
||||||
|
const stamp = { ino: 1, mtimeMs: 2, size: 3 };
|
||||||
|
expect(installChanged(null, stamp)).toBe(false);
|
||||||
|
expect(installChanged(stamp, null)).toBe(false);
|
||||||
|
expect(installChanged(null, null)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,6 +3,71 @@
|
|||||||
Notable changes to `@johanleroy/git-arboretum` (the Arboretum daemon). The VS Code
|
Notable changes to `@johanleroy/git-arboretum` (the Arboretum daemon). The VS Code
|
||||||
extension keeps its own changelog in `packages/vscode/CHANGELOG.md`.
|
extension keeps its own changelog in `packages/vscode/CHANGELOG.md`.
|
||||||
|
|
||||||
|
## 3.7.0
|
||||||
|
|
||||||
|
Terminals stop going black, and they now sit side by side. Files and commits follow the terminal you
|
||||||
|
are actually looking at. Fully additive, no protocol version bump.
|
||||||
|
|
||||||
|
- **A terminal could stay completely black while its session was alive and running.** The attach
|
||||||
|
replay is a binary frame, but a client only learns its channel number from the `attached` message.
|
||||||
|
The server sent the replay *first*, so every client dropped it on an unknown channel: nothing was
|
||||||
|
painted, and a resting TUI (Claude at its prompt) never emits anything on its own. `attached` is now
|
||||||
|
sent before the replay, which fixes the web app, the desktop app and the VS Code extension at once.
|
||||||
|
A resize on attach used to hide the bug by triggering a repaint through SIGWINCH, which is why it
|
||||||
|
looked intermittent.
|
||||||
|
- **Screen-less attachments.** `attach` accepts an optional `screen` flag (default `true`). With
|
||||||
|
`screen: false`, a client that only wants to answer a dialog no longer takes control of the session,
|
||||||
|
no longer forces its own dimensions onto the PTY (which used to freeze the real terminal's geometry)
|
||||||
|
and no longer receives the output stream just to throw it away.
|
||||||
|
- **The reason a session died is now visible in the terminal**: a last line, `[arboretum] claude
|
||||||
|
exited with code 1`, is written to the stream before clients are detached. A process that died at
|
||||||
|
spawn time used to leave nothing but an empty screen.
|
||||||
|
- **A stale Claude CLI path is re-resolved.** The resolved binary was cached for the lifetime of the
|
||||||
|
daemon; after an nvm or asdf switch it pointed at a file that no longer existed, and the PTY died
|
||||||
|
without a single byte of output.
|
||||||
|
- **Terminal columns.** The dock holds up to three resizable columns, each with its own tabs. Alt+click
|
||||||
|
a session (tree, panels, attention list) or use the tab button to open it beside the current one.
|
||||||
|
Keystrokes always go to the focused column. The dock's height ceiling now follows the viewport
|
||||||
|
instead of a fixed 640 px, and opening the dock gives it a usable height.
|
||||||
|
- **Changes are scoped to the focused terminal.** The Changes view shows the worktree of the terminal
|
||||||
|
you are working in, or every repo of its group for a group session, with a one-click "show every
|
||||||
|
project" toggle. The Git index in the sidebar stays global on purpose: it is the way out of a narrow
|
||||||
|
scope. The activity-bar badge stays global too: it exists to surface work you are *not* looking at.
|
||||||
|
|
||||||
|
## 3.6.0
|
||||||
|
|
||||||
|
Files open again, and uncommitted work gets a real surface: one block per project, in the centre of
|
||||||
|
the IDE. Fully additive, no protocol version bump.
|
||||||
|
|
||||||
|
- **Opening a file showed an empty page.** The container of the single Monaco instance lived inside a
|
||||||
|
`v-if`, so mounting the IDE with no open tab (first use, or after closing everything) bailed out
|
||||||
|
silently and the editor was never created: the first file you opened rendered nothing, with no
|
||||||
|
spinner and no error. The container is now always mounted and the editor is created on demand.
|
||||||
|
Closing the last tab no longer destroys it either.
|
||||||
|
- **The editor now says when it cannot load.** A missing editor chunk (a stale `index.html` after an
|
||||||
|
update, a network drop) used to be memoized as a permanent failure, silently, for the whole
|
||||||
|
session. It reports the failure, offers Retry and Reload page, and shows a loading state while the
|
||||||
|
chunk and the file are fetched. A file that disappears under the editor is reported instead of
|
||||||
|
being swallowed.
|
||||||
|
- **No more console errors when opening TypeScript.** Only the base worker was provided, so the
|
||||||
|
TypeScript language service kept calling a worker that did not implement its methods, throwing on
|
||||||
|
every single file open. The language workers are shipped now (loaded on demand). Semantic
|
||||||
|
diagnostics stay off on purpose: with no tsconfig and no node_modules, they would invent errors.
|
||||||
|
- **Changes: your uncommitted work, per project, in the centre.** Two buttons on the right of the tab
|
||||||
|
bar switch the centre between Files and Changes. Changes shows one block per worktree across every
|
||||||
|
open project, each with its staged and unstaged files, its diff unfolded in place, its commit,
|
||||||
|
push, fetch and pull, and its own history. The Git panel in the sidebar becomes the index: what
|
||||||
|
each project is worth at a glance, one click to open the matching block. The activity bar badge
|
||||||
|
finally counts the worktrees that need attention.
|
||||||
|
- **Push and commit buttons tell the truth.** Push was enabled with nothing to push and disabled when
|
||||||
|
merely behind; it now follows what git will actually do. Amending just a message is allowed, as the
|
||||||
|
server already did. A rebase is offered as soon as the branch is behind, not only after a
|
||||||
|
fast-forward fails.
|
||||||
|
- **Commit, fetch and push refresh what they change.** They only broadcast a worktree update, so the
|
||||||
|
"n unpushed" counter stayed stale right after a push, and files just committed were still listed.
|
||||||
|
- On mobile, tapping a file in the explorer now brings the editor to the front, and the Git tab opens
|
||||||
|
the Changes view (the sidebar index is a desktop affordance).
|
||||||
|
|
||||||
## 3.5.1
|
## 3.5.1
|
||||||
|
|
||||||
Completes the terminal copy & paste of 3.5.0, which only worked in a browser.
|
Completes the terminal copy & paste of 3.5.0, which only worked in a browser.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@johanleroy/git-arboretum",
|
"name": "@johanleroy/git-arboretum",
|
||||||
"version": "3.5.1",
|
"version": "3.7.0",
|
||||||
"description": "Self-hosted multi-project AI IDE for git worktrees and the Claude Code sessions running on them",
|
"description": "Self-hosted multi-project AI IDE for git worktrees and the Claude Code sessions running on them",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
|
|||||||
@@ -0,0 +1,200 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Acceptation P17 : « le terminal reste tout noir alors que la session tourne ».
|
||||||
|
//
|
||||||
|
// Cause racine reproduite ici : le replay d'attache est une frame BINAIRE, et le client n'apprend le
|
||||||
|
// numéro de canal qu'avec le message `attached`. Émis AVANT, le replay tombait sur un canal inconnu et
|
||||||
|
// était jeté en silence : rien à l'écran jusqu'au prochain octet spontané du PTY, c'est-à-dire jamais
|
||||||
|
// pour un TUI au repos. Ce script vérifie l'ordre réel des trames sur un VRAI WebSocket, et couvre au
|
||||||
|
// passage les attaches sans écran et l'épilogue de sortie.
|
||||||
|
//
|
||||||
|
// Aucun quota Claude consommé : commande `bash`.
|
||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7549;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-p17-'));
|
||||||
|
const srv = spawn('node', [join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 'a.db'), '--no-discover'], {
|
||||||
|
env: { ...process.env, ARBORETUM_LOG: 'warn' },
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
});
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client WS qui conserve la CHRONOLOGIE des trames (`frames`), texte et binaire mêlés : c'est le seul
|
||||||
|
* moyen de tester un ordre. Les frames binaires sont décodées en {type, channel, payload}.
|
||||||
|
*/
|
||||||
|
function wsClient(cookie) {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${PORT}/ws`, { headers: { Origin: ORIGIN, Cookie: cookie } });
|
||||||
|
ws.binaryType = 'arraybuffer';
|
||||||
|
const frames = [];
|
||||||
|
const msgs = [];
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
if (!isBinary) {
|
||||||
|
const msg = JSON.parse(String(data));
|
||||||
|
msgs.push(msg);
|
||||||
|
frames.push({ kind: 'text', msg });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const buf = Buffer.from(data);
|
||||||
|
frames.push({ kind: 'binary', type: buf.readUInt8(0), channel: buf.readUInt32LE(1), payload: buf.subarray(5) });
|
||||||
|
});
|
||||||
|
const waitMsg = async (pred, timeout = 8000) => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
while (Date.now() - t0 < timeout) {
|
||||||
|
const m = msgs.find(pred);
|
||||||
|
if (m) return m;
|
||||||
|
await sleep(50);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Sortie telle que le VRAI client la peindrait : il n'enregistre un canal qu'en recevant `attached`
|
||||||
|
* et jette toute frame binaire arrivée avant. On imite ce comportement, sinon ce script verrait un
|
||||||
|
* écran que le navigateur, lui, n'affiche pas.
|
||||||
|
*/
|
||||||
|
const outputOf = (channel) => {
|
||||||
|
const known = frames.findIndex((f) => f.kind === 'text' && f.msg.type === 'attached' && f.msg.channel === channel);
|
||||||
|
if (known < 0) return '';
|
||||||
|
return frames
|
||||||
|
.slice(known)
|
||||||
|
.filter((f) => f.kind === 'binary' && f.channel === channel)
|
||||||
|
.map((f) => f.payload.toString('latin1'))
|
||||||
|
.join('');
|
||||||
|
};
|
||||||
|
return { ws, frames, msgs, waitMsg, outputOf, send: (m) => ws.send(JSON.stringify(m)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sleep(1500);
|
||||||
|
const token = /arb_[0-9a-f]+/.exec(srvOut)?.[0];
|
||||||
|
check('boot + token bootstrap', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const cookie = login.headers.get('set-cookie')?.split(';')[0] ?? '';
|
||||||
|
check('login → cookie', login.status === 200 && cookie.startsWith('arb_session='));
|
||||||
|
|
||||||
|
const api = (path, init = {}) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, { ...init, headers: { 'Content-Type': 'application/json', Origin: ORIGIN, Cookie: cookie, ...(init.headers ?? {}) } });
|
||||||
|
|
||||||
|
const created = await api('/api/v1/sessions', { method: 'POST', body: JSON.stringify({ cwd: tmp, command: 'bash' }) });
|
||||||
|
const sid = (await created.json()).session.id;
|
||||||
|
check('spawn bash', created.status === 201 && !!sid);
|
||||||
|
|
||||||
|
// --- 1. Première attache : de la sortie existe déjà dans le ring ---
|
||||||
|
const c1 = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c1.ws.on('open', res), c1.ws.on('error', rej)));
|
||||||
|
c1.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c1.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
|
||||||
|
c1.send({ type: 'attach', sessionId: sid, mode: 'interactive', cols: 120, rows: 32 });
|
||||||
|
const att1 = await c1.waitMsg((m) => m.type === 'attached');
|
||||||
|
check('attach interactif + controlling', att1?.controlling === true);
|
||||||
|
await sleep(300);
|
||||||
|
c1.send({ type: 'stdin', channel: att1.channel, data: 'echo MARQUEUR-ECRAN-1\r' });
|
||||||
|
await sleep(800);
|
||||||
|
check('stdin → output', c1.outputOf(att1.channel).includes('MARQUEUR-ECRAN-1'));
|
||||||
|
|
||||||
|
// --- 2. Ré-attache (nouvelle connexion, PTY silencieux) : l'écran DOIT revenir ---
|
||||||
|
// C'est le scénario vécu : l'app est rechargée, Claude est à son prompt et n'émet plus rien.
|
||||||
|
const c2 = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c2.ws.on('open', res), c2.ws.on('error', rej)));
|
||||||
|
c2.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c2.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c2.send({ type: 'attach', sessionId: sid, mode: 'interactive', cols: 120, rows: 32 });
|
||||||
|
const att2 = await c2.waitMsg((m) => m.type === 'attached');
|
||||||
|
await sleep(400);
|
||||||
|
|
||||||
|
const idxAttached = c2.frames.findIndex((f) => f.kind === 'text' && f.msg.type === 'attached');
|
||||||
|
const idxResync = c2.frames.findIndex((f) => f.kind === 'binary' && f.type === 0x02);
|
||||||
|
check('ORDRE : `attached` précède le replay binaire', idxAttached >= 0 && idxResync > idxAttached, `attached@${idxAttached}, resync@${idxResync}`);
|
||||||
|
check('le replay porte le canal annoncé', c2.frames[idxResync]?.channel === att2.channel);
|
||||||
|
const replay = c2.outputOf(att2.channel);
|
||||||
|
check('l’écran se reconstitue à la ré-attache (fin de l’écran noir)', replay.includes('MARQUEUR-ECRAN-1'), `${replay.length} octets rejoués`);
|
||||||
|
|
||||||
|
// --- 3. Un observateur peint aussi : il doit recevoir son replay ---
|
||||||
|
const c3 = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c3.ws.on('open', res), c3.ws.on('error', rej)));
|
||||||
|
c3.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c3.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c3.send({ type: 'attach', sessionId: sid, mode: 'observer', cols: 100, rows: 30 });
|
||||||
|
const att3 = await c3.waitMsg((m) => m.type === 'attached');
|
||||||
|
await sleep(400);
|
||||||
|
check('un observateur reçoit son replay (non-controlling)', att3?.controlling === false && c3.outputOf(att3.channel).includes('MARQUEUR-ECRAN-1'));
|
||||||
|
|
||||||
|
// --- 4. Attache SANS écran : ne vole pas le contrôle, ne reçoit rien ---
|
||||||
|
// Régression : le DialogPrompt attachait en interactif avec des dimensions bidon, prenait le
|
||||||
|
// `controlling` et figeait la géométrie du TUI pour le terminal ouvert ensuite.
|
||||||
|
const c4 = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c4.ws.on('open', res), c4.ws.on('error', rej)));
|
||||||
|
c4.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c4.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c4.send({ type: 'attach', sessionId: sid, mode: 'interactive', cols: 80, rows: 24, screen: false });
|
||||||
|
const att4 = await c4.waitMsg((m) => m.type === 'attached');
|
||||||
|
await sleep(300);
|
||||||
|
check('attache sans écran : jamais controlling', att4?.controlling === false);
|
||||||
|
check('attache sans écran : aucune frame binaire', !c4.frames.some((f) => f.kind === 'binary'));
|
||||||
|
|
||||||
|
c2.send({ type: 'stdin', channel: att2.channel, data: 'echo APRES-AVEUGLE\r' });
|
||||||
|
await sleep(800);
|
||||||
|
check('attache sans écran : ne reçoit pas la sortie du PTY', !c4.frames.some((f) => f.kind === 'binary'));
|
||||||
|
check('le terminal à écran garde le contrôle et fonctionne', c2.outputOf(att2.channel).includes('APRES-AVEUGLE'));
|
||||||
|
// elle garde en revanche le droit d'écrire (c'est sa seule raison d'être)
|
||||||
|
c4.send({ type: 'stdin', channel: att4.channel, data: 'echo ECRIT-PAR-AVEUGLE\r' });
|
||||||
|
await sleep(800);
|
||||||
|
check('attache sans écran : peut écrire', c2.outputOf(att2.channel).includes('ECRIT-PAR-AVEUGLE'));
|
||||||
|
|
||||||
|
// --- 5. Épilogue de sortie : la raison de la mort est visible DANS le terminal ---
|
||||||
|
const dying = await api('/api/v1/sessions', { method: 'POST', body: JSON.stringify({ cwd: tmp, command: 'bash' }) });
|
||||||
|
const dsid = (await dying.json()).session.id;
|
||||||
|
const c5 = wsClient(cookie);
|
||||||
|
await new Promise((res, rej) => (c5.ws.on('open', res), c5.ws.on('error', rej)));
|
||||||
|
c5.send({ type: 'hello', protocol: 1 });
|
||||||
|
await c5.waitMsg((m) => m.type === 'hello_ok');
|
||||||
|
c5.send({ type: 'attach', sessionId: dsid, mode: 'interactive', cols: 80, rows: 24 });
|
||||||
|
const att5 = await c5.waitMsg((m) => m.type === 'attached');
|
||||||
|
await sleep(300);
|
||||||
|
c5.send({ type: 'stdin', channel: att5.channel, data: 'exit 3\r' });
|
||||||
|
const detached5 = await c5.waitMsg((m) => m.type === 'detached' && m.channel === att5.channel, 8000);
|
||||||
|
const epilogue = c5.outputOf(att5.channel);
|
||||||
|
check('épilogue : le code de sortie est écrit dans le terminal', epilogue.includes('[arboretum]') && epilogue.includes('exited with code 3'), epilogue.slice(-60).replace(/[\r\n]+/g, ' '));
|
||||||
|
check('épilogue reçu AVANT le detached', !!detached5);
|
||||||
|
|
||||||
|
// --- 6. Le PTY n'a pas été redimensionné par les attaches sans écran ---
|
||||||
|
const listed = await (await api('/api/v1/sessions')).json();
|
||||||
|
check('session toujours vivante après tout ça', listed.sessions.some((s) => s.id === sid && s.live));
|
||||||
|
|
||||||
|
for (const c of [c1, c2, c3, c4, c5]) c.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
srv.kill('SIGTERM');
|
||||||
|
await sleep(1500);
|
||||||
|
check('arrêt propre du daemon (SIGTERM)', srv.exitCode === 0 || srv.exitCode === null);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
if (failed.length > 0) console.log(`\n--- sortie du daemon ---\n${srvOut.slice(-2000)}`);
|
||||||
|
console.log(failed.length === 0 ? '\nACCEPTANCE P17: ALL GREEN' : `\nACCEPTANCE P17: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,403 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Vérification E2E de la ZONE CENTRALE de l'IDE, par interaction réelle (pas des captures) : daemon
|
||||||
|
// temporaire isolé + Chromium headless piloté en CDP + cookie de session injecté. On clique dans
|
||||||
|
// l'arbre comme un utilisateur, puis on lit le DOM de Monaco.
|
||||||
|
//
|
||||||
|
// Ce que ce script prouve, et qu'aucune capture ne prouvait :
|
||||||
|
// (a) ouvrir un fichier alors qu'AUCUN onglet n'est persisté affiche réellement son contenu. C'est
|
||||||
|
// le cas nominal qui restait vide et muet : le conteneur de Monaco vivait sous un `v-if`, donc
|
||||||
|
// l'éditeur n'était jamais créé et aucun watcher ne retentait ;
|
||||||
|
// (b) fermer le dernier onglet puis réouvrir un fichier réaffiche le contenu (le conteneur ne doit
|
||||||
|
// pas être détruit, sinon l'éditeur pointe sur un noeud détaché) ;
|
||||||
|
// (c) sur mobile, toucher un fichier amène la zone centrale au premier plan (l'arbre et l'éditeur
|
||||||
|
// étant mutuellement exclusifs sous 768 px, un contenu visible EST la preuve de la bascule) ;
|
||||||
|
// (d) chunk de l'éditeur introuvable : un message et des actions de récupération, pas une zone vide ;
|
||||||
|
// (e) la bascule Fichiers / Changements liste bien les fichiers modifiés et permet de committer.
|
||||||
|
//
|
||||||
|
// Usage : node packages/server/scripts/verify-editor.mjs
|
||||||
|
// Prérequis : `npm run build` puis `node packages/server/scripts/copy-web.mjs`.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7412;
|
||||||
|
const CDP_PORT = 9335;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const MARKER = 'ARB_EDITOR_RENDERED_4242';
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
function findChromium() {
|
||||||
|
for (const bin of ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']) {
|
||||||
|
try {
|
||||||
|
return execFileSync('which', [bin]).toString().trim();
|
||||||
|
} catch {
|
||||||
|
/* essai suivant */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Client CDP minimal : un seul socket, corrélation par id, sessionId pour la cible attachée. */
|
||||||
|
function cdp(url) {
|
||||||
|
const ws = new WebSocket(url, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
|
||||||
|
let nextId = 1;
|
||||||
|
const pending = new Map();
|
||||||
|
const events = [];
|
||||||
|
ws.on('message', (raw) => {
|
||||||
|
const msg = JSON.parse(String(raw));
|
||||||
|
if (msg.id && pending.has(msg.id)) {
|
||||||
|
const { resolve, reject } = pending.get(msg.id);
|
||||||
|
pending.delete(msg.id);
|
||||||
|
msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.method) events.push(msg);
|
||||||
|
});
|
||||||
|
const ready = new Promise((res, rej) => (ws.on('open', res), ws.on('error', rej)));
|
||||||
|
const send = (method, params = {}, sessionId) =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const id = nextId++;
|
||||||
|
pending.set(id, { resolve, reject });
|
||||||
|
ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
||||||
|
setTimeout(() => pending.has(id) && (pending.delete(id), reject(new Error(`CDP timeout: ${method}`))), 30_000);
|
||||||
|
});
|
||||||
|
return { ws, ready, send, events };
|
||||||
|
}
|
||||||
|
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-verify-editor-'));
|
||||||
|
let srv = null;
|
||||||
|
let browser = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const publicIndex = join(serverDir, 'public', 'index.html');
|
||||||
|
check('SPA copiée dans packages/server/public', existsSync(publicIndex), publicIndex);
|
||||||
|
|
||||||
|
// --- dépôt de démonstration : un fichier sonde EN PREMIÈRE LIGNE (Monaco virtualise le rendu) ---
|
||||||
|
const repo = join(tmp, 'demo-repo');
|
||||||
|
mkdirSync(repo, { recursive: true });
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||||
|
writeFileSync(join(repo, 'probe.ts'), `export const probe = '${MARKER}';\n`);
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'commit initial');
|
||||||
|
// du travail non commité, pour la vue Changements
|
||||||
|
writeFileSync(join(repo, 'dirty.txt'), 'travail en cours\n');
|
||||||
|
|
||||||
|
srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 't.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, XDG_DATA_HOME: join(tmp, 'xdg'), ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
for (let i = 0; i < 60 && !/arb_[0-9a-f]{16,}/.test(srvOut); i++) await sleep(150);
|
||||||
|
const token = /arb_[0-9a-f]{16,}/.exec(srvOut)?.[0];
|
||||||
|
check('daemon temporaire démarré + token', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const sessionCookie = (login.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).find((c) => c.startsWith('arb_session='));
|
||||||
|
check('login → cookie de session', !!sessionCookie);
|
||||||
|
const cookieValue = sessionCookie?.slice('arb_session='.length) ?? '';
|
||||||
|
|
||||||
|
const j = (path, method, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: sessionCookie ?? '', ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
const repoRes = await (await j('/api/v1/repos', 'POST', { path: repo })).json();
|
||||||
|
const repoId = repoRes.repo?.id;
|
||||||
|
const repoLabel = repoRes.repo?.label;
|
||||||
|
check('dépôt de démonstration enregistré', !!repoId, repoLabel ?? '');
|
||||||
|
|
||||||
|
const chromeBin = findChromium();
|
||||||
|
check('Chromium disponible', !!chromeBin, chromeBin ?? 'introuvable');
|
||||||
|
if (!chromeBin) throw new Error('Chromium introuvable : impossible de vérifier le rendu');
|
||||||
|
browser = spawn(
|
||||||
|
chromeBin,
|
||||||
|
[
|
||||||
|
'--headless=new',
|
||||||
|
`--remote-debugging-port=${CDP_PORT}`,
|
||||||
|
`--user-data-dir=${join(tmp, 'chrome')}`,
|
||||||
|
'--no-first-run',
|
||||||
|
'--no-default-browser-check',
|
||||||
|
'--disable-gpu',
|
||||||
|
'--hide-scrollbars',
|
||||||
|
],
|
||||||
|
{ stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let wsUrl = null;
|
||||||
|
for (let i = 0; i < 80 && !wsUrl; i++) {
|
||||||
|
await sleep(200);
|
||||||
|
try {
|
||||||
|
wsUrl = (await (await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`)).json()).webSocketDebuggerUrl;
|
||||||
|
} catch {
|
||||||
|
/* pas encore prêt */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check('Chromium en écoute CDP', !!wsUrl);
|
||||||
|
const client = cdp(wsUrl);
|
||||||
|
await client.ready;
|
||||||
|
|
||||||
|
// localStorage est partagé par les cibles d'un même profil : on l'efface pour chaque scénario.
|
||||||
|
// AUCUN onglet persisté : c'est précisément le cas qui restait vide. `arboretum.locale` n'est pas
|
||||||
|
// un persistedRef (chaîne brute, pas de JSON).
|
||||||
|
const seed = (extra = '') =>
|
||||||
|
`localStorage.clear();localStorage.setItem('arb.theme', '"dark"');localStorage.setItem('arboretum.locale', 'en');${extra}`;
|
||||||
|
|
||||||
|
/** Ouvre une cible isolée, authentifiée, avec un état de vue amorcé. */
|
||||||
|
async function openTarget({ width = 1440, height = 900, extraSeed = '', blocked = [] } = {}) {
|
||||||
|
const { targetId } = await client.send('Target.createTarget', { url: 'about:blank' });
|
||||||
|
const { sessionId } = await client.send('Target.attachToTarget', { targetId, flatten: true });
|
||||||
|
await client.send('Runtime.enable', {}, sessionId);
|
||||||
|
await client.send('Log.enable', {}, sessionId);
|
||||||
|
await client.send('Network.enable', {}, sessionId);
|
||||||
|
await client.send('Page.enable', {}, sessionId);
|
||||||
|
await client.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 500 }, sessionId);
|
||||||
|
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
|
||||||
|
if (blocked.length > 0) await client.send('Network.setBlockedURLs', { urls: blocked }, sessionId);
|
||||||
|
await client.send('Page.addScriptToEvaluateOnNewDocument', { source: seed(extraSeed) }, sessionId);
|
||||||
|
const before = client.events.length;
|
||||||
|
await client.send('Page.navigate', { url: `${ORIGIN}/ide` }, sessionId);
|
||||||
|
return { targetId, sessionId, before };
|
||||||
|
}
|
||||||
|
|
||||||
|
const evaluate = async (expression, sessionId) =>
|
||||||
|
(await client.send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)).result?.value;
|
||||||
|
|
||||||
|
/** Attend qu'une condition devienne vraie (jamais de sleep fixe sur un rendu asynchrone). */
|
||||||
|
async function waitFor(fn, tries = 60, delay = 250) {
|
||||||
|
for (let i = 0; i < tries; i++) {
|
||||||
|
if (await fn()) return true;
|
||||||
|
await sleep(delay);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clic sur une ligne par son libellé exact : les libellés vivent dans un <span> à l'intérieur du
|
||||||
|
// <button> de la ligne (arbre de projets comme arbre de fichiers).
|
||||||
|
const clickRow = (label, sessionId) =>
|
||||||
|
evaluate(
|
||||||
|
`(() => {
|
||||||
|
const span = [...document.querySelectorAll('button span')].find((s) => s.textContent.trim() === ${JSON.stringify(label)});
|
||||||
|
const btn = span?.closest('button');
|
||||||
|
if (!btn) return false;
|
||||||
|
btn.click();
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Monaco VIRTUALISE : seules les lignes visibles existent dans le DOM, et les espaces sortent en
|
||||||
|
// U+00A0. La sonde est donc en première ligne, et on normalise avant comparaison.
|
||||||
|
const editorText = async (sessionId) =>
|
||||||
|
(await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const lines = document.querySelector('.monaco-editor .view-lines');
|
||||||
|
return lines ? lines.textContent.replace(/\\u00a0/g, ' ') : '';
|
||||||
|
})()`,
|
||||||
|
sessionId,
|
||||||
|
)) ?? '';
|
||||||
|
|
||||||
|
const editorBox = async (sessionId) =>
|
||||||
|
JSON.parse(
|
||||||
|
(await evaluate(
|
||||||
|
`JSON.stringify((() => {
|
||||||
|
const el = document.querySelector('.monaco-editor');
|
||||||
|
if (!el) return null;
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
return { w: Math.round(r.width), h: Math.round(r.height) };
|
||||||
|
})())`,
|
||||||
|
sessionId,
|
||||||
|
)) ?? 'null',
|
||||||
|
);
|
||||||
|
|
||||||
|
const describeError = (e) => {
|
||||||
|
const d = e.params?.exceptionDetails;
|
||||||
|
if (d) {
|
||||||
|
const ex = d.exception ?? {};
|
||||||
|
const where = d.url ? ` @${d.url}:${d.lineNumber ?? '?'}` : '';
|
||||||
|
return `${d.text ?? ''} ${ex.description ?? ex.value ?? ''}${where}`.trim();
|
||||||
|
}
|
||||||
|
return (e.params?.args ?? []).map((a) => a.description ?? a.value ?? a.type).join(' ');
|
||||||
|
};
|
||||||
|
|
||||||
|
const consoleErrors = (sessionId, before) =>
|
||||||
|
client.events
|
||||||
|
.slice(before)
|
||||||
|
.filter((e) => e.sessionId === sessionId)
|
||||||
|
.filter((e) => (e.method === 'Runtime.consoleAPICalled' && e.params?.type === 'error') || e.method === 'Runtime.exceptionThrown')
|
||||||
|
.map(describeError)
|
||||||
|
.filter((m) => m && !/favicon|manifest\.webmanifest/i.test(m));
|
||||||
|
|
||||||
|
/** Déroule l'arbre jusqu'au fichier sonde : dépôt, puis branche, puis fichier. */
|
||||||
|
async function openProbeFile(sessionId) {
|
||||||
|
if (!(await waitFor(() => clickRow(repoLabel, sessionId)))) return false;
|
||||||
|
if (!(await waitFor(() => clickRow('main', sessionId)))) return false;
|
||||||
|
return waitFor(() => clickRow('probe.ts', sessionId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- (a) desktop, aucun onglet persisté : le cas nominal qui restait vide ---
|
||||||
|
{
|
||||||
|
const { targetId, sessionId, before } = await openTarget();
|
||||||
|
const treeReady = await waitFor(async () => !!(await clickRow(repoLabel, sessionId)));
|
||||||
|
check('a · arbre de projets rendu', treeReady);
|
||||||
|
// L'éditeur ne doit pas exister avant qu'un fichier soit demandé (chargement paresseux préservé).
|
||||||
|
check('a · Monaco non chargé avant ouverture d un fichier', (await editorBox(sessionId)) === null);
|
||||||
|
|
||||||
|
check('a · navigation jusqu au fichier', await waitFor(() => clickRow('main', sessionId)) && (await waitFor(() => clickRow('probe.ts', sessionId))));
|
||||||
|
const shown = await waitFor(async () => (await editorText(sessionId)).includes(MARKER));
|
||||||
|
check('a · le contenu du fichier est réellement rendu', shown, shown ? '' : await editorText(sessionId));
|
||||||
|
const box = await editorBox(sessionId);
|
||||||
|
check('a · l éditeur occupe une surface réelle', !!box && box.w > 200 && box.h > 100, JSON.stringify(box));
|
||||||
|
check('a · la gouttière de numéros est rendue', !!(await evaluate("!!document.querySelector('.margin-view-overlays .line-numbers')", sessionId)));
|
||||||
|
const errs = consoleErrors(sessionId, before);
|
||||||
|
check('a · aucune erreur console', errs.length === 0, errs.slice(0, 3).join(' | '));
|
||||||
|
await client.send('Target.closeTarget', { targetId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- (b) fermer le dernier onglet, puis réouvrir : le conteneur ne doit pas avoir été détruit ---
|
||||||
|
{
|
||||||
|
const { targetId, sessionId, before } = await openTarget();
|
||||||
|
check('b · fichier ouvert une première fois', (await openProbeFile(sessionId)) && (await waitFor(async () => (await editorText(sessionId)).includes(MARKER))));
|
||||||
|
|
||||||
|
const closed = await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const tab = [...document.querySelectorAll('[title="probe.ts"]')].find((e) => e.querySelector('button'));
|
||||||
|
const btn = tab?.querySelector('button');
|
||||||
|
if (!btn) return false;
|
||||||
|
btn.click();
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
check('b · dernier onglet fermé', !!closed);
|
||||||
|
const tabsLeft = await evaluate("JSON.parse(localStorage.getItem('arb.ide.tabs') ?? '[]').length", sessionId);
|
||||||
|
check('b · plus aucun onglet', tabsLeft === 0, `restants: ${tabsLeft}`);
|
||||||
|
// Le point à prouver : le CONTENEUR survit (v-show, pas v-if). Sans modèle, Monaco détruit sa
|
||||||
|
// vue de lui-même (`.monaco-editor` disparaît) et la recrée au prochain setModel : c'est normal.
|
||||||
|
// Ce qui ne doit jamais disparaître, c'est le conteneur, sinon l'instance garde une référence sur
|
||||||
|
// un noeud détaché et la zone reste définitivement vide.
|
||||||
|
const hostAlive = await waitFor(
|
||||||
|
async () => (await evaluate("!!document.querySelector('[data-editor-host]')", sessionId)) === true,
|
||||||
|
12,
|
||||||
|
);
|
||||||
|
check('b · le conteneur de l éditeur survit à la fermeture', hostAlive);
|
||||||
|
check(
|
||||||
|
'b · état vide affiché',
|
||||||
|
await waitFor(async () => String(await evaluate('document.body.innerText', sessionId)).includes('No file open'), 12),
|
||||||
|
);
|
||||||
|
|
||||||
|
check('b · fichier réouvert', await waitFor(() => clickRow('probe.ts', sessionId)));
|
||||||
|
check('b · le contenu revient après réouverture', await waitFor(async () => (await editorText(sessionId)).includes(MARKER)));
|
||||||
|
const errs = consoleErrors(sessionId, before);
|
||||||
|
check('b · aucune erreur console', errs.length === 0, errs.slice(0, 3).join(' | '));
|
||||||
|
await client.send('Target.closeTarget', { targetId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- (c) mobile : l'arbre et l'éditeur sont mutuellement exclusifs, donc un contenu visible
|
||||||
|
// prouve que l'ouverture d'un fichier a bien amené la zone centrale au premier plan ---
|
||||||
|
{
|
||||||
|
const { targetId, sessionId } = await openTarget({ width: 390, height: 844 });
|
||||||
|
check('c · fichier ouvert depuis l explorateur mobile', await openProbeFile(sessionId));
|
||||||
|
check('c · le contenu s affiche (le panneau a basculé)', await waitFor(async () => (await editorText(sessionId)).includes(MARKER)));
|
||||||
|
const treeGone = await evaluate(
|
||||||
|
`![...document.querySelectorAll('button span')].some((s) => s.textContent.trim() === 'probe.ts')`,
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
check('c · l explorateur a laissé la place à l éditeur', !!treeGone);
|
||||||
|
await client.send('Target.closeTarget', { targetId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- (d) chunk de l'éditeur introuvable : message + actions, puis récupération au rechargement ---
|
||||||
|
// On bloque UNIQUEMENT le module d'import dynamique. Surtout pas *vendor-monaco* : le chunk
|
||||||
|
// d'entrée l'importe statiquement, le bloquer tuerait toute la SPA.
|
||||||
|
{
|
||||||
|
const { targetId, sessionId } = await openTarget({ blocked: ['*monaco-setup*'] });
|
||||||
|
check('d · fichier demandé malgré le chunk bloqué', await openProbeFile(sessionId));
|
||||||
|
const said = await waitFor(async () =>
|
||||||
|
String(await evaluate('document.body.innerText', sessionId)).includes('The code editor could not be loaded'),
|
||||||
|
);
|
||||||
|
check('d · l échec est annoncé au lieu d une zone vide', said);
|
||||||
|
const actions = await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const labels = [...document.querySelectorAll('button')].map((b) => b.textContent.trim());
|
||||||
|
return labels.includes('Retry') && labels.includes('Reload page');
|
||||||
|
})()`,
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
check('d · des actions de récupération sont proposées', !!actions);
|
||||||
|
|
||||||
|
await client.send('Network.setBlockedURLs', { urls: [] }, sessionId);
|
||||||
|
await client.send('Page.reload', {}, sessionId);
|
||||||
|
check('d · après rechargement, le fichier s ouvre', (await openProbeFile(sessionId)) && (await waitFor(async () => (await editorText(sessionId)).includes(MARKER))));
|
||||||
|
await client.send('Target.closeTarget', { targetId });
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- (e) bascule Fichiers / Changements : la liste des fichiers non commités et le commit ---
|
||||||
|
{
|
||||||
|
const { targetId, sessionId, before } = await openTarget({
|
||||||
|
extraSeed:
|
||||||
|
`localStorage.setItem('arb.ide.centerMode', '"changes"');` +
|
||||||
|
`localStorage.setItem('arb.ide.expandedRepos', ${JSON.stringify(JSON.stringify([repoId]))});` +
|
||||||
|
`localStorage.setItem('arb.ide.changesExpanded', ${JSON.stringify(JSON.stringify([`${repoId}\0${repo}`]))});`,
|
||||||
|
});
|
||||||
|
const listed = await waitFor(async () => String(await evaluate('document.body.innerText', sessionId)).includes('dirty.txt'));
|
||||||
|
check('e · la vue Changements liste le fichier non commité', listed);
|
||||||
|
const hasCommit = await evaluate(
|
||||||
|
`[...document.querySelectorAll('button')].some((b) => b.textContent.trim().startsWith('Commit'))`,
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
check('e · le panneau de commit est présent dans le bloc', !!hasCommit);
|
||||||
|
// La bascule de mode vit dans la barre d'onglets, donc elle est là même sans aucun onglet ouvert.
|
||||||
|
const switched = await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const btn = [...document.querySelectorAll('button[title]')].find((b) => b.getAttribute('title') === 'Files');
|
||||||
|
if (!btn) return false;
|
||||||
|
btn.click();
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
check('e · la bascule Fichiers est accessible sans onglet ouvert', !!switched);
|
||||||
|
check(
|
||||||
|
'e · retour au mode Fichiers',
|
||||||
|
await waitFor(async () => String(await evaluate('document.body.innerText', sessionId)).includes('No file open')),
|
||||||
|
);
|
||||||
|
const errs = consoleErrors(sessionId, before);
|
||||||
|
check('e · aucune erreur console', errs.length === 0, errs.slice(0, 3).join(' | '));
|
||||||
|
await client.send('Target.closeTarget', { targetId });
|
||||||
|
}
|
||||||
|
|
||||||
|
client.ws.close();
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
browser?.kill('SIGTERM');
|
||||||
|
srv?.kill('SIGTERM');
|
||||||
|
await sleep(1200);
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nVERIFY EDITOR: ALL GREEN' : `\nVERIFY EDITOR: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -0,0 +1,411 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Vérification E2E du DOCK TERMINAUX par interaction réelle : daemon temporaire isolé + Chromium
|
||||||
|
// headless piloté en CDP + cookie de session injecté. On clique comme un utilisateur, puis on lit le
|
||||||
|
// DOM et l'écran d'xterm.
|
||||||
|
//
|
||||||
|
// Ce que ce script prouve, et qu'aucune capture ne prouvait :
|
||||||
|
// (a) un terminal attaché AFFICHE la sortie de son PTY (le bug « écran tout noir » venait du replay
|
||||||
|
// émis avant `attached`, donc jeté par le client : ici on lit le texte réellement peint) ;
|
||||||
|
// (b) deux terminaux tiennent côte à côte, chacun dans sa colonne, tous les deux visibles ;
|
||||||
|
// (c) la frappe va au terminal de la colonne ACTIVE, et suit le changement de colonne ;
|
||||||
|
// (d) fermer une colonne rend sa place à l'autre, et le terminal restant continue de fonctionner ;
|
||||||
|
// (e) la vue Changements suit le terminal focalisé (portée), et la bascule « tout voir » la libère.
|
||||||
|
//
|
||||||
|
// Sessions `bash` uniquement : aucun quota Claude consommé.
|
||||||
|
// Usage : node packages/server/scripts/verify-terminals.mjs
|
||||||
|
// Prérequis : `npm run build` puis `node packages/server/scripts/copy-web.mjs`.
|
||||||
|
import { spawn, execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
const WebSocket = require('ws');
|
||||||
|
|
||||||
|
const PORT = 7413;
|
||||||
|
const CDP_PORT = 9336;
|
||||||
|
const ORIGIN = `http://127.0.0.1:${PORT}`;
|
||||||
|
const serverDir = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
const results = [];
|
||||||
|
const check = (name, ok, detail = '') => {
|
||||||
|
results.push({ name, ok, detail });
|
||||||
|
console.log(`${ok ? '✅' : '❌'} ${name}${detail ? `: ${detail}` : ''}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
function findChromium() {
|
||||||
|
for (const bin of ['chromium', 'chromium-browser', 'google-chrome', 'google-chrome-stable']) {
|
||||||
|
try {
|
||||||
|
return execFileSync('which', [bin]).toString().trim();
|
||||||
|
} catch {
|
||||||
|
/* essai suivant */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cdp(url) {
|
||||||
|
const ws = new WebSocket(url, { perMessageDeflate: false, maxPayload: 256 * 1024 * 1024 });
|
||||||
|
let nextId = 1;
|
||||||
|
const pending = new Map();
|
||||||
|
const events = [];
|
||||||
|
ws.on('message', (raw) => {
|
||||||
|
const msg = JSON.parse(String(raw));
|
||||||
|
if (msg.id && pending.has(msg.id)) {
|
||||||
|
const { resolve, reject } = pending.get(msg.id);
|
||||||
|
pending.delete(msg.id);
|
||||||
|
msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.method) events.push(msg);
|
||||||
|
});
|
||||||
|
const ready = new Promise((res, rej) => (ws.on('open', res), ws.on('error', rej)));
|
||||||
|
const send = (method, params = {}, sessionId) =>
|
||||||
|
new Promise((resolve, reject) => {
|
||||||
|
const id = nextId++;
|
||||||
|
pending.set(id, { resolve, reject });
|
||||||
|
ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
|
||||||
|
setTimeout(() => pending.has(id) && (pending.delete(id), reject(new Error(`CDP timeout: ${method}`))), 30_000);
|
||||||
|
});
|
||||||
|
return { ws, ready, send, events };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Répertoire de captures optionnel : `node scripts/verify-terminals.mjs [out]`. */
|
||||||
|
const shotDir = process.argv[2] ?? null;
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'arb-verify-term-'));
|
||||||
|
let srv = null;
|
||||||
|
let browser = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
check('SPA copiée dans packages/server/public', existsSync(join(serverDir, 'public', 'index.html')));
|
||||||
|
|
||||||
|
// Deux dépôts : le second sert à prouver que la portée git suit bien le terminal focalisé.
|
||||||
|
const repos = [];
|
||||||
|
for (const name of ['alpha', 'beta']) {
|
||||||
|
const dir = join(tmp, name);
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
const git = (...args) => execFileSync('git', args, { cwd: dir, stdio: 'pipe' });
|
||||||
|
git('init', '-b', 'main');
|
||||||
|
git('config', 'user.email', 'test@arboretum.dev');
|
||||||
|
git('config', 'user.name', 'Test');
|
||||||
|
writeFileSync(join(dir, 'README.md'), `# ${name}\n`);
|
||||||
|
git('add', '-A');
|
||||||
|
git('commit', '-m', 'commit initial');
|
||||||
|
writeFileSync(join(dir, `wip-${name}.txt`), 'travail en cours\n');
|
||||||
|
repos.push({ name, dir });
|
||||||
|
}
|
||||||
|
|
||||||
|
srv = spawn(
|
||||||
|
'node',
|
||||||
|
[join(serverDir, 'dist', 'index.js'), '--port', String(PORT), '--db', join(tmp, 't.db'), '--claude-home', join(tmp, 'claude'), '--no-discover'],
|
||||||
|
{ env: { ...process.env, XDG_DATA_HOME: join(tmp, 'xdg'), ARBORETUM_LOG: 'warn' }, stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let srvOut = '';
|
||||||
|
srv.stdout.on('data', (d) => (srvOut += d));
|
||||||
|
srv.stderr.on('data', (d) => (srvOut += d));
|
||||||
|
for (let i = 0; i < 60 && !/arb_[0-9a-f]{16,}/.test(srvOut); i++) await sleep(150);
|
||||||
|
const token = /arb_[0-9a-f]{16,}/.exec(srvOut)?.[0];
|
||||||
|
check('daemon temporaire démarré + token', !!token);
|
||||||
|
|
||||||
|
const login = await fetch(`${ORIGIN}/api/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', Origin: ORIGIN },
|
||||||
|
body: JSON.stringify({ token }),
|
||||||
|
});
|
||||||
|
const sessionCookie = (login.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).find((c) => c.startsWith('arb_session='));
|
||||||
|
const cookieValue = sessionCookie?.slice('arb_session='.length) ?? '';
|
||||||
|
check('login → cookie de session', !!sessionCookie);
|
||||||
|
|
||||||
|
const j = (path, method, body) =>
|
||||||
|
fetch(`${ORIGIN}${path}`, {
|
||||||
|
method,
|
||||||
|
headers: { Origin: ORIGIN, Cookie: sessionCookie ?? '', ...(body ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
...(body ? { body: JSON.stringify(body) } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const r of repos) {
|
||||||
|
const res = await (await j('/api/v1/repos', 'POST', { path: r.dir })).json();
|
||||||
|
r.id = res.repo?.id;
|
||||||
|
}
|
||||||
|
check('deux dépôts enregistrés', repos.every((r) => !!r.id));
|
||||||
|
|
||||||
|
// Une session bash par dépôt : ce sont elles qui peupleront les deux colonnes.
|
||||||
|
for (const r of repos) {
|
||||||
|
const res = await (await j('/api/v1/sessions', 'POST', { cwd: r.dir, command: 'bash' })).json();
|
||||||
|
r.sessionId = res.session?.id;
|
||||||
|
}
|
||||||
|
check('deux sessions bash lancées', repos.every((r) => !!r.sessionId));
|
||||||
|
|
||||||
|
const chromeBin = findChromium();
|
||||||
|
check('Chromium disponible', !!chromeBin, chromeBin ?? 'introuvable');
|
||||||
|
if (!chromeBin) throw new Error('Chromium introuvable');
|
||||||
|
browser = spawn(
|
||||||
|
chromeBin,
|
||||||
|
[
|
||||||
|
'--headless=new',
|
||||||
|
`--remote-debugging-port=${CDP_PORT}`,
|
||||||
|
`--user-data-dir=${join(tmp, 'chrome')}`,
|
||||||
|
'--no-first-run',
|
||||||
|
'--no-default-browser-check',
|
||||||
|
'--disable-gpu',
|
||||||
|
// xterm peint sur un canvas WebGL quand il peut : le texte n'est alors PAS dans le DOM et
|
||||||
|
// aucun test ne peut le lire. On force le renderer DOM ; le chemin vérifié (transport → xterm)
|
||||||
|
// est le même, seule la peinture change.
|
||||||
|
'--disable-webgl',
|
||||||
|
'--hide-scrollbars',
|
||||||
|
],
|
||||||
|
{ stdio: ['ignore', 'pipe', 'pipe'] },
|
||||||
|
);
|
||||||
|
let wsUrl = null;
|
||||||
|
for (let i = 0; i < 80 && !wsUrl; i++) {
|
||||||
|
await sleep(200);
|
||||||
|
try {
|
||||||
|
wsUrl = (await (await fetch(`http://127.0.0.1:${CDP_PORT}/json/version`)).json()).webSocketDebuggerUrl;
|
||||||
|
} catch {
|
||||||
|
/* pas encore prêt */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
check('Chromium en écoute CDP', !!wsUrl);
|
||||||
|
const client = cdp(wsUrl);
|
||||||
|
await client.ready;
|
||||||
|
|
||||||
|
const { targetId } = await client.send('Target.createTarget', { url: 'about:blank' });
|
||||||
|
const { sessionId } = await client.send('Target.attachToTarget', { targetId, flatten: true });
|
||||||
|
await client.send('Runtime.enable', {}, sessionId);
|
||||||
|
await client.send('Log.enable', {}, sessionId);
|
||||||
|
await client.send('Page.enable', {}, sessionId);
|
||||||
|
await client.send('Emulation.setDeviceMetricsOverride', { width: 1600, height: 950, deviceScaleFactor: 1, mobile: false }, sessionId);
|
||||||
|
await client.send('Network.enable', {}, sessionId);
|
||||||
|
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
|
||||||
|
// Aucun état de vue persisté : le dock part vide, comme au premier lancement.
|
||||||
|
// Amorçage AVANT navigation (sinon le store lit un localStorage encore vide) : panneau Sessions à
|
||||||
|
// gauche pour ouvrir les terminaux, et zone centrale en mode Changements pour observer la portée.
|
||||||
|
await client.send(
|
||||||
|
'Page.addScriptToEvaluateOnNewDocument',
|
||||||
|
{
|
||||||
|
source: [
|
||||||
|
"localStorage.clear();",
|
||||||
|
`localStorage.setItem('arb.theme', '"dark"');`,
|
||||||
|
"localStorage.setItem('arboretum.locale', 'en');",
|
||||||
|
`localStorage.setItem('arb.ide.activity', '"sessions"');`,
|
||||||
|
`localStorage.setItem('arb.ide.centerMode', '"changes"');`,
|
||||||
|
"localStorage.setItem('arb.ide.leftVisible', 'true');",
|
||||||
|
].join(''),
|
||||||
|
},
|
||||||
|
sessionId,
|
||||||
|
);
|
||||||
|
const consoleBefore = client.events.length;
|
||||||
|
await client.send('Page.navigate', { url: `${ORIGIN}/ide` }, sessionId);
|
||||||
|
|
||||||
|
const evaluate = async (expression) => (await client.send('Runtime.evaluate', { expression, returnByValue: true }, sessionId)).result?.value;
|
||||||
|
async function waitFor(fn, tries = 60, delay = 250) {
|
||||||
|
for (let i = 0; i < tries; i++) {
|
||||||
|
if (await fn()) return true;
|
||||||
|
await sleep(delay);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
/** Texte réellement PEINT par une instance xterm (index de colonne dans le dock). */
|
||||||
|
const screenText = (n) =>
|
||||||
|
evaluate(
|
||||||
|
`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('.xterm-rows')];
|
||||||
|
const el = rows[${n}] ?? [...document.querySelectorAll('.xterm-screen')][${n}];
|
||||||
|
return el ? el.innerText.replace(/\\u00a0/g, ' ') : null;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
const columnCount = () => evaluate(`document.querySelectorAll('.xterm-screen').length`);
|
||||||
|
const clickRow = (label) =>
|
||||||
|
evaluate(
|
||||||
|
`(() => {
|
||||||
|
const span = [...document.querySelectorAll('button span')].find((s) => s.textContent.trim() === ${JSON.stringify(label)});
|
||||||
|
const btn = span?.closest('button');
|
||||||
|
if (!btn) return false;
|
||||||
|
btn.click();
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
const clickTitled = (title, nth = 0) =>
|
||||||
|
evaluate(
|
||||||
|
`(() => {
|
||||||
|
const btns = [...document.querySelectorAll('[title=' + JSON.stringify(${JSON.stringify(title)}) + ']')];
|
||||||
|
const btn = btns[${nth}];
|
||||||
|
if (!btn) return false;
|
||||||
|
btn.click();
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
/**
|
||||||
|
* Clic NATIF au centre d'une colonne : c'est le seul moyen de donner le focus au textarea caché
|
||||||
|
* d'xterm (un PointerEvent synthétique ne déplace pas le focus du navigateur).
|
||||||
|
*/
|
||||||
|
async function clickColumn(n) {
|
||||||
|
const box = await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const el = [...document.querySelectorAll('.xterm-screen')][${n}];
|
||||||
|
if (!el) return null;
|
||||||
|
const r = el.getBoundingClientRect();
|
||||||
|
return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2) };
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
if (!box) return false;
|
||||||
|
for (const type of ['mousePressed', 'mouseReleased']) {
|
||||||
|
await client.send('Input.dispatchMouseEvent', { type, x: box.x, y: box.y, button: 'left', clickCount: 1 }, sessionId);
|
||||||
|
}
|
||||||
|
await sleep(200);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
/** Frappe réelle : insertText va à l'élément focalisé (le textarea d'xterm). */
|
||||||
|
const type = (text) => client.send('Input.insertText', { text }, sessionId);
|
||||||
|
const pressEnter = async () => {
|
||||||
|
await client.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13, text: '\r' }, sessionId);
|
||||||
|
await client.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, nativeVirtualKeyCode: 13 }, sessionId);
|
||||||
|
};
|
||||||
|
|
||||||
|
check('SPA chargée sur /ide', await waitFor(async () => (await evaluate(`!!document.querySelector('[aria-label], nav, main')`)) === true));
|
||||||
|
|
||||||
|
// --- (a) un terminal affiche la sortie de son PTY ---
|
||||||
|
/** Clique la ligne de session du panneau Sessions correspondant à un dépôt. `alt` = ouvrir à côté. */
|
||||||
|
const clickSessionRow = (repoName, alt = false) =>
|
||||||
|
evaluate(
|
||||||
|
`(() => {
|
||||||
|
const rows = [...document.querySelectorAll('aside button, div button')].filter(
|
||||||
|
(b) => b.textContent.includes(${JSON.stringify(repoName)}) && b.querySelector('span'),
|
||||||
|
);
|
||||||
|
const row = rows[0];
|
||||||
|
if (!row) return false;
|
||||||
|
row.dispatchEvent(new MouseEvent('click', { bubbles: true, altKey: ${alt} }));
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const listed = await waitFor(async () => (await evaluate(`document.body.innerText.includes('alpha') && document.body.innerText.includes('beta')`)) === true, 40);
|
||||||
|
check('les deux sessions sont listées dans le panneau', listed);
|
||||||
|
|
||||||
|
const openedFirst = await waitFor(async () => {
|
||||||
|
await clickSessionRow('alpha');
|
||||||
|
return (await columnCount()) >= 1;
|
||||||
|
}, 30);
|
||||||
|
check('un terminal s’ouvre dans le dock', openedFirst, `colonnes: ${await columnCount()}`);
|
||||||
|
|
||||||
|
await clickColumn(0);
|
||||||
|
check('le terminal prend le focus clavier', (await evaluate(`document.activeElement?.tagName?.toLowerCase() ?? ''`)) === 'textarea');
|
||||||
|
// Deux preuves complémentaires : le PTY a bien reçu la frappe (fichier créé dans SON cwd), et sa
|
||||||
|
// sortie est réellement peinte à l'écran (c'était précisément ce qui manquait : un écran noir).
|
||||||
|
await type('touch recu-A && echo MARQUEUR-COLONNE-A');
|
||||||
|
await pressEnter();
|
||||||
|
const gotA = await waitFor(() => existsSync(join(repos[0].dir, 'recu-A')), 40);
|
||||||
|
check('(a) la frappe atteint le PTY du terminal', gotA);
|
||||||
|
const paintedA = await waitFor(async () => ((await screenText(0)) ?? '').includes('MARQUEUR-COLONNE-A'), 40);
|
||||||
|
check('(a) le terminal PEINT la sortie de son PTY (fin de l’écran noir)', paintedA, ((await screenText(0)) ?? '').replace(/\s+/g, ' ').slice(-70));
|
||||||
|
|
||||||
|
// --- (b) deux terminaux côte à côte ---
|
||||||
|
const splitDone = await waitFor(async () => {
|
||||||
|
await clickSessionRow('beta', true); // Alt+clic = ouvrir à côté
|
||||||
|
return (await columnCount()) === 2;
|
||||||
|
}, 30);
|
||||||
|
check('(b) deux colonnes de terminaux visibles simultanément', splitDone, `colonnes: ${await columnCount()}`);
|
||||||
|
|
||||||
|
const bothVisible = await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const screens = [...document.querySelectorAll('.xterm-screen')];
|
||||||
|
if (screens.length !== 2) return false;
|
||||||
|
return screens.every((s) => { const r = s.getBoundingClientRect(); return r.width > 50 && r.height > 20; });
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
check('(b) les deux colonnes ont une surface réelle', bothVisible === true);
|
||||||
|
|
||||||
|
const sideBySide = await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const [a, b] = [...document.querySelectorAll('.xterm-screen')].map((s) => s.getBoundingClientRect());
|
||||||
|
return !!a && !!b && Math.abs(a.top - b.top) < 40 && Math.abs(a.left - b.left) > 100;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
check('(b) elles sont côte à côte (et non empilées)', sideBySide === true);
|
||||||
|
|
||||||
|
// Capture optionnelle (argument 1) : preuve visuelle des deux colonnes, utile en revue.
|
||||||
|
if (shotDir) {
|
||||||
|
mkdirSync(shotDir, { recursive: true });
|
||||||
|
const shot = await client.send('Page.captureScreenshot', { format: 'png' }, sessionId);
|
||||||
|
const file = join(shotDir, 'terminal-columns.png');
|
||||||
|
writeFileSync(file, Buffer.from(shot.data, 'base64'));
|
||||||
|
check('capture des deux colonnes écrite', existsSync(file), file);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- (c) la frappe va à la colonne active (la seconde vient d'être créée) ---
|
||||||
|
await type('touch recu-B && echo MARQUEUR-COLONNE-B');
|
||||||
|
await pressEnter();
|
||||||
|
const gotB = await waitFor(() => existsSync(join(repos[1].dir, 'recu-B')), 40);
|
||||||
|
check('(c) la frappe va au PTY de la colonne active (nouvelle colonne focalisée)', gotB);
|
||||||
|
check('(c) elle ne fuit pas dans l’autre PTY', !existsSync(join(repos[0].dir, 'recu-B')));
|
||||||
|
const paintedB = await waitFor(async () => ((await screenText(1)) ?? '').includes('MARQUEUR-COLONNE-B'), 40);
|
||||||
|
check('(c) la seconde colonne peint aussi sa sortie', paintedB);
|
||||||
|
|
||||||
|
// Retour sur la première colonne : un clic dedans doit lui rendre la frappe.
|
||||||
|
await clickColumn(0);
|
||||||
|
await type('touch retour-A');
|
||||||
|
await pressEnter();
|
||||||
|
const backToA = await waitFor(() => existsSync(join(repos[0].dir, 'retour-A')), 40);
|
||||||
|
check('(c) le focus suit le clic sur une colonne', backToA);
|
||||||
|
|
||||||
|
// --- (e) la portée git suit le terminal focalisé (zone centrale en mode Changements) ---
|
||||||
|
// La colonne active est celle d'alpha (on vient d'y revenir) : seul son fichier modifié doit être
|
||||||
|
// listé, celui de beta doit disparaître de la vue.
|
||||||
|
const centerText = () => evaluate(`document.querySelector('main')?.innerText ?? ''`);
|
||||||
|
const scopedToAlpha = await waitFor(async () => {
|
||||||
|
const txt = await centerText();
|
||||||
|
return txt.includes('wip-alpha.txt') && !txt.includes('wip-beta.txt');
|
||||||
|
}, 40);
|
||||||
|
check('(e) la vue Changements ne montre que le projet du terminal focalisé', scopedToAlpha, (await centerText()).replace(/\s+/g, ' ').slice(0, 90));
|
||||||
|
|
||||||
|
// Focaliser la colonne de beta doit faire suivre la vue.
|
||||||
|
await clickColumn(1);
|
||||||
|
const followsBeta = await waitFor(async () => {
|
||||||
|
const txt = await centerText();
|
||||||
|
return txt.includes('wip-beta.txt') && !txt.includes('wip-alpha.txt');
|
||||||
|
}, 40);
|
||||||
|
check('(e) changer de colonne fait suivre la vue Changements', followsBeta, (await centerText()).replace(/\s+/g, ' ').slice(0, 90));
|
||||||
|
|
||||||
|
// La bascule « tout voir » doit libérer la portée.
|
||||||
|
await evaluate(
|
||||||
|
`(() => {
|
||||||
|
const btn = [...document.querySelectorAll('button')].find((b) => /Show every project|Follow the focused terminal/.test(b.getAttribute('title') ?? ''));
|
||||||
|
btn?.click();
|
||||||
|
return !!btn;
|
||||||
|
})()`,
|
||||||
|
);
|
||||||
|
// Un bloc replié ne liste pas ses fichiers : la preuve d'élargissement, ce sont les deux dépôts.
|
||||||
|
const seesBoth = await waitFor(async () => {
|
||||||
|
const txt = await centerText();
|
||||||
|
return txt.includes('alpha') && txt.includes('beta');
|
||||||
|
}, 40);
|
||||||
|
check('(e) la bascule « tout voir » libère la portée', seesBoth);
|
||||||
|
|
||||||
|
// --- (d) fermer une colonne ---
|
||||||
|
const closed = await waitFor(async () => {
|
||||||
|
await clickTitled('Close', 0);
|
||||||
|
return (await columnCount()) <= 1;
|
||||||
|
}, 20);
|
||||||
|
check('(d) fermer un terminal libère sa colonne', closed, `colonnes: ${await columnCount()}`);
|
||||||
|
|
||||||
|
const consoleErrors = client.events
|
||||||
|
.slice(consoleBefore)
|
||||||
|
.filter((e) => e.method === 'Log.entryAdded' && e.params?.entry?.level === 'error')
|
||||||
|
.map((e) => e.params.entry.text)
|
||||||
|
// Les 404 de favicon et les avertissements de chunk ne concernent pas le dock.
|
||||||
|
.filter((t) => !/favicon|manifest/i.test(t));
|
||||||
|
check('aucune erreur console', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '));
|
||||||
|
} catch (err) {
|
||||||
|
check('exception', false, String(err));
|
||||||
|
} finally {
|
||||||
|
browser?.kill('SIGKILL');
|
||||||
|
srv?.kill('SIGTERM');
|
||||||
|
await sleep(1200);
|
||||||
|
srv?.kill('SIGKILL');
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
const failed = results.filter((r) => !r.ok);
|
||||||
|
console.log(failed.length === 0 ? '\nVERIFY TERMINALS: ALL GREEN' : `\nVERIFY TERMINALS: ${failed.length} FAILURE(S)`);
|
||||||
|
process.exit(failed.length === 0 ? 0 : 1);
|
||||||
|
}
|
||||||
@@ -130,6 +130,11 @@ try {
|
|||||||
check('groupe de démonstration créé', !!groupRes.group?.id);
|
check('groupe de démonstration créé', !!groupRes.group?.id);
|
||||||
const sess = await (await j('/api/v1/sessions', 'POST', { cwd: repo, command: 'bash' })).json();
|
const sess = await (await j('/api/v1/sessions', 'POST', { cwd: repo, command: 'bash' })).json();
|
||||||
check('session bash de démonstration', !!sess.session?.id);
|
check('session bash de démonstration', !!sess.session?.id);
|
||||||
|
// Un fichier indexé et un non indexé dans le checkout principal : la vue Changements doit montrer
|
||||||
|
// ses DEUX sections (« Staged » et « Changes »), sinon la capture ne prouve que la moitié.
|
||||||
|
writeFileSync(join(repo, 'notes.md'), 'brouillon\n');
|
||||||
|
const staged = await j(`/api/v1/repos/${repoId}/worktrees/stage`, 'POST', { path: repo, files: ['src/app.ts'] });
|
||||||
|
check('un fichier indexé pour la démonstration', staged.ok);
|
||||||
|
|
||||||
// --- Chromium headless en CDP ---
|
// --- Chromium headless en CDP ---
|
||||||
const chromeBin = findChromium();
|
const chromeBin = findChromium();
|
||||||
@@ -167,7 +172,24 @@ try {
|
|||||||
const expanded = JSON.stringify(JSON.stringify([repoId]));
|
const expanded = JSON.stringify(JSON.stringify([repoId]));
|
||||||
const context = JSON.stringify(JSON.stringify({ repoId, wtPath: repo }));
|
const context = JSON.stringify(JSON.stringify({ repoId, wtPath: repo }));
|
||||||
const seedExplorer = `localStorage.setItem('arb.ide.expandedRepos', ${expanded});localStorage.setItem('arb.ide.context', ${context});`;
|
const seedExplorer = `localStorage.setItem('arb.ide.expandedRepos', ${expanded});localStorage.setItem('arb.ide.context', ${context});`;
|
||||||
const seedGit = `${seedExplorer}localStorage.setItem('arb.ide.activity', '"git"');localStorage.setItem('arb.history.open', 'true');`;
|
// Index Git de la sidebar : compteurs par projet, sans liste de fichiers (celle-ci vit au centre).
|
||||||
|
const seedGit = `${seedExplorer}localStorage.setItem('arb.ide.activity', '"git"');`;
|
||||||
|
// Vue Changements de la zone centrale : blocs dépliés du checkout principal ET du worktree de
|
||||||
|
// feature, plus l'historique du premier (sa clé de repli est désormais PAR worktree).
|
||||||
|
const changesKeys = JSON.stringify(
|
||||||
|
JSON.stringify([`${repoId}\0${repo}`, ...(wtRes.worktree?.path ? [`${repoId}\0${wtRes.worktree.path}`] : [])]),
|
||||||
|
);
|
||||||
|
const seedChanges =
|
||||||
|
`${seedExplorer}localStorage.setItem('arb.ide.centerMode', '"changes"');` +
|
||||||
|
`localStorage.setItem('arb.ide.changesExpanded', ${changesKeys});` +
|
||||||
|
`localStorage.setItem(${JSON.stringify(`arb.history.open:${repoId}\0${repo}`)}, 'true');`;
|
||||||
|
const seedChangesMobile = `${seedChanges}localStorage.setItem('arb.ide.mobilePanel', '"changes"');`;
|
||||||
|
// Zone d'édition : un onglet persisté, jamais capturé jusqu'ici.
|
||||||
|
const editorTabId = `${repoId}\0${repo}\0src/app.ts`;
|
||||||
|
const seedEditor =
|
||||||
|
`${seedExplorer}localStorage.setItem('arb.ide.tabs', ${JSON.stringify(
|
||||||
|
JSON.stringify([{ id: editorTabId, repoId, wtPath: repo, file: 'src/app.ts', view: 'editor' }]),
|
||||||
|
)});localStorage.setItem('arb.ide.activeTab', ${JSON.stringify(JSON.stringify(editorTabId))});`;
|
||||||
// Panneau Groupes avec le groupe ET le worktree dépliés : c'est la vue qui porte l'arborescence de
|
// Panneau Groupes avec le groupe ET le worktree dépliés : c'est la vue qui porte l'arborescence de
|
||||||
// fichiers des membres du groupe, sinon jamais capturée.
|
// fichiers des membres du groupe, sinon jamais capturée.
|
||||||
const seedGroups =
|
const seedGroups =
|
||||||
@@ -175,11 +197,17 @@ try {
|
|||||||
`localStorage.setItem('arb.ide.expandedGroups', ${JSON.stringify(JSON.stringify([groupRes.group?.id]))});` +
|
`localStorage.setItem('arb.ide.expandedGroups', ${JSON.stringify(JSON.stringify([groupRes.group?.id]))});` +
|
||||||
`localStorage.setItem('arb.ide.expandedWts', ${JSON.stringify(JSON.stringify([repo]))});`;
|
`localStorage.setItem('arb.ide.expandedWts', ${JSON.stringify(JSON.stringify([repo]))});`;
|
||||||
|
|
||||||
|
// `expect` : une capture non vide ne prouve pas que le bon composant s'est rendu. On exige donc un
|
||||||
|
// fragment de texte propre à la surface visée.
|
||||||
const shots = [
|
const shots = [
|
||||||
{ name: 'ide-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedExplorer },
|
{ name: 'ide-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedExplorer },
|
||||||
{ name: 'ide-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedExplorer },
|
{ name: 'ide-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedExplorer },
|
||||||
{ name: 'git-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedGit },
|
{ name: 'git-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedGit, expect: 'feature/demo' },
|
||||||
{ name: 'git-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedGit },
|
{ name: 'git-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedGit, expect: 'feature/demo' },
|
||||||
|
{ name: 'changes-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedChanges, expect: 'wip.txt' },
|
||||||
|
{ name: 'changes-light-desktop', theme: 'light', width: 1440, height: 900, seed: seedChanges, expect: 'wip.txt' },
|
||||||
|
{ name: 'changes-dark-mobile', theme: 'dark', width: 390, height: 844, seed: seedChangesMobile, expect: 'wip.txt' },
|
||||||
|
{ name: 'editor-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedEditor, expect: 'src/app.ts' },
|
||||||
{ name: 'groups-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedGroups },
|
{ name: 'groups-dark-desktop', theme: 'dark', width: 1440, height: 900, seed: seedGroups },
|
||||||
{ name: 'ide-dark-mobile', theme: 'dark', width: 390, height: 844, seed: seedExplorer },
|
{ name: 'ide-dark-mobile', theme: 'dark', width: 390, height: 844, seed: seedExplorer },
|
||||||
{ name: 'ide-light-mobile', theme: 'light', width: 390, height: 844, seed: seedExplorer },
|
{ name: 'ide-light-mobile', theme: 'light', width: 390, height: 844, seed: seedExplorer },
|
||||||
@@ -196,9 +224,12 @@ try {
|
|||||||
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
|
await client.send('Network.setCookie', { name: 'arb_session', value: cookieValue, domain: '127.0.0.1', path: '/', httpOnly: true }, sessionId);
|
||||||
// Thème : la SPA lit `arb.theme` avant le premier paint (script anti-FOUC).
|
// Thème : la SPA lit `arb.theme` avant le premier paint (script anti-FOUC).
|
||||||
await client.send('Page.enable', {}, sessionId);
|
await client.send('Page.enable', {}, sessionId);
|
||||||
|
// `localStorage.clear()` d'abord : les cibles d'un même profil Chromium le PARTAGENT, donc sans
|
||||||
|
// ça une capture héritait de l'état de vue de la précédente (une capture de la zone d'édition
|
||||||
|
// montrait la vue Changements laissée par celle d'avant).
|
||||||
await client.send(
|
await client.send(
|
||||||
'Page.addScriptToEvaluateOnNewDocument',
|
'Page.addScriptToEvaluateOnNewDocument',
|
||||||
{ source: `localStorage.setItem('arb.theme', ${JSON.stringify(JSON.stringify(shot.theme))});${shot.seed ?? ''}` },
|
{ source: `localStorage.clear();localStorage.setItem('arb.theme', ${JSON.stringify(JSON.stringify(shot.theme))});${shot.seed ?? ''}` },
|
||||||
sessionId,
|
sessionId,
|
||||||
);
|
);
|
||||||
const before = client.events.length;
|
const before = client.events.length;
|
||||||
@@ -208,6 +239,7 @@ try {
|
|||||||
const text = await client.send('Runtime.evaluate', { expression: 'document.body.innerText', returnByValue: true }, sessionId);
|
const text = await client.send('Runtime.evaluate', { expression: 'document.body.innerText', returnByValue: true }, sessionId);
|
||||||
const rendered = String(text.result?.value ?? '');
|
const rendered = String(text.result?.value ?? '');
|
||||||
check(`${shot.name} : page rendue`, rendered.length > 20, `${rendered.length} caractères`);
|
check(`${shot.name} : page rendue`, rendered.length > 20, `${rendered.length} caractères`);
|
||||||
|
if (shot.expect) check(`${shot.name} : contenu attendu`, rendered.includes(shot.expect), shot.expect);
|
||||||
|
|
||||||
const errs = client.events
|
const errs = client.events
|
||||||
.slice(before)
|
.slice(before)
|
||||||
|
|||||||
@@ -86,7 +86,14 @@ export function resolveClaudeBin(configuredPath?: string | null): string {
|
|||||||
}
|
}
|
||||||
return configuredPath;
|
return configuredPath;
|
||||||
}
|
}
|
||||||
if (cachedClaudeBin) return cachedClaudeBin;
|
// Cache REVALIDÉ : le daemon vit des jours. Un changement de version nvm/asdf, une réinstallation
|
||||||
|
// du CLI ou un simple `npm i -g` remplace le chemin, et le cache pointait alors sur un fichier
|
||||||
|
// disparu : node-pty spawnait dans le vide, le PTY mourait sans un octet, et l'utilisateur n'avait
|
||||||
|
// qu'un terminal vide sans explication.
|
||||||
|
if (cachedClaudeBin) {
|
||||||
|
if (isExecutable(cachedClaudeBin)) return cachedClaudeBin;
|
||||||
|
cachedClaudeBin = null;
|
||||||
|
}
|
||||||
const found = findClaudeOnPath();
|
const found = findClaudeOnPath();
|
||||||
if (!found) {
|
if (!found) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|||||||
@@ -23,6 +23,8 @@ const NOTIFY_DEBOUNCE_MS = 1500;
|
|||||||
/** Capture du claudeSessionId après spawn : poll du registre par pid (waitReady validé S1). */
|
/** Capture du claudeSessionId après spawn : poll du registre par pid (waitReady validé S1). */
|
||||||
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;
|
||||||
|
/** Replay d'une attache sans écran : rien à peindre (alloué une fois, jamais muté). */
|
||||||
|
const EMPTY_REPLAY = Buffer.alloc(0);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ligne `sessions` telle que lue pour construire un SessionSummary historique (session terminée).
|
* Ligne `sessions` telle que lue pour construire un SessionSummary historique (session terminée).
|
||||||
@@ -79,6 +81,14 @@ function parseAddedDirs(raw: string | null): string[] {
|
|||||||
export interface ClientBinding {
|
export interface ClientBinding {
|
||||||
channel: number;
|
channel: number;
|
||||||
mode: 'interactive' | 'observer';
|
mode: 'interactive' | 'observer';
|
||||||
|
/**
|
||||||
|
* false = attache SANS écran (le client ne peint rien : il n'est là que pour écrire, cf. le
|
||||||
|
* DialogPrompt qui répond à un dialogue depuis la liste « À traiter »). Un tel binding ne prend
|
||||||
|
* jamais le `controlling` et ne redimensionne donc jamais le PTY : sinon ses dimensions
|
||||||
|
* arbitraires figeaient la géométrie du TUI pour le vrai terminal ouvert ensuite. Il ne reçoit
|
||||||
|
* pas non plus la sortie (inutile) et ne pèse pas dans le flow control.
|
||||||
|
*/
|
||||||
|
screen: boolean;
|
||||||
controlling: boolean;
|
controlling: boolean;
|
||||||
sentBytes: number;
|
sentBytes: number;
|
||||||
ackedBytes: number;
|
ackedBytes: number;
|
||||||
@@ -403,22 +413,32 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
|
|
||||||
// ---- attach / detach / io ----
|
// ---- attach / detach / io ----
|
||||||
|
|
||||||
attach(sessionId: string, binding: ClientBinding, cols: number, rows: number): { ok: true; controlling: boolean } | { ok: false; code: 'NOT_FOUND' | 'SESSION_EXITED' } {
|
/**
|
||||||
|
* Attache un client. Le payload de replay (reset terminal + queue du ring, l'écran TUI courant se
|
||||||
|
* reconstitue) est RENVOYÉ, pas envoyé : la gateway doit l'émettre APRÈS le message `attached`,
|
||||||
|
* sinon le client reçoit une frame binaire sur un canal qu'il ne connaît pas encore et la jette,
|
||||||
|
* ce qui laissait un terminal vide jusqu'au prochain octet spontané du PTY (jamais, pour un TUI
|
||||||
|
* au repos). Invariant à ne pas casser.
|
||||||
|
*/
|
||||||
|
attach(
|
||||||
|
sessionId: string,
|
||||||
|
binding: ClientBinding,
|
||||||
|
cols: number,
|
||||||
|
rows: number,
|
||||||
|
): { ok: true; controlling: boolean; replay: Buffer } | { ok: false; code: 'NOT_FOUND' | 'SESSION_EXITED' } {
|
||||||
const s = this.live.get(sessionId);
|
const s = this.live.get(sessionId);
|
||||||
if (!s) return { ok: false, code: 'NOT_FOUND' };
|
if (!s) return { ok: false, code: 'NOT_FOUND' };
|
||||||
if (s.exited) return { ok: false, code: 'SESSION_EXITED' };
|
if (s.exited) return { ok: false, code: 'SESSION_EXITED' };
|
||||||
const hasController = [...s.clients].some((c) => c.controlling);
|
const hasController = [...s.clients].some((c) => c.controlling);
|
||||||
binding.controlling = binding.mode === 'interactive' && !hasController;
|
binding.controlling = binding.mode === 'interactive' && binding.screen && !hasController;
|
||||||
s.clients.add(binding);
|
s.clients.add(binding);
|
||||||
if (binding.controlling) {
|
if (binding.controlling) {
|
||||||
s.proc.resize(cols, rows);
|
s.proc.resize(cols, rows);
|
||||||
s.tracker?.resize(cols, rows);
|
s.tracker?.resize(cols, rows);
|
||||||
}
|
}
|
||||||
// Replay : reset terminal + queue du ring (l'écran TUI courant se reconstitue)
|
|
||||||
binding.sendResync(s.ring.tail(REPLAY_TAIL_BYTES));
|
|
||||||
binding.sentBytes = 0;
|
binding.sentBytes = 0;
|
||||||
binding.ackedBytes = 0;
|
binding.ackedBytes = 0;
|
||||||
return { ok: true, controlling: binding.controlling };
|
return { ok: true, controlling: binding.controlling, replay: binding.screen ? s.ring.tail(REPLAY_TAIL_BYTES) : EMPTY_REPLAY };
|
||||||
}
|
}
|
||||||
|
|
||||||
detach(sessionId: string, binding: ClientBinding): void {
|
detach(sessionId: string, binding: ClientBinding): void {
|
||||||
@@ -426,7 +446,9 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
if (!s) return;
|
if (!s) return;
|
||||||
s.clients.delete(binding);
|
s.clients.delete(binding);
|
||||||
if (binding.controlling) {
|
if (binding.controlling) {
|
||||||
const next = [...s.clients].find((c) => c.mode === 'interactive');
|
// Le relais ne peut aller qu'à un client qui PEINT : un binding sans écran redimensionnerait
|
||||||
|
// le PTY à des dimensions arbitraires (cf. ClientBinding.screen).
|
||||||
|
const next = [...s.clients].find((c) => c.mode === 'interactive' && c.screen);
|
||||||
if (next) {
|
if (next) {
|
||||||
next.controlling = true;
|
next.controlling = true;
|
||||||
next.onControlChanged(true);
|
next.onControlChanged(true);
|
||||||
@@ -535,7 +557,7 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
s.ring.write(chunk);
|
s.ring.write(chunk);
|
||||||
s.tracker?.feed(chunk);
|
s.tracker?.feed(chunk);
|
||||||
for (const c of s.clients) {
|
for (const c of s.clients) {
|
||||||
if (c.lagging) continue;
|
if (c.lagging || !c.screen) continue;
|
||||||
c.sendOutput(chunk);
|
c.sendOutput(chunk);
|
||||||
c.sentBytes += chunk.length;
|
c.sentBytes += chunk.length;
|
||||||
if (c.sentBytes - c.ackedBytes > FLOW.LAGGING_BYTES) c.lagging = true;
|
if (c.sentBytes - c.ackedBytes > FLOW.LAGGING_BYTES) c.lagging = true;
|
||||||
@@ -545,11 +567,13 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* pause() seulement quand TOUS les clients interactifs non-lagging dépassent HIGH ;
|
* pause() seulement quand TOUS les clients interactifs non-lagging dépassent HIGH ;
|
||||||
* resume() quand le min repasse sous LOW. Les observers ne freinent jamais le PTY.
|
* resume() quand le min repasse sous LOW. Les observers ne freinent jamais le PTY, et les
|
||||||
|
* attaches sans écran ne reçoivent rien : les compter maintiendrait un `outstanding` nul et
|
||||||
|
* empêcherait toute pause, donc on les écarte.
|
||||||
*/
|
*/
|
||||||
private updateFlowControl(s: ManagedSession): void {
|
private updateFlowControl(s: ManagedSession): void {
|
||||||
if (s.exited) return;
|
if (s.exited) return;
|
||||||
const interactive = [...s.clients].filter((c) => c.mode === 'interactive' && !c.lagging);
|
const interactive = [...s.clients].filter((c) => c.mode === 'interactive' && c.screen && !c.lagging);
|
||||||
if (interactive.length === 0) {
|
if (interactive.length === 0) {
|
||||||
if (s.paused) {
|
if (s.paused) {
|
||||||
s.proc.resume();
|
s.proc.resume();
|
||||||
@@ -576,6 +600,11 @@ export class PtyManager extends EventEmitter<PtyManagerEvents> {
|
|||||||
if (s.notifyTimer) clearTimeout(s.notifyTimer);
|
if (s.notifyTimer) clearTimeout(s.notifyTimer);
|
||||||
const endedAt = new Date().toISOString();
|
const endedAt = new Date().toISOString();
|
||||||
this.db.prepare('UPDATE sessions SET ended_at = ?, exit_code = ? WHERE id = ?').run(endedAt, exitCode, s.id);
|
this.db.prepare('UPDATE sessions SET ended_at = ?, exit_code = ? WHERE id = ?').run(endedAt, exitCode, s.id);
|
||||||
|
// Épilogue visible DANS le terminal : sans lui, un process mort à l'instant du spawn (binaire
|
||||||
|
// introuvable, auth expirée, commande de lancement qui sort aussitôt) ne laissait qu'un écran
|
||||||
|
// vide et un bandeau « Session terminée », sans jamais dire pourquoi. Diffusé AVANT le
|
||||||
|
// `onDetached` : après, le client a déjà oublié le canal et jetterait la frame.
|
||||||
|
this.handleOutput(s, Buffer.from(`\r\n[arboretum] ${s.command} ${signal ? `terminated by signal ${signal}` : `exited with code ${exitCode ?? 0}`}\r\n`));
|
||||||
for (const c of s.clients) c.onDetached('session_exit');
|
for (const c of s.clients) c.onDetached('session_exit');
|
||||||
s.clients.clear();
|
s.clients.clear();
|
||||||
this.live.delete(s.id);
|
this.live.delete(s.id);
|
||||||
|
|||||||
@@ -564,6 +564,11 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
throw httpError(400, 'COMMIT_FAILED', (err as Error).message);
|
throw httpError(400, 'COMMIT_FAILED', (err as Error).message);
|
||||||
}
|
}
|
||||||
this.factsCache.delete(repoId);
|
this.factsCache.delete(repoId);
|
||||||
|
// Un commit vide l'index et déplace HEAD : sans cette émission, les vues à contenu paresseux
|
||||||
|
// continuaient d'afficher les fichiers qu'on venait de committer, et l'historique ne voyait pas
|
||||||
|
// le nouveau commit (le watcher FS finissait par le rattraper, mais seulement si ce worktree
|
||||||
|
// était observé, et avec le délai du debounce).
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -676,6 +681,10 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
return this.withLock(repoId, async () => {
|
return this.withLock(repoId, async () => {
|
||||||
await fetchRemote(w.path).catch((err) => { throw httpError(400, 'FETCH_FAILED', (err as Error).message); });
|
await fetchRemote(w.path).catch((err) => { throw httpError(400, 'FETCH_FAILED', (err as Error).message); });
|
||||||
this.factsCache.delete(repoId);
|
this.factsCache.delete(repoId);
|
||||||
|
// Un fetch ne touche pas l'arbre de travail, mais il change ce que valent les compteurs et
|
||||||
|
// l'historique : uniformité « toute mutation git ré-arme les vues à contenu paresseux », sans
|
||||||
|
// quoi ce bouton est le seul du panneau à ne rien rafraîchir de visible.
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -793,6 +802,9 @@ export class WorktreeManager extends EventEmitter<WorktreeManagerEvents> {
|
|||||||
throw httpError(400, 'PUSH_FAILED', (err as Error).message);
|
throw httpError(400, 'PUSH_FAILED', (err as Error).message);
|
||||||
}
|
}
|
||||||
this.factsCache.delete(repoId);
|
this.factsCache.delete(repoId);
|
||||||
|
// Corrige le badge « n commits non poussés » de l'historique, qui restait périmé après un push :
|
||||||
|
// son seul déclencheur est ce jeton d'invalidation.
|
||||||
|
this.emit('worktree_changes', { repoId, path: w.path });
|
||||||
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
return (await this.emitWorktree(row, w.path)) as WorktreeSummary;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ export function registerWsGateway(
|
|||||||
const binding: ClientBinding = {
|
const binding: ClientBinding = {
|
||||||
channel,
|
channel,
|
||||||
mode: msg.mode,
|
mode: msg.mode,
|
||||||
|
screen: msg.screen ?? true,
|
||||||
controlling: false,
|
controlling: false,
|
||||||
sentBytes: 0,
|
sentBytes: 0,
|
||||||
ackedBytes: 0,
|
ackedBytes: 0,
|
||||||
@@ -200,7 +201,13 @@ export function registerWsGateway(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
channels.set(channel, { sessionId: msg.sessionId, binding });
|
channels.set(channel, { sessionId: msg.sessionId, binding });
|
||||||
|
// ORDRE CRITIQUE : `attached` d'abord, le replay ENSUITE. Le client n'apprend le numéro de
|
||||||
|
// canal qu'avec `attached` ; une frame binaire émise avant tombe sur un canal inconnu et
|
||||||
|
// est jetée en silence, ce qui laissait le terminal vide (un TUI au repos ne réémet rien).
|
||||||
send({ type: 'attached', channel, sessionId: msg.sessionId, mode: msg.mode, controlling: res.controlling });
|
send({ type: 'attached', channel, sessionId: msg.sessionId, mode: msg.mode, controlling: res.controlling });
|
||||||
|
// Toujours envoyé quand le client peint, même vide : le resync porte AUSSI l'ordre de reset,
|
||||||
|
// sans quoi une ré-attache après reconnexion empilerait le nouveau flux sur un écran périmé.
|
||||||
|
if (binding.screen) binding.sendResync(res.replay);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
case 'detach': {
|
case 'detach': {
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
// Le chemin du CLI claude est mémorisé pour la vie du process (le `which` coûte un fork par spawn).
|
||||||
|
// Régression : un daemon qui tourne des jours voyait ce chemin devenir invalide (bascule de version
|
||||||
|
// nvm/asdf, réinstallation du CLI) et continuait de spawner un fichier disparu. Le PTY mourait sans
|
||||||
|
// produire un seul octet, ce qui donnait un terminal vide et muet. Le cache est donc revalidé.
|
||||||
|
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
let dir: string;
|
||||||
|
/** Réponse courante du faux `which` : on la fait varier comme le ferait un changement de version. */
|
||||||
|
let onPath: string;
|
||||||
|
|
||||||
|
function makeBin(name: string): string {
|
||||||
|
const path = join(dir, name);
|
||||||
|
writeFileSync(path, '#!/bin/sh\nexit 0\n');
|
||||||
|
chmodSync(path, 0o755);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
dir = mkdtempSync(join(tmpdir(), 'arb-claude-bin-'));
|
||||||
|
vi.resetModules();
|
||||||
|
vi.doMock('node:child_process', () => ({ execFileSync: () => `${onPath}\n` }));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.doUnmock('node:child_process');
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('resolveClaudeBin · cache revalidé', () => {
|
||||||
|
it('le chemin caché disparu est re-résolu au lieu d’être servi tel quel', async () => {
|
||||||
|
const first = makeBin('claude-v1');
|
||||||
|
onPath = first;
|
||||||
|
const { resolveClaudeBin } = await import('../src/core/claude-launcher.js');
|
||||||
|
|
||||||
|
expect(resolveClaudeBin()).toBe(first);
|
||||||
|
|
||||||
|
// le CLI est réinstallé ailleurs : l'ancien chemin n'existe plus
|
||||||
|
rmSync(first);
|
||||||
|
const second = makeBin('claude-v2');
|
||||||
|
onPath = second;
|
||||||
|
|
||||||
|
expect(resolveClaudeBin()).toBe(second);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tant que le chemin caché existe, aucun `which` supplémentaire n’est fait', async () => {
|
||||||
|
const bin = makeBin('claude-stable');
|
||||||
|
onPath = bin;
|
||||||
|
const calls: number[] = [];
|
||||||
|
vi.doMock('node:child_process', () => ({
|
||||||
|
execFileSync: () => {
|
||||||
|
calls.push(1);
|
||||||
|
return `${onPath}\n`;
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
vi.resetModules();
|
||||||
|
const { resolveClaudeBin } = await import('../src/core/claude-launcher.js');
|
||||||
|
|
||||||
|
expect(resolveClaudeBin()).toBe(bin);
|
||||||
|
expect(resolveClaudeBin()).toBe(bin);
|
||||||
|
expect(resolveClaudeBin()).toBe(bin);
|
||||||
|
expect(calls).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -77,10 +77,11 @@ type BindingSpies = ClientBinding & {
|
|||||||
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
let channelSeq = 1;
|
let channelSeq = 1;
|
||||||
function makeBinding(mode: 'interactive' | 'observer'): BindingSpies {
|
function makeBinding(mode: 'interactive' | 'observer', screen = true): BindingSpies {
|
||||||
return {
|
return {
|
||||||
channel: channelSeq++,
|
channel: channelSeq++,
|
||||||
mode,
|
mode,
|
||||||
|
screen,
|
||||||
controlling: false,
|
controlling: false,
|
||||||
sentBytes: 0,
|
sentBytes: 0,
|
||||||
ackedBytes: 0,
|
ackedBytes: 0,
|
||||||
@@ -252,10 +253,12 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
|
|
||||||
const b = makeBinding('interactive');
|
const b = makeBinding('interactive');
|
||||||
const res = manager.attach(summary.id, b, 80, 24);
|
const res = manager.attach(summary.id, b, 80, 24);
|
||||||
expect(res).toEqual({ ok: true, controlling: true });
|
expect(res).toMatchObject({ ok: true, controlling: true });
|
||||||
|
|
||||||
expect(b.sendResync).toHaveBeenCalledTimes(1);
|
// Le replay est RENVOYÉ (la gateway l'émet après `attached`), jamais envoyé par attach :
|
||||||
const payload = b.sendResync.mock.calls[0]![0]!;
|
// une frame binaire qui précède `attached` tombe sur un canal inconnu du client et est jetée.
|
||||||
|
expect(b.sendResync).not.toHaveBeenCalled();
|
||||||
|
const payload = (res as { replay: Buffer }).replay;
|
||||||
const full = Buffer.from(chunks.join(''), 'ascii');
|
const full = Buffer.from(chunks.join(''), 'ascii');
|
||||||
expect(payload.length).toBe(REPLAY_TAIL_BYTES);
|
expect(payload.length).toBe(REPLAY_TAIL_BYTES);
|
||||||
expect(payload.equals(full.subarray(full.length - REPLAY_TAIL_BYTES))).toBe(true);
|
expect(payload.equals(full.subarray(full.length - REPLAY_TAIL_BYTES))).toBe(true);
|
||||||
@@ -264,12 +267,31 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
expect(b.ackedBytes).toBe(0);
|
expect(b.ackedBytes).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('ring vide → resync avec payload vide', () => {
|
it('ring vide → replay vide', () => {
|
||||||
const { summary } = spawnBash();
|
const { summary } = spawnBash();
|
||||||
const b = makeBinding('interactive');
|
const b = makeBinding('interactive');
|
||||||
manager.attach(summary.id, b, 80, 24);
|
const res = manager.attach(summary.id, b, 80, 24);
|
||||||
expect(b.sendResync).toHaveBeenCalledTimes(1);
|
expect((res as { replay: Buffer }).replay.length).toBe(0);
|
||||||
expect(b.sendResync.mock.calls[0]![0]!.length).toBe(0);
|
expect(b.sendResync).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('attache sans écran : ni contrôle, ni resize, ni sortie, ni replay', () => {
|
||||||
|
const { summary, pty } = spawnBash();
|
||||||
|
pty.emitData('hello');
|
||||||
|
const blind = makeBinding('interactive', false);
|
||||||
|
const res = manager.attach(summary.id, blind, 120, 32);
|
||||||
|
expect(res).toMatchObject({ ok: true, controlling: false });
|
||||||
|
expect((res as { replay: Buffer }).replay.length).toBe(0);
|
||||||
|
expect(pty.resize).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
// le vrai terminal ouvert ensuite prend bien le contrôle et impose SA géométrie
|
||||||
|
const real = makeBinding('interactive');
|
||||||
|
expect(manager.attach(summary.id, real, 200, 50)).toMatchObject({ ok: true, controlling: true });
|
||||||
|
expect(pty.resize).toHaveBeenCalledWith(200, 50);
|
||||||
|
|
||||||
|
pty.emitData('world');
|
||||||
|
expect(blind.sendOutput).not.toHaveBeenCalled();
|
||||||
|
expect(real.sendOutput).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('contrôle au premier interactif seulement, les observers ne comptent pas', () => {
|
it('contrôle au premier interactif seulement, les observers ne comptent pas', () => {
|
||||||
@@ -278,13 +300,13 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
const a = makeBinding('interactive');
|
const a = makeBinding('interactive');
|
||||||
const b = makeBinding('interactive');
|
const b = makeBinding('interactive');
|
||||||
|
|
||||||
expect(manager.attach(summary.id, obs, 80, 24)).toEqual({ ok: true, controlling: false });
|
expect(manager.attach(summary.id, obs, 80, 24)).toMatchObject({ ok: true, controlling: false });
|
||||||
expect(pty.resize).not.toHaveBeenCalled(); // un observer ne redimensionne pas
|
expect(pty.resize).not.toHaveBeenCalled(); // un observer ne redimensionne pas
|
||||||
|
|
||||||
expect(manager.attach(summary.id, a, 100, 30)).toEqual({ ok: true, controlling: true });
|
expect(manager.attach(summary.id, a, 100, 30)).toMatchObject({ ok: true, controlling: true });
|
||||||
expect(pty.resize).toHaveBeenCalledWith(100, 30); // le contrôleur impose sa taille
|
expect(pty.resize).toHaveBeenCalledWith(100, 30); // le contrôleur impose sa taille
|
||||||
|
|
||||||
expect(manager.attach(summary.id, b, 200, 50)).toEqual({ ok: true, controlling: false });
|
expect(manager.attach(summary.id, b, 200, 50)).toMatchObject({ ok: true, controlling: false });
|
||||||
expect(pty.resize).toHaveBeenCalledTimes(1); // pas de resize pour le non-contrôleur
|
expect(pty.resize).toHaveBeenCalledTimes(1); // pas de resize pour le non-contrôleur
|
||||||
expect(manager.get(summary.id)?.clients).toBe(3);
|
expect(manager.get(summary.id)?.clients).toBe(3);
|
||||||
});
|
});
|
||||||
@@ -531,8 +553,9 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
|
|
||||||
manager.ack(summary.id, a, 3 * mib); // rattrapage : outstanding 0 < LOW
|
manager.ack(summary.id, a, 3 * mib); // rattrapage : outstanding 0 < LOW
|
||||||
expect(a.lagging).toBe(false);
|
expect(a.lagging).toBe(false);
|
||||||
expect(a.sendResync).toHaveBeenCalledTimes(2); // attach + rattrapage
|
// seul le rattrapage passe par sendResync : le replay d'attache est renvoyé à la gateway
|
||||||
const payload = a.sendResync.mock.calls[1]![0]!;
|
expect(a.sendResync).toHaveBeenCalledTimes(1);
|
||||||
|
const payload = a.sendResync.mock.calls[0]![0]!;
|
||||||
const full = Buffer.from(chunks.join(''), 'ascii');
|
const full = Buffer.from(chunks.join(''), 'ascii');
|
||||||
expect(payload.equals(full.subarray(full.length - REPLAY_TAIL_BYTES))).toBe(true);
|
expect(payload.equals(full.subarray(full.length - REPLAY_TAIL_BYTES))).toBe(true);
|
||||||
expect(a.sentBytes).toBe(0);
|
expect(a.sentBytes).toBe(0);
|
||||||
@@ -592,7 +615,7 @@ describe('PtyManager (pty mocké)', () => {
|
|||||||
manager.attach(summary.id, a, 80, 24);
|
manager.attach(summary.id, a, 80, 24);
|
||||||
manager.detach(summary.id, a);
|
manager.detach(summary.id, a);
|
||||||
const b = makeBinding('interactive');
|
const b = makeBinding('interactive');
|
||||||
expect(manager.attach(summary.id, b, 80, 24)).toEqual({ ok: true, controlling: true });
|
expect(manager.attach(summary.id, b, 80, 24)).toMatchObject({ ok: true, controlling: true });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -212,6 +212,33 @@ describe('WorktreeManager', () => {
|
|||||||
expect(w.git.dirtyCount).toBe(0);
|
expect(w.git.dirtyCount).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Les vues à contenu paresseux (liste de fichiers modifiés, historique) ne se rechargent QUE sur
|
||||||
|
// `worktree_changes`. Il manquait sur commit, fetch et push, d'où un badge « non poussé » périmé et
|
||||||
|
// des fichiers déjà commités encore listés.
|
||||||
|
it('commit, fetch et push émettent worktree_changes (pas seulement worktree_update)', async () => {
|
||||||
|
const repo = makeTmpRepo();
|
||||||
|
const remote = mkdtempSync(join(tmpdir(), 'arb-remote-'));
|
||||||
|
dirs.push(remote);
|
||||||
|
execFileSync('git', ['init', '--bare', '-b', 'main'], { cwd: remote, stdio: 'pipe' });
|
||||||
|
execFileSync('git', ['remote', 'add', 'origin', remote], { cwd: repo, stdio: 'pipe' });
|
||||||
|
|
||||||
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
const changed: Array<{ repoId: string; path: string }> = [];
|
||||||
|
wt.on('worktree_changes', (e) => changed.push(e));
|
||||||
|
|
||||||
|
writeFileSync(join(repo, 'f.txt'), 'x\n');
|
||||||
|
await wt.commitWorktree(r.id, repo, 'add f');
|
||||||
|
expect(changed).toHaveLength(1);
|
||||||
|
|
||||||
|
const pushed = await wt.pushWorktree(r.id, repo);
|
||||||
|
expect(changed).toHaveLength(2);
|
||||||
|
expect(pushed.git.ahead).toBe(0); // documente le nouveau canPush : plus rien à pousser
|
||||||
|
|
||||||
|
await wt.fetch(r.id, repo);
|
||||||
|
expect(changed).toHaveLength(3);
|
||||||
|
expect(changed.every((e) => e.repoId === r.id && resolve(e.path) === resolve(repo))).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
it('promoteWorktree : la branche du worktree devient le checkout principal, worktree supprimé, ancienne branche conservée', async () => {
|
it('promoteWorktree : la branche du worktree devient le checkout principal, worktree supprimé, ancienne branche conservée', async () => {
|
||||||
const repo = makeTmpRepo();
|
const repo = makeTmpRepo();
|
||||||
const r = await wt.addRepo({ path: repo });
|
const r = await wt.addRepo({ path: repo });
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
// Ordre des trames à l'attache : régression de « le terminal reste tout noir alors que la session
|
||||||
|
// tourne ». Le replay d'attache est une frame BINAIRE ; le client n'apprend le numéro de canal
|
||||||
|
// qu'avec le message `attached`, et jette toute frame binaire portant un canal inconnu. Émettre le
|
||||||
|
// replay avant `attached` revenait donc à ne rien afficher jusqu'au prochain octet spontané du PTY,
|
||||||
|
// c'est-à-dire jamais pour un TUI au repos (Claude à son prompt).
|
||||||
|
//
|
||||||
|
// On instrumente la gateway avec un faux socket et de faux bus d'événements : c'est le seul moyen
|
||||||
|
// d'observer l'ORDRE réel des `socket.send` sans monter un vrai serveur WebSocket (couvert par
|
||||||
|
// scripts/acceptance-p17.mjs).
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { BINARY_FRAME, decodeBinaryFrame, PROTOCOL_VERSION } from '@arboretum/shared';
|
||||||
|
import { registerWsGateway } from '../src/ws/gateway.js';
|
||||||
|
import { PtyManager } from '../src/core/pty-manager.js';
|
||||||
|
import { openDb, type Db } from '../src/db/index.js';
|
||||||
|
|
||||||
|
vi.mock('node:child_process', () => ({ execFileSync: () => '/usr/bin/claude\n' }));
|
||||||
|
|
||||||
|
const ptyMock = vi.hoisted(() => ({ instances: [] as unknown[] }));
|
||||||
|
|
||||||
|
vi.mock('@homebridge/node-pty-prebuilt-multiarch', () => {
|
||||||
|
let nextPid = 200_000;
|
||||||
|
class FakePtyImpl {
|
||||||
|
pid = nextPid++;
|
||||||
|
write = vi.fn();
|
||||||
|
resize = vi.fn();
|
||||||
|
pause = vi.fn();
|
||||||
|
resume = vi.fn();
|
||||||
|
kill = vi.fn();
|
||||||
|
private dataCbs: Array<(d: string) => void> = [];
|
||||||
|
constructor(
|
||||||
|
readonly file: string,
|
||||||
|
readonly args: string[],
|
||||||
|
readonly opts: unknown,
|
||||||
|
) {}
|
||||||
|
onData(cb: (d: string) => void): { dispose: () => void } {
|
||||||
|
this.dataCbs.push(cb);
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
onExit(): { dispose: () => void } {
|
||||||
|
return { dispose: () => {} };
|
||||||
|
}
|
||||||
|
emitData(d: string): void {
|
||||||
|
for (const cb of this.dataCbs) cb(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
default: {
|
||||||
|
spawn: (file: string, args: string[], opts: unknown): FakePtyImpl => {
|
||||||
|
const p = new FakePtyImpl(file, args, opts);
|
||||||
|
ptyMock.instances.push(p);
|
||||||
|
return p;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Bus d'événements inerte : la gateway s'abonne à 7 services dont un seul nous intéresse. */
|
||||||
|
const inertBus = (): { on: () => void; off: () => void } => ({ on: () => {}, off: () => {} });
|
||||||
|
|
||||||
|
interface FakeSocket {
|
||||||
|
readyState: number;
|
||||||
|
OPEN: number;
|
||||||
|
sent: Array<string | Uint8Array>;
|
||||||
|
send(data: string | Uint8Array): void;
|
||||||
|
on(event: string, cb: (...args: unknown[]) => void): void;
|
||||||
|
ping(): void;
|
||||||
|
terminate(): void;
|
||||||
|
close(): void;
|
||||||
|
emit(event: string, ...args: unknown[]): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSocket(): FakeSocket {
|
||||||
|
const handlers = new Map<string, Array<(...args: unknown[]) => void>>();
|
||||||
|
return {
|
||||||
|
readyState: 1,
|
||||||
|
OPEN: 1,
|
||||||
|
sent: [],
|
||||||
|
send(data) {
|
||||||
|
this.sent.push(data);
|
||||||
|
},
|
||||||
|
on(event, cb) {
|
||||||
|
const list = handlers.get(event) ?? [];
|
||||||
|
list.push(cb);
|
||||||
|
handlers.set(event, list);
|
||||||
|
},
|
||||||
|
ping() {},
|
||||||
|
terminate() {},
|
||||||
|
close() {},
|
||||||
|
emit(event, ...args) {
|
||||||
|
for (const cb of handlers.get(event) ?? []) cb(...args);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('gateway · ordre des trames à l’attache', () => {
|
||||||
|
let db: Db;
|
||||||
|
let manager: PtyManager;
|
||||||
|
let socket: FakeSocket;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
ptyMock.instances.length = 0;
|
||||||
|
db = openDb(':memory:');
|
||||||
|
manager = new PtyManager(db);
|
||||||
|
socket = makeSocket();
|
||||||
|
|
||||||
|
let handler: ((s: unknown, req: unknown) => void) | null = null;
|
||||||
|
const app = {
|
||||||
|
get: (_path: string, _opts: unknown, h: (s: unknown, req: unknown) => void) => {
|
||||||
|
handler = h;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
registerWsGateway(
|
||||||
|
app as never,
|
||||||
|
manager,
|
||||||
|
inertBus() as never,
|
||||||
|
inertBus() as never,
|
||||||
|
inertBus() as never,
|
||||||
|
inertBus() as never,
|
||||||
|
inertBus() as never,
|
||||||
|
inertBus() as never,
|
||||||
|
'0.0.0-test',
|
||||||
|
);
|
||||||
|
handler!(socket, {});
|
||||||
|
socket.emit('message', Buffer.from(JSON.stringify({ type: 'hello', protocol: PROTOCOL_VERSION })), false);
|
||||||
|
socket.sent.length = 0; // on ignore le hello_ok
|
||||||
|
});
|
||||||
|
|
||||||
|
const send = (msg: unknown): void => socket.emit('message', Buffer.from(JSON.stringify(msg)), false);
|
||||||
|
const texts = (): Array<Record<string, unknown>> =>
|
||||||
|
socket.sent.filter((f): f is string => typeof f === 'string').map((f) => JSON.parse(f) as Record<string, unknown>);
|
||||||
|
|
||||||
|
it('`attached` d’abord, replay binaire ENSUITE, sur le même canal', () => {
|
||||||
|
const summary = manager.spawn({ cwd: tmpdir(), command: 'bash' });
|
||||||
|
(ptyMock.instances.at(-1) as { emitData(d: string): void }).emitData('prompt$ ');
|
||||||
|
|
||||||
|
send({ type: 'attach', sessionId: summary.id, mode: 'interactive', cols: 80, rows: 24 });
|
||||||
|
|
||||||
|
expect(socket.sent).toHaveLength(2);
|
||||||
|
const attached = JSON.parse(socket.sent[0] as string) as { type: string; channel: number };
|
||||||
|
expect(attached.type).toBe('attached');
|
||||||
|
|
||||||
|
const frame = decodeBinaryFrame(socket.sent[1] as Uint8Array);
|
||||||
|
expect(frame.type).toBe(BINARY_FRAME.RESYNC);
|
||||||
|
expect(frame.channel).toBe(attached.channel);
|
||||||
|
expect(Buffer.from(frame.payload).toString()).toBe('prompt$ ');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ring vide : le resync part quand même (il porte l’ordre de reset)', () => {
|
||||||
|
const summary = manager.spawn({ cwd: tmpdir(), command: 'bash' });
|
||||||
|
send({ type: 'attach', sessionId: summary.id, mode: 'interactive', cols: 80, rows: 24 });
|
||||||
|
|
||||||
|
expect(socket.sent).toHaveLength(2);
|
||||||
|
const frame = decodeBinaryFrame(socket.sent[1] as Uint8Array);
|
||||||
|
expect(frame.type).toBe(BINARY_FRAME.RESYNC);
|
||||||
|
expect(frame.payload.byteLength).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('attache sans écran : `attached` seul, aucune frame binaire', () => {
|
||||||
|
const summary = manager.spawn({ cwd: tmpdir(), command: 'bash' });
|
||||||
|
(ptyMock.instances.at(-1) as { emitData(d: string): void }).emitData('bruit');
|
||||||
|
|
||||||
|
send({ type: 'attach', sessionId: summary.id, mode: 'interactive', cols: 120, rows: 32, screen: false });
|
||||||
|
|
||||||
|
expect(texts().map((m) => m.type)).toEqual(['attached']);
|
||||||
|
expect(socket.sent.every((f) => typeof f === 'string')).toBe(true);
|
||||||
|
expect(texts()[0]).toMatchObject({ controlling: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un observer reçoit aussi son replay (il peint, lui)', () => {
|
||||||
|
const summary = manager.spawn({ cwd: tmpdir(), command: 'bash' });
|
||||||
|
(ptyMock.instances.at(-1) as { emitData(d: string): void }).emitData('ecran');
|
||||||
|
|
||||||
|
send({ type: 'attach', sessionId: summary.id, mode: 'observer', cols: 80, rows: 24 });
|
||||||
|
|
||||||
|
const frame = decodeBinaryFrame(socket.sent[1] as Uint8Array);
|
||||||
|
expect(frame.type).toBe(BINARY_FRAME.RESYNC);
|
||||||
|
expect(Buffer.from(frame.payload).toString()).toBe('ecran');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('session introuvable : erreur seule, pas de canal ni de frame binaire', () => {
|
||||||
|
send({ type: 'attach', sessionId: 'inconnue', mode: 'interactive', cols: 80, rows: 24 });
|
||||||
|
expect(texts()).toEqual([{ type: 'error', code: 'NOT_FOUND', message: 'Cannot attach: NOT_FOUND' }]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -266,7 +266,11 @@ export interface CloneOperation {
|
|||||||
// ---- Messages client → serveur ----
|
// ---- Messages client → serveur ----
|
||||||
export type ClientMessage =
|
export type ClientMessage =
|
||||||
| { type: 'hello'; protocol: number }
|
| { type: 'hello'; protocol: number }
|
||||||
| { type: 'attach'; sessionId: string; mode: 'interactive' | 'observer'; cols: number; rows: number }
|
// `screen` (défaut true) : false = le client n'affiche RIEN, il attache seulement pour écrire
|
||||||
|
// (ex. répondre à un dialogue depuis la liste « À traiter »). Le serveur ne lui envoie alors ni
|
||||||
|
// sortie ni replay, ne lui confie jamais le contrôle et ignore ses dimensions : sans ce drapeau,
|
||||||
|
// une telle attache volait le `controlling` et figeait la géométrie du TUI pour le vrai terminal.
|
||||||
|
| { type: 'attach'; sessionId: string; mode: 'interactive' | 'observer'; cols: number; rows: number; screen?: boolean }
|
||||||
| { type: 'detach'; channel: number }
|
| { type: 'detach'; channel: number }
|
||||||
| { type: 'stdin'; channel: number; data: string }
|
| { type: 'stdin'; channel: number; data: string }
|
||||||
// P4-A : répondre à un dialogue Claude sans clavier. Le serveur traduit l'intention
|
// P4-A : répondre à un dialogue Claude sans clavier. Le serveur traduit l'intention
|
||||||
@@ -340,7 +344,7 @@ export function parseClientMessage(raw: string): ClientMessage | null {
|
|||||||
return isCount(m.protocol) ? { type: 'hello', protocol: m.protocol } : null;
|
return isCount(m.protocol) ? { type: 'hello', protocol: m.protocol } : null;
|
||||||
case 'attach':
|
case 'attach':
|
||||||
return typeof m.sessionId === 'string' && (m.mode === 'interactive' || m.mode === 'observer') && isDim(m.cols) && isDim(m.rows)
|
return typeof m.sessionId === 'string' && (m.mode === 'interactive' || m.mode === 'observer') && isDim(m.cols) && isDim(m.rows)
|
||||||
? { type: 'attach', sessionId: m.sessionId, mode: m.mode, cols: m.cols, rows: m.rows }
|
? { type: 'attach', sessionId: m.sessionId, mode: m.mode, cols: m.cols, rows: m.rows, screen: typeof m.screen === 'boolean' ? m.screen : true }
|
||||||
: null;
|
: null;
|
||||||
case 'detach':
|
case 'detach':
|
||||||
return isU32(m.channel) ? { type: 'detach', channel: m.channel } : null;
|
return isU32(m.channel) ? { type: 'detach', channel: m.channel } : null;
|
||||||
|
|||||||
@@ -77,13 +77,24 @@ describe('parseClientMessage · cas valides', () => {
|
|||||||
it('attach avec dimensions aux bornes', () => {
|
it('attach avec dimensions aux bornes', () => {
|
||||||
const make = (cols: number, rows: number): string =>
|
const make = (cols: number, rows: number): string =>
|
||||||
JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'interactive', cols, rows });
|
JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'interactive', cols, rows });
|
||||||
expect(parseClientMessage(make(2, 2))).toEqual({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 2, rows: 2 });
|
expect(parseClientMessage(make(2, 2))).toEqual({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 2, rows: 2, screen: true });
|
||||||
expect(parseClientMessage(make(1000, 1000))).toEqual({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 1000, rows: 1000 });
|
expect(parseClientMessage(make(1000, 1000))).toEqual({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 1000, rows: 1000, screen: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('attach en mode observer', () => {
|
it('attach en mode observer', () => {
|
||||||
expect(parseClientMessage(JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'observer', cols: 80, rows: 24 })))
|
expect(parseClientMessage(JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'observer', cols: 80, rows: 24 })))
|
||||||
.toEqual({ type: 'attach', sessionId: 's1', mode: 'observer', cols: 80, rows: 24 });
|
.toEqual({ type: 'attach', sessionId: 's1', mode: 'observer', cols: 80, rows: 24, screen: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
// `screen` est ADDITIF : absent, il vaut true (un vieux client garde le comportement d'origine).
|
||||||
|
// À false, l'attache n'affiche rien : ni contrôle du PTY, ni sortie, ni replay.
|
||||||
|
it('attach avec screen : défaut true, false respecté, valeur non booléenne ignorée', () => {
|
||||||
|
const attach = (screen?: unknown): unknown =>
|
||||||
|
parseClientMessage(JSON.stringify({ type: 'attach', sessionId: 's1', mode: 'interactive', cols: 80, rows: 24, screen }));
|
||||||
|
expect(attach(false)).toMatchObject({ screen: false });
|
||||||
|
expect(attach(true)).toMatchObject({ screen: true });
|
||||||
|
expect(attach()).toMatchObject({ screen: true });
|
||||||
|
expect(attach('nope')).toMatchObject({ screen: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('detach avec channel aux bornes u32', () => {
|
it('detach avec channel aux bornes u32', () => {
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ export interface AttachOptions {
|
|||||||
cols: number;
|
cols: number;
|
||||||
rows: number;
|
rows: number;
|
||||||
sink: AttachmentSink;
|
sink: AttachmentSink;
|
||||||
|
/** false = attache d'écriture seule, sans affichage (cf. le champ `screen` du protocole). */
|
||||||
|
screen?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Transport minimal : abstrait pour les tests ; l'impl par défaut enveloppe `ws`. */
|
/** Transport minimal : abstrait pour les tests ; l'impl par défaut enveloppe `ws`. */
|
||||||
@@ -74,6 +76,7 @@ export class Attachment {
|
|||||||
readonly sink: AttachmentSink,
|
readonly sink: AttachmentSink,
|
||||||
cols: number,
|
cols: number,
|
||||||
rows: number,
|
rows: number,
|
||||||
|
readonly screen = true,
|
||||||
) {
|
) {
|
||||||
this.cols = cols;
|
this.cols = cols;
|
||||||
this.rows = rows;
|
this.rows = rows;
|
||||||
@@ -165,7 +168,7 @@ export class ArbWsClient {
|
|||||||
|
|
||||||
/** résout sur le prochain 'attached' corrélé ; rejette si la session est introuvable/terminée */
|
/** résout sur le prochain 'attached' corrélé ; rejette si la session est introuvable/terminée */
|
||||||
attach(opts: AttachOptions): Promise<Attachment> {
|
attach(opts: AttachOptions): Promise<Attachment> {
|
||||||
const att = new Attachment(this, opts.sessionId, opts.mode, opts.sink, opts.cols, opts.rows);
|
const att = new Attachment(this, opts.sessionId, opts.mode, opts.sink, opts.cols, opts.rows, opts.screen ?? true);
|
||||||
const promise = new Promise<Attachment>((resolve, reject) => {
|
const promise = new Promise<Attachment>((resolve, reject) => {
|
||||||
att.pending = { resolve, reject };
|
att.pending = { resolve, reject };
|
||||||
});
|
});
|
||||||
@@ -279,7 +282,7 @@ export class ArbWsClient {
|
|||||||
|
|
||||||
private sendAttach(att: Attachment): void {
|
private sendAttach(att: Attachment): void {
|
||||||
this.awaitingAttached.push(att);
|
this.awaitingAttached.push(att);
|
||||||
this.sendControl({ type: 'attach', sessionId: att.sessionId, mode: att.mode, cols: att.cols, rows: att.rows });
|
this.sendControl({ type: 'attach', sessionId: att.sessionId, mode: att.mode, cols: att.cols, rows: att.rows, screen: att.screen });
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleText(text: string): void {
|
private handleText(text: string): void {
|
||||||
|
|||||||
@@ -59,7 +59,9 @@ export async function answerSession(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const noop: AttachmentSink = { data: () => {}, reset: () => {}, detached: () => {}, controlChanged: () => {} };
|
const noop: AttachmentSink = { data: () => {}, reset: () => {}, detached: () => {}, controlChanged: () => {} };
|
||||||
const att = await deps.ws.attach({ sessionId: session.id, mode: 'interactive', cols: 80, rows: 24, sink: noop });
|
// `screen: false` : canal de réponse seul, sans affichage. Sinon il volait le `controlling` de la
|
||||||
|
// session et imposait 80x24 au PTY, ce qui déformait le terminal réellement ouvert ailleurs.
|
||||||
|
const att = await deps.ws.attach({ sessionId: session.id, mode: 'interactive', cols: 80, rows: 24, sink: noop, screen: false });
|
||||||
att.answer(action, optionN);
|
att.answer(action, optionN);
|
||||||
setTimeout(() => att.detach(), 600); // laisse le serveur traiter avant de fermer le canal éphémère
|
setTimeout(() => att.detach(), 600); // laisse le serveur traiter avant de fermer le canal éphémère
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { computed } from 'vue';
|
|||||||
import { wsClient } from './lib/ws-client';
|
import { wsClient } from './lib/ws-client';
|
||||||
import { useRealtimeBootstrap } from './composables/useRealtimeBootstrap';
|
import { useRealtimeBootstrap } from './composables/useRealtimeBootstrap';
|
||||||
import { useWatchedWorktrees } from './composables/useWatchedWorktrees';
|
import { useWatchedWorktrees } from './composables/useWatchedWorktrees';
|
||||||
|
import { useTerminalContext } from './composables/useTerminalContext';
|
||||||
import WsBanner from './components/layout/WsBanner.vue';
|
import WsBanner from './components/layout/WsBanner.vue';
|
||||||
import ToastContainer from './components/ToastContainer.vue';
|
import ToastContainer from './components/ToastContainer.vue';
|
||||||
import CommandPalette from './components/CommandPalette.vue';
|
import CommandPalette from './components/CommandPalette.vue';
|
||||||
@@ -24,4 +25,6 @@ const wsReconnecting = computed(() => wsClient.status.value === 'reconnecting');
|
|||||||
useRealtimeBootstrap();
|
useRealtimeBootstrap();
|
||||||
// Idem pour les abonnements ciblés `watch` : ils doivent survivre au démontage des panneaux.
|
// Idem pour les abonnements ciblés `watch` : ils doivent survivre au démontage des panneaux.
|
||||||
useWatchedWorktrees();
|
useWatchedWorktrees();
|
||||||
|
// Le terminal focalisé impose le worktree actif (propriétaire unique de cette écriture).
|
||||||
|
useTerminalContext();
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -53,7 +53,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue';
|
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { Search, GitBranch, TerminalSquare, Boxes, Plus, FolderPlus, Rocket } from '@lucide/vue';
|
import { Search, GitBranch, TerminalSquare, Boxes, Plus, FolderPlus, Rocket, SquareSplitHorizontal } from '@lucide/vue';
|
||||||
import type { WorktreeSummary } from '@arboretum/shared';
|
import type { WorktreeSummary } from '@arboretum/shared';
|
||||||
import { useSessionsStore } from '../stores/sessions';
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
@@ -126,6 +126,10 @@ const items = computed<PaletteItem[]>(() => {
|
|||||||
out.push({ id: 'act-newSession', type: 'action', label: t('palette.actions.newSession'), icon: Plus as Component, keywords: t('palette.actions.newSession').toLowerCase(), run: () => void modals.open(NewSessionModal) });
|
out.push({ id: 'act-newSession', type: 'action', label: t('palette.actions.newSession'), icon: Plus as Component, keywords: t('palette.actions.newSession').toLowerCase(), run: () => void modals.open(NewSessionModal) });
|
||||||
out.push({ id: 'act-addRepo', type: 'action', label: t('palette.actions.addRepo'), icon: FolderPlus as Component, keywords: t('palette.actions.addRepo').toLowerCase(), run: () => ide.setActivity('explorer') });
|
out.push({ id: 'act-addRepo', type: 'action', label: t('palette.actions.addRepo'), icon: FolderPlus as Component, keywords: t('palette.actions.addRepo').toLowerCase(), run: () => ide.setActivity('explorer') });
|
||||||
out.push({ id: 'act-newGroup', type: 'action', label: t('palette.actions.newGroup'), icon: Boxes as Component, keywords: t('palette.actions.newGroup').toLowerCase(), run: () => void modals.open(GroupCreateModal) });
|
out.push({ id: 'act-newGroup', type: 'action', label: t('palette.actions.newGroup'), icon: Boxes as Component, keywords: t('palette.actions.newGroup').toLowerCase(), run: () => void modals.open(GroupCreateModal) });
|
||||||
|
// Une SEULE entrée pour le split (et non une par session : la palette doublerait de taille).
|
||||||
|
if (ide.canSplitTerminal) {
|
||||||
|
out.push({ id: 'act-splitTerminal', type: 'action', label: t('palette.actions.splitTerminal'), icon: SquareSplitHorizontal as Component, keywords: t('palette.actions.splitTerminal').toLowerCase(), run: () => ide.splitTerminal() });
|
||||||
|
}
|
||||||
return out;
|
return out;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -41,8 +41,7 @@ const { t } = useI18n();
|
|||||||
const busy = ref(false);
|
const busy = ref(false);
|
||||||
const dialog = computed(() => (props.session.activity === 'waiting' ? props.session.dialog ?? null : null));
|
const dialog = computed(() => (props.session.activity === 'waiting' ? props.session.dialog ?? null : null));
|
||||||
|
|
||||||
// Sink no-op : l'attache de réponse n'affiche rien ; elle rappelle le callback du flow
|
// Sink no-op : cette attache n'affiche rien, elle sert uniquement à répondre.
|
||||||
// control pour ne jamais bloquer le PTY côté serveur.
|
|
||||||
const noopSink: TerminalSink = {
|
const noopSink: TerminalSink = {
|
||||||
write: (_data, cb) => cb?.(),
|
write: (_data, cb) => cb?.(),
|
||||||
reset: () => {},
|
reset: () => {},
|
||||||
@@ -52,7 +51,10 @@ const noopSink: TerminalSink = {
|
|||||||
|
|
||||||
let attachPromise: Promise<Attachment> | null = null;
|
let attachPromise: Promise<Attachment> | null = null;
|
||||||
function ensureAttached(): Promise<Attachment> {
|
function ensureAttached(): Promise<Attachment> {
|
||||||
attachPromise ??= wsClient.attach({ sessionId: props.session.id, mode: 'interactive', cols: 120, rows: 32, sink: noopSink });
|
// `screen: false` : sans lui, cette attache prenait le `controlling` de la session et imposait au
|
||||||
|
// PTY ses dimensions bidon (le terminal ouvert ensuite restait figé à 120x32, et ne pouvait plus
|
||||||
|
// se redimensionner) ; elle recevait en outre tout le flux de sortie pour le jeter.
|
||||||
|
attachPromise ??= wsClient.attach({ sessionId: props.session.id, mode: 'interactive', cols: 120, rows: 32, sink: noopSink, screen: false });
|
||||||
return attachPromise;
|
return attachPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,21 @@
|
|||||||
>
|
>
|
||||||
{{ t('terminal.sessionEnded') }}
|
{{ t('terminal.sessionEnded') }}
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="channelError"
|
||||||
|
class="absolute inset-x-0 top-0 border-b border-warn/40 bg-warn/15 px-4 py-2 text-center text-sm text-warn"
|
||||||
|
>
|
||||||
|
{{ channelError }}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="waitingOutput"
|
||||||
|
class="absolute inset-x-0 bottom-0 flex items-center justify-center gap-3 border-t border-border-soft bg-surface-1/95 px-4 py-2 text-xs text-fg-muted"
|
||||||
|
>
|
||||||
|
<span>{{ t('terminal.waitingForOutput') }}</span>
|
||||||
|
<button type="button" class="rounded-md border border-border px-2 py-0.5 text-fg hover:bg-surface-2" @click="refreshScreen">
|
||||||
|
{{ t('terminal.refreshScreen') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -37,6 +52,10 @@ const { t } = useI18n();
|
|||||||
const container = useTemplateRef<HTMLDivElement>('container');
|
const container = useTemplateRef<HTMLDivElement>('container');
|
||||||
const controlling = ref(true);
|
const controlling = ref(true);
|
||||||
const ended = ref(false);
|
const ended = ref(false);
|
||||||
|
/** « attaché, session vivante, mais rien à peindre » : sans cet état, la panne était un écran noir muet. */
|
||||||
|
const waitingOutput = ref(false);
|
||||||
|
/** Dernière erreur serveur portant sur ce canal (frappe refusée...), effacée d'elle-même. */
|
||||||
|
const channelError = ref<string | null>(null);
|
||||||
|
|
||||||
let term: Terminal | null = null;
|
let term: Terminal | null = null;
|
||||||
let attachment: Attachment | null = null;
|
let attachment: Attachment | null = null;
|
||||||
@@ -46,6 +65,40 @@ let onVisible: (() => void) | null = null;
|
|||||||
let onDomCopy: ((e: ClipboardEvent) => void) | null = null;
|
let onDomCopy: ((e: ClipboardEvent) => void) | null = null;
|
||||||
let stopThemeWatch: (() => void) | null = null;
|
let stopThemeWatch: (() => void) | null = null;
|
||||||
let disposed = false;
|
let disposed = false;
|
||||||
|
/** re-mesure + repaint, hissé hors de onMounted pour être appelable par le parent (colonnes du dock). */
|
||||||
|
let refit: (() => void) | null = null;
|
||||||
|
/** un seul octet reçu suffit à prouver que le canal peint : désarme la sonde ci-dessous. */
|
||||||
|
let gotOutput = false;
|
||||||
|
let outputProbe: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let errorTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
/** Délai avant de tenter un repaint forcé, puis avant de l'avouer à l'utilisateur. */
|
||||||
|
const OUTPUT_PROBE_MS = 1200;
|
||||||
|
const OUTPUT_GIVEUP_MS = 900;
|
||||||
|
|
||||||
|
function noteOutput(): void {
|
||||||
|
gotOutput = true;
|
||||||
|
waitingOutput.value = false;
|
||||||
|
if (outputProbe) {
|
||||||
|
clearTimeout(outputProbe);
|
||||||
|
outputProbe = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Force un repaint COMPLET du TUI en faisant varier la géométrie : un `TIOCSWINSZ` de taille
|
||||||
|
* différente provoque un SIGWINCH, seul signal auquel un TUI au repos (Ink de Claude, vim) réagit
|
||||||
|
* en redessinant tout. Le noyau n'émet rien si la taille est identique, d'où le passage par rows-1.
|
||||||
|
* Sans écran contrôlant, on se rabat sur un simple repaint local.
|
||||||
|
*/
|
||||||
|
function refreshScreen(): void {
|
||||||
|
const active = term;
|
||||||
|
if (!active) return;
|
||||||
|
if (attachment && controlling.value) {
|
||||||
|
attachment.resize(active.cols, Math.max(2, active.rows - 1));
|
||||||
|
attachment.resize(active.cols, active.rows);
|
||||||
|
}
|
||||||
|
active.refresh(0, active.rows - 1);
|
||||||
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
if (!container.value) return;
|
if (!container.value) return;
|
||||||
@@ -92,7 +145,7 @@ onMounted(async () => {
|
|||||||
// taille finale (la hauteur flex se résout après le 1er paint) → un seul `fit()` donne trop peu de
|
// taille finale (la hauteur flex se résout après le 1er paint) → un seul `fit()` donne trop peu de
|
||||||
// lignes et déforme le TUI. On refait donc le calcul en `requestAnimationFrame`, puis on resynchronise
|
// lignes et déforme le TUI. On refait donc le calcul en `requestAnimationFrame`, puis on resynchronise
|
||||||
// les dimensions PTY. Sert aussi après un resync (reconnexion) où l'écran est remis à plat.
|
// les dimensions PTY. Sert aussi après un resync (reconnexion) où l'écran est remis à plat.
|
||||||
const refit = (): void => {
|
const doRefit = (): void => {
|
||||||
try {
|
try {
|
||||||
fit.fit();
|
fit.fit();
|
||||||
} catch {
|
} catch {
|
||||||
@@ -103,10 +156,11 @@ onMounted(async () => {
|
|||||||
// d'arrière-plan, resync) → on force un rafraîchissement pour éviter un écran figé.
|
// d'arrière-plan, resync) → on force un rafraîchissement pour éviter un écran figé.
|
||||||
activeTerm.refresh(0, activeTerm.rows - 1);
|
activeTerm.refresh(0, activeTerm.rows - 1);
|
||||||
};
|
};
|
||||||
|
refit = doRefit; // exposé au parent (une colonne du dock re-mesure ses panes)
|
||||||
|
|
||||||
// Filet : re-mesure quand la fonte web est prête (au cas où le load ci-dessus n'a pas suffi).
|
// Filet : re-mesure quand la fonte web est prête (au cas où le load ci-dessus n'a pas suffi).
|
||||||
void document.fonts?.ready.then(() => {
|
void document.fonts?.ready.then(() => {
|
||||||
if (!disposed) refit();
|
if (!disposed) doRefit();
|
||||||
});
|
});
|
||||||
// Repeint xterm lors d'une bascule de thème clair/sombre (sans recréer le terminal).
|
// Repeint xterm lors d'une bascule de thème clair/sombre (sans recréer le terminal).
|
||||||
stopThemeWatch = watch(resolvedTheme, (r) => {
|
stopThemeWatch = watch(resolvedTheme, (r) => {
|
||||||
@@ -120,10 +174,13 @@ onMounted(async () => {
|
|||||||
cols: activeTerm.cols,
|
cols: activeTerm.cols,
|
||||||
rows: activeTerm.rows,
|
rows: activeTerm.rows,
|
||||||
sink: {
|
sink: {
|
||||||
write: (data, callback) => activeTerm.write(data, callback),
|
write: (data, callback) => {
|
||||||
|
noteOutput();
|
||||||
|
activeTerm.write(data, callback);
|
||||||
|
},
|
||||||
reset: () => {
|
reset: () => {
|
||||||
activeTerm.reset();
|
activeTerm.reset();
|
||||||
requestAnimationFrame(refit);
|
requestAnimationFrame(doRefit);
|
||||||
},
|
},
|
||||||
onDetached: (reason) => {
|
onDetached: (reason) => {
|
||||||
if (reason === 'session_exit' || reason === 'replaced') ended.value = true;
|
if (reason === 'session_exit' || reason === 'replaced') ended.value = true;
|
||||||
@@ -131,6 +188,15 @@ onMounted(async () => {
|
|||||||
onControlChanged: (c) => {
|
onControlChanged: (c) => {
|
||||||
controlling.value = c;
|
controlling.value = c;
|
||||||
},
|
},
|
||||||
|
onChannelError: (code, message) => {
|
||||||
|
// Une frappe refusée (observateur) ou un canal périmé ne doit plus disparaître en console.
|
||||||
|
channelError.value = code === 'NOT_CONTROLLING' ? t('terminal.observer') : message;
|
||||||
|
if (errorTimer) clearTimeout(errorTimer);
|
||||||
|
errorTimer = setTimeout(() => {
|
||||||
|
channelError.value = null;
|
||||||
|
errorTimer = null;
|
||||||
|
}, 4000);
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
@@ -144,7 +210,22 @@ onMounted(async () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
controlling.value = attachment.controlling;
|
controlling.value = attachment.controlling;
|
||||||
requestAnimationFrame(refit); // recale la taille une fois le layout fullbleed stabilisé
|
requestAnimationFrame(doRefit); // recale la taille une fois le layout fullbleed stabilisé
|
||||||
|
|
||||||
|
// Sonde anti-écran-noir : une session vivante à laquelle on est attaché doit avoir peint quelque
|
||||||
|
// chose (le replay du serveur, au minimum). Si rien n'arrive, on tente d'abord un repaint forcé
|
||||||
|
// (un TUI au repos ne réémet que sur SIGWINCH), et si cela ne suffit pas on le DIT, avec l'action
|
||||||
|
// qui débloque, au lieu de laisser un rectangle noir sans explication.
|
||||||
|
outputProbe = setTimeout(() => {
|
||||||
|
outputProbe = null;
|
||||||
|
if (disposed || gotOutput || ended.value) return;
|
||||||
|
refreshScreen();
|
||||||
|
outputProbe = setTimeout(() => {
|
||||||
|
outputProbe = null;
|
||||||
|
if (disposed || gotOutput || ended.value) return;
|
||||||
|
waitingOutput.value = true;
|
||||||
|
}, OUTPUT_GIVEUP_MS);
|
||||||
|
}, OUTPUT_PROBE_MS);
|
||||||
|
|
||||||
activeTerm.onData((data) => attachment?.sendStdin(data));
|
activeTerm.onData((data) => attachment?.sendStdin(data));
|
||||||
|
|
||||||
@@ -175,7 +256,7 @@ onMounted(async () => {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
};
|
};
|
||||||
document.addEventListener('copy', onDomCopy);
|
document.addEventListener('copy', onDomCopy);
|
||||||
resizeObserver = new ResizeObserver(refit);
|
resizeObserver = new ResizeObserver(doRefit);
|
||||||
resizeObserver.observe(container.value);
|
resizeObserver.observe(container.value);
|
||||||
// Re-révélation RÉELLE du conteneur : cellule de grille démontée/remontée (maximize↔grille), scroll
|
// Re-révélation RÉELLE du conteneur : cellule de grille démontée/remontée (maximize↔grille), scroll
|
||||||
// hors/dans le viewport, ou navigation SPA : autant de cas que `visibilitychange` (onglet only) ne
|
// hors/dans le viewport, ou navigation SPA : autant de cas que `visibilitychange` (onglet only) ne
|
||||||
@@ -186,7 +267,7 @@ onMounted(async () => {
|
|||||||
if (!entry.isIntersecting) continue;
|
if (!entry.isIntersecting) continue;
|
||||||
// évite un fit() sur conteneur de taille 0 (remontage transitoire) → déforme le TUI
|
// évite un fit() sur conteneur de taille 0 (remontage transitoire) → déforme le TUI
|
||||||
if (entry.intersectionRect.width === 0 || entry.intersectionRect.height === 0) continue;
|
if (entry.intersectionRect.width === 0 || entry.intersectionRect.height === 0) continue;
|
||||||
refit();
|
doRefit();
|
||||||
attachment?.flushAck();
|
attachment?.flushAck();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -205,9 +286,19 @@ onBeforeUnmount(() => {
|
|||||||
stopThemeWatch?.();
|
stopThemeWatch?.();
|
||||||
resizeObserver?.disconnect();
|
resizeObserver?.disconnect();
|
||||||
intersectionObserver?.disconnect();
|
intersectionObserver?.disconnect();
|
||||||
|
if (outputProbe) clearTimeout(outputProbe);
|
||||||
|
if (errorTimer) clearTimeout(errorTimer);
|
||||||
if (onVisible) document.removeEventListener('visibilitychange', onVisible);
|
if (onVisible) document.removeEventListener('visibilitychange', onVisible);
|
||||||
if (onDomCopy) document.removeEventListener('copy', onDomCopy);
|
if (onDomCopy) document.removeEventListener('copy', onDomCopy);
|
||||||
attachment?.detach();
|
attachment?.detach();
|
||||||
term?.dispose();
|
term?.dispose();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Le focus n'était posé qu'au montage : un pane laissé monté en v-show (bascule d'onglet, colonne
|
||||||
|
// réactivée) ne pouvait plus JAMAIS reprendre la frappe. Le parent le lui redonne explicitement.
|
||||||
|
defineExpose({
|
||||||
|
focus: (): void => term?.focus(),
|
||||||
|
refit: (): void => refit?.(),
|
||||||
|
refresh: refreshScreen,
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -57,13 +57,16 @@ import {
|
|||||||
Sun,
|
Sun,
|
||||||
} from '@lucide/vue';
|
} from '@lucide/vue';
|
||||||
import { useIdeStore, type ActivityView } from '../../stores/ide';
|
import { useIdeStore, type ActivityView } from '../../stores/ide';
|
||||||
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
import { useModalsStore } from '../../stores/modals';
|
import { useModalsStore } from '../../stores/modals';
|
||||||
|
import { pendingWorktreeCount } from '../../lib/changes-model';
|
||||||
import { useNav } from '../../composables/useNav';
|
import { useNav } from '../../composables/useNav';
|
||||||
import { useSession } from '../../composables/useSession';
|
import { useSession } from '../../composables/useSession';
|
||||||
import { themeMode, cycleTheme } from '../../lib/theme';
|
import { themeMode, cycleTheme } from '../../lib/theme';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
const modals = useModalsStore();
|
const modals = useModalsStore();
|
||||||
const { waitingCount } = useNav();
|
const { waitingCount } = useNav();
|
||||||
const { logout } = useSession();
|
const { logout } = useSession();
|
||||||
@@ -74,9 +77,13 @@ const HelpOverlay = defineAsyncComponent(() => import('./overlays/HelpOverlay.vu
|
|||||||
|
|
||||||
const isActive = (v: ActivityView): boolean => ide.activeActivity === v && ide.leftVisible;
|
const isActive = (v: ActivityView): boolean => ide.activeActivity === v && ide.leftVisible;
|
||||||
|
|
||||||
|
// Badge Git : nombre de worktrees à traiter (plus lisible qu'un nombre de fichiers, et il ne
|
||||||
|
// s'emballe pas). Dérivé des compteurs déjà diffusés par WS, donc sans aucune requête.
|
||||||
|
const gitBadge = computed(() => pendingWorktreeCount(worktrees.visibleRepos, (id) => worktrees.worktreesForRepo(id)));
|
||||||
|
|
||||||
const items = computed(() => [
|
const items = computed(() => [
|
||||||
{ view: 'explorer' as ActivityView, icon: FolderTree, label: t('ide.activity.explorer'), badge: 0 },
|
{ view: 'explorer' as ActivityView, icon: FolderTree, label: t('ide.activity.explorer'), badge: 0 },
|
||||||
{ view: 'git' as ActivityView, icon: GitCompare, label: t('ide.activity.git'), badge: 0 },
|
{ view: 'git' as ActivityView, icon: GitCompare, label: t('ide.activity.git'), badge: gitBadge.value },
|
||||||
{ view: 'sessions' as ActivityView, icon: SquareTerminal, label: t('ide.activity.sessions'), badge: waitingCount.value },
|
{ view: 'sessions' as ActivityView, icon: SquareTerminal, label: t('ide.activity.sessions'), badge: waitingCount.value },
|
||||||
{ view: 'groups' as ActivityView, icon: Boxes, label: t('ide.activity.groups'), badge: 0 },
|
{ view: 'groups' as ActivityView, icon: Boxes, label: t('ide.activity.groups'), badge: 0 },
|
||||||
]);
|
]);
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
type="button"
|
type="button"
|
||||||
class="truncate text-left font-mono text-[11px] text-warn/80 transition-colors hover:text-warn"
|
class="truncate text-left font-mono text-[11px] text-warn/80 transition-colors hover:text-warn"
|
||||||
:title="s.cwd"
|
:title="s.cwd"
|
||||||
@click="ide.openTerminal(s.id)"
|
@click="(e: MouseEvent) => ide.openTerminal(s.id, { split: e.altKey })"
|
||||||
>
|
>
|
||||||
{{ sessionLabel(s, worktrees) }}
|
{{ sessionLabel(s, worktrees) }}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex h-full min-h-0 flex-col">
|
||||||
|
<div class="label-mono flex items-center gap-2 px-3 py-2">
|
||||||
|
<GitCompare :size="13" />
|
||||||
|
{{ t('changes.title') }}
|
||||||
|
<span class="text-fg-subtle normal-case">{{ t('changes.summary', { n: pendingCount }, pendingCount) }}</span>
|
||||||
|
<span class="ml-auto flex min-w-0 items-center gap-1">
|
||||||
|
<!-- Portée : suivre le terminal focalisé (ou son groupe), ou tout voir. Le libellé dit
|
||||||
|
TOUJOURS ce qui serait suivi, y compris en mode « tout voir ». -->
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex min-w-0 items-center gap-1 rounded px-1 py-0.5 normal-case hover:bg-surface-2 hover:text-fg"
|
||||||
|
:class="scoped ? 'text-accent' : 'text-fg-subtle'"
|
||||||
|
:title="scoped ? t('changes.scope.all') : t('changes.scope.follow')"
|
||||||
|
@click="toggleScope"
|
||||||
|
>
|
||||||
|
<Crosshair :size="13" class="shrink-0" />
|
||||||
|
<span class="truncate text-[11px]">{{ scopeLabel }}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded p-0.5 hover:bg-surface-2 hover:text-fg"
|
||||||
|
:title="allExpanded ? t('changes.collapseAll') : t('changes.expandAll')"
|
||||||
|
@click="toggleAll"
|
||||||
|
>
|
||||||
|
<component :is="allExpanded ? FoldVertical : UnfoldVertical" :size="14" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded p-0.5 hover:bg-surface-2 hover:text-fg"
|
||||||
|
:class="ide.changesShowClean ? 'text-accent' : ''"
|
||||||
|
:title="ide.changesShowClean ? t('changes.hideClean') : t('changes.showClean')"
|
||||||
|
@click="ide.changesShowClean = !ide.changesShowClean"
|
||||||
|
>
|
||||||
|
<component :is="ide.changesShowClean ? Eye : EyeOff" :size="14" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded p-0.5 hover:bg-surface-2 hover:text-fg"
|
||||||
|
:title="t('common.refresh')"
|
||||||
|
@click="refreshAll"
|
||||||
|
>
|
||||||
|
<RefreshCw :size="14" />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="min-h-0 flex-1 overflow-auto pb-6">
|
||||||
|
<!-- Les trois états distingués, comme dans l'explorateur : chargement, échec, vide. -->
|
||||||
|
<SkeletonRow v-if="worktrees.loading && repos.length === 0" :count="4" :height="26" class="px-2 py-1" />
|
||||||
|
<div v-else-if="worktrees.loadError" class="px-3 py-2 text-xs">
|
||||||
|
<p class="text-danger">{{ worktrees.loadError }}</p>
|
||||||
|
<button type="button" class="mt-1 rounded px-1 text-accent hover:bg-surface-2" @click="worktrees.fetchAll()">
|
||||||
|
{{ t('common.retry') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<!-- « Tout est committé et poussé » serait un MENSONGE sous une portée restreinte : le travail
|
||||||
|
existe peut-être juste à côté. On le dit, avec la sortie. -->
|
||||||
|
<EmptyState
|
||||||
|
v-else-if="groups.length === 0 && scoped"
|
||||||
|
:icon="Crosshair"
|
||||||
|
:title="t('changes.scope.emptyInScope')"
|
||||||
|
:hint="t('changes.scope.emptyInScopeHint')"
|
||||||
|
class="m-6"
|
||||||
|
>
|
||||||
|
<template #action>
|
||||||
|
<button type="button" class="rounded-md border border-border px-2 py-1 text-xs text-accent hover:bg-surface-2" @click="toggleScope">
|
||||||
|
{{ t('changes.scope.all') }}
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
</EmptyState>
|
||||||
|
<EmptyState
|
||||||
|
v-else-if="groups.length === 0"
|
||||||
|
:icon="GitCompare"
|
||||||
|
:title="t('changes.allClean')"
|
||||||
|
:hint="t('changes.allCleanHint')"
|
||||||
|
class="m-6"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div v-for="g in groups" :key="g.repo.id">
|
||||||
|
<div class="flex items-center gap-1.5 border-b border-border bg-surface-1/60 px-2 py-1 text-xs">
|
||||||
|
<FolderGit2 :size="13" class="shrink-0" :style="tint(g.repo.id)" />
|
||||||
|
<span class="truncate font-medium" :title="g.repo.path">{{ g.repo.label }}</span>
|
||||||
|
<span class="shrink-0 text-[10px] text-fg-subtle">{{ t('changes.repoDirty', { n: g.dirtyFiles }, g.dirtyFiles) }}</span>
|
||||||
|
</div>
|
||||||
|
<ChangesWorktreeBlock v-for="wt in g.worktrees" :key="wtKey(wt.repoId, wt.path)" :wt="wt" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Vue « Changements » de la zone centrale : le statut git non commité de TOUS les projets ouverts,
|
||||||
|
// un bloc par worktree, avec de quoi indexer, committer et pousser sur place. Elle remplace le
|
||||||
|
// panneau latéral comme surface de travail ; la sidebar n'en garde que l'index.
|
||||||
|
import { computed, watch } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Crosshair, Eye, EyeOff, FoldVertical, FolderGit2, GitCompare, RefreshCw, UnfoldVertical } from '@lucide/vue';
|
||||||
|
import { useIdeStore, wtKey } from '../../stores/ide';
|
||||||
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
|
import { useGroupsStore } from '../../stores/groups';
|
||||||
|
import { useChangesStore } from '../../stores/changes';
|
||||||
|
import { groupWorktreesByRepo, pendingWorktreeCount } from '../../lib/changes-model';
|
||||||
|
import { useContextScope } from '../../composables/useContextScope';
|
||||||
|
import ChangesWorktreeBlock from './ChangesWorktreeBlock.vue';
|
||||||
|
import EmptyState from '../ui/EmptyState.vue';
|
||||||
|
import SkeletonRow from '../ui/SkeletonRow.vue';
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const groupsStore = useGroupsStore();
|
||||||
|
const changes = useChangesStore();
|
||||||
|
// Portée de travail : le terminal focalisé impose son worktree (ou son groupe). C'est ce qui évite de
|
||||||
|
// se perdre entre projets ; la bascule « tout voir » reste à un clic.
|
||||||
|
const { scope, scoped, label: scopeLabel, inScope, toggle: toggleScope } = useContextScope();
|
||||||
|
|
||||||
|
const repos = computed(() => worktrees.visibleRepos);
|
||||||
|
const groups = computed(() =>
|
||||||
|
groupWorktreesByRepo(repos.value, (id) => worktrees.worktreesForRepo(id), {
|
||||||
|
showClean: ide.changesShowClean,
|
||||||
|
active: ide.activeContext,
|
||||||
|
inScope: inScope.value,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const pendingCount = computed(() => pendingWorktreeCount(repos.value, (id) => worktrees.worktreesForRepo(id), inScope.value));
|
||||||
|
|
||||||
|
const allKeys = computed(() => groups.value.flatMap((g) => g.worktrees.map((w) => wtKey(w.repoId, w.path))));
|
||||||
|
const allExpanded = computed(() => allKeys.value.length > 0 && allKeys.value.every((k) => ide.changesExpanded.includes(k)));
|
||||||
|
|
||||||
|
// Teinte de groupe : relie visuellement un dépôt à son groupe, comme dans l'explorateur.
|
||||||
|
function tint(repoId: string): Record<string, string> {
|
||||||
|
const color = groupsStore.colorForRepo(repoId);
|
||||||
|
return color ? { color } : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleAll(): void {
|
||||||
|
ide.setChangesExpanded(allExpanded.value ? [] : allKeys.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Premier affichage : les blocs sont repliés par défaut (aucune requête), mais une vue entièrement
|
||||||
|
// repliée ne montre rien. On déplie donc le premier bloc, celui du worktree actif s'il est listé.
|
||||||
|
watch(
|
||||||
|
// La portée compte comme dépendance : changer de terminal renouvelle la liste, et sans cela la vue
|
||||||
|
// restait entièrement repliée sur le nouveau contexte.
|
||||||
|
() => [allKeys.value, scope.value] as const,
|
||||||
|
([keys]) => {
|
||||||
|
if (keys.length === 0 || keys.some((k) => ide.changesExpanded.includes(k))) return;
|
||||||
|
const ctx = ide.activeContext;
|
||||||
|
const preferred = ctx ? wtKey(ctx.repoId, ctx.wtPath) : null;
|
||||||
|
ide.setChangesExpanded([preferred && keys.includes(preferred) ? preferred : keys[0]!]);
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
function refreshAll(): void {
|
||||||
|
changes.invalidateAll();
|
||||||
|
for (const key of ide.changesExpanded) {
|
||||||
|
const wt = worktrees.worktrees.find((w) => wtKey(w.repoId, w.path) === key);
|
||||||
|
if (wt) changes.request(wt.repoId, wt.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
<template>
|
||||||
|
<div class="border-b border-border">
|
||||||
|
<!-- En-tête : ZÉRO requête, tout vient du WorktreeSummary diffusé par WS. -->
|
||||||
|
<div class="flex items-center gap-2 px-2 py-1.5" :class="isActive ? 'bg-surface-2/60' : 'hover:bg-surface-2/30'">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex min-w-0 flex-1 items-center gap-1.5 text-left text-xs"
|
||||||
|
:aria-expanded="expanded"
|
||||||
|
@click="onToggle"
|
||||||
|
>
|
||||||
|
<component :is="expanded ? ChevronDown : ChevronRight" :size="13" class="shrink-0 text-fg-subtle" />
|
||||||
|
<component :is="wt.isMain ? Home : GitBranch" :size="13" class="shrink-0 text-fg-subtle" />
|
||||||
|
<span class="truncate font-mono" :title="wt.path">{{ wt.branch ?? t('worktrees.detached') }}</span>
|
||||||
|
<GitStatusBadge :git="wt.git" :branch="wt.branch" dense class="shrink-0" />
|
||||||
|
<!-- L'upstream est déjà nommé sur la ligne d'actions distantes juste en dessous : ici on ne
|
||||||
|
garde que ce qui appelle une action, ou l'état « propre ». -->
|
||||||
|
<span v-if="unpushed" class="shrink-0 text-[10px] text-warn">{{ t('changes.unpushed', { n: unpushed }) }}</span>
|
||||||
|
<span v-else-if="clean" class="shrink-0 text-[10px] text-fg-subtle">{{ t('changes.clean') }}</span>
|
||||||
|
</button>
|
||||||
|
<!-- Boutons frères et non imbriqués : un bouton dans un bouton est invalide. -->
|
||||||
|
<button
|
||||||
|
v-if="selected"
|
||||||
|
type="button"
|
||||||
|
class="shrink-0 rounded p-0.5 text-fg-subtle hover:bg-surface-3 hover:text-fg"
|
||||||
|
:title="t('changes.openInEditor')"
|
||||||
|
@click="openInEditor"
|
||||||
|
>
|
||||||
|
<FileCode :size="13" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="shrink-0 rounded p-0.5 text-fg-subtle hover:bg-surface-3 hover:text-fg"
|
||||||
|
:title="t('common.refresh')"
|
||||||
|
@click="changes.invalidate(wt.repoId, wt.path)"
|
||||||
|
>
|
||||||
|
<RefreshCw :size="13" :class="entry?.loading ? 'animate-spin' : undefined" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-if="expanded">
|
||||||
|
<div v-if="entry?.error" class="flex items-center gap-2 px-3 py-1.5 text-xs text-danger">
|
||||||
|
<span class="min-w-0 flex-1">{{ t('changes.loadFailed') }} {{ entry.error }}</span>
|
||||||
|
<BaseButton size="sm" variant="ghost" @click="changes.invalidate(wt.repoId, wt.path)">{{ t('common.retry') }}</BaseButton>
|
||||||
|
</div>
|
||||||
|
<SkeletonRow v-if="entry?.loading && entry.changes.length === 0" :count="3" :height="18" class="px-2 py-1" />
|
||||||
|
|
||||||
|
<CommitPanel
|
||||||
|
:repo-id="wt.repoId"
|
||||||
|
:wt="wt.path"
|
||||||
|
:changes="entry?.changes ?? []"
|
||||||
|
:git="wt.git"
|
||||||
|
:truncated="entry?.truncated ?? false"
|
||||||
|
:active="selected?.file ?? null"
|
||||||
|
@select="onSelect"
|
||||||
|
@changed="changes.invalidate(wt.repoId, wt.path)"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<DiffViewer
|
||||||
|
v-if="selected"
|
||||||
|
:key="`d:${selected.file}:${selected.staged}`"
|
||||||
|
:repo-id="wt.repoId"
|
||||||
|
:wt="wt.path"
|
||||||
|
:file="selected.file"
|
||||||
|
:staged="selected.staged"
|
||||||
|
:version="version"
|
||||||
|
class="max-h-96 border-y border-border bg-surface-1/40"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<CommitHistory :repo-id="wt.repoId" :wt="wt.path" :version="version" />
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Un worktree dans la vue « Changements » : en-tête toujours peu coûteux (compteurs WS), et si
|
||||||
|
// déplié, le panneau de commit, le diff du fichier sélectionné INLINE, puis l'historique.
|
||||||
|
// Le diff est inline et non en onglet : en mode « changements », un onglet est masqué par
|
||||||
|
// construction, donc le clic n'aurait aucun effet visible. Le bouton FileCode garde la porte de
|
||||||
|
// sortie vers l'éditeur plein cadre.
|
||||||
|
import { computed, ref, watch } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { ChevronDown, ChevronRight, FileCode, GitBranch, Home, RefreshCw } from '@lucide/vue';
|
||||||
|
import type { WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import { useIdeStore, tabId, wtKey } from '../../stores/ide';
|
||||||
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
|
import { useChangesStore } from '../../stores/changes';
|
||||||
|
import CommitPanel from '../workspace/CommitPanel.vue';
|
||||||
|
import CommitHistory from '../workspace/CommitHistory.vue';
|
||||||
|
import DiffViewer from '../workspace/DiffViewer.vue';
|
||||||
|
import GitStatusBadge from '../workspace/GitStatusBadge.vue';
|
||||||
|
import BaseButton from '../ui/BaseButton.vue';
|
||||||
|
import SkeletonRow from '../ui/SkeletonRow.vue';
|
||||||
|
|
||||||
|
const props = defineProps<{ wt: WorktreeSummary }>();
|
||||||
|
const { t } = useI18n();
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const changes = useChangesStore();
|
||||||
|
|
||||||
|
const selected = ref<{ file: string; staged: boolean } | null>(null);
|
||||||
|
|
||||||
|
const key = computed(() => wtKey(props.wt.repoId, props.wt.path));
|
||||||
|
const expanded = computed(() => ide.changesExpanded.includes(key.value));
|
||||||
|
const isActive = computed(
|
||||||
|
() => ide.activeContext?.repoId === props.wt.repoId && ide.activeContext?.wtPath === props.wt.path,
|
||||||
|
);
|
||||||
|
const version = computed(() => worktrees.changeVersion(props.wt.repoId, props.wt.path));
|
||||||
|
const entry = computed(() => changes.entry(props.wt.repoId, props.wt.path));
|
||||||
|
const unpushed = computed(() => (props.wt.git.upstream ? props.wt.git.ahead : 0));
|
||||||
|
const clean = computed(() => props.wt.git.dirtyCount === 0 && props.wt.git.ahead === 0 && props.wt.git.behind === 0);
|
||||||
|
|
||||||
|
function onToggle(): void {
|
||||||
|
ide.toggleChangesWt(key.value);
|
||||||
|
ide.setActiveWorktree(props.wt.repoId, props.wt.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSelect(sel: { file: string; staged: boolean }): void {
|
||||||
|
// Second clic sur la même ligne : on replie le diff (même geste que l'historique des commits).
|
||||||
|
selected.value =
|
||||||
|
selected.value?.file === sel.file && selected.value.staged === sel.staged ? null : { ...sel };
|
||||||
|
}
|
||||||
|
|
||||||
|
function openInEditor(): void {
|
||||||
|
const sel = selected.value;
|
||||||
|
if (!sel) return;
|
||||||
|
ide.openFile(props.wt.repoId, props.wt.path, sel.file, 'diff');
|
||||||
|
ide.setTabView(tabId(props.wt.repoId, props.wt.path, sel.file), 'diff', sel.staged);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Charge à l'ouverture, recharge dès que le disque bouge, libère au repli (bornage mémoire sur un
|
||||||
|
// parc de dépôts important).
|
||||||
|
watch(
|
||||||
|
() => [expanded.value, version.value] as const,
|
||||||
|
([open]) => {
|
||||||
|
if (open) changes.request(props.wt.repoId, props.wt.path);
|
||||||
|
else changes.forget(props.wt.repoId, props.wt.path);
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
// Le fichier sélectionné a disparu de la liste (commité, abandonné) : on replie le diff.
|
||||||
|
watch(
|
||||||
|
() => entry.value?.changes,
|
||||||
|
(list) => {
|
||||||
|
if (selected.value && list && !list.some((c) => c.path === selected.value?.file)) selected.value = null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
</script>
|
||||||
@@ -1,7 +1,14 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="flex h-full min-h-0 flex-col">
|
<div class="flex h-full min-h-0 flex-col">
|
||||||
<EditorTabs />
|
<EditorTabs>
|
||||||
|
<template #trailing>
|
||||||
|
<SegmentedControl v-model="modeModel" :options="modeOptions" />
|
||||||
|
</template>
|
||||||
|
</EditorTabs>
|
||||||
|
|
||||||
|
<!-- Mode « fichiers » en v-show et JAMAIS en v-if : l'unique instance Monaco, ses modèles et son
|
||||||
|
conteneur doivent survivre à un aller-retour vers la vue Changements. -->
|
||||||
|
<div v-show="ide.centerMode === 'files'" class="flex min-h-0 flex-1 flex-col">
|
||||||
<template v-if="activeTab">
|
<template v-if="activeTab">
|
||||||
<!-- barre : bascule éditeur/diff + chemin + save -->
|
<!-- barre : bascule éditeur/diff + chemin + save -->
|
||||||
<div class="flex items-center gap-2 border-b border-border px-2 py-1 text-xs">
|
<div class="flex items-center gap-2 border-b border-border px-2 py-1 text-xs">
|
||||||
@@ -32,9 +39,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="loadError && activeTab.view === 'editor'" class="px-3 py-1 text-xs text-danger">{{ loadError }}</p>
|
<p v-if="loadError && activeTab.view === 'editor'" class="px-3 py-1 text-xs text-danger">{{ loadError }}</p>
|
||||||
|
<p v-else-if="syncError && activeTab.view === 'editor'" class="px-3 py-1 text-xs text-warn">{{ syncError }}</p>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Zone de rendu TOUJOURS montée : ce conteneur porte le DOM de l'unique instance Monaco.
|
||||||
|
Sous un v-if, il était détruit à la fermeture du dernier onglet (l'éditeur pointait alors
|
||||||
|
sur un noeud détaché : zone vide définitive) et absent au montage sans onglet actif
|
||||||
|
(l'éditeur n'était alors JAMAIS créé, ce qui laissait le premier fichier ouvert vide et
|
||||||
|
muet). Les autres états sont des surcouches. Ne jamais repasser ce bloc en v-if. -->
|
||||||
<div class="relative min-h-0 flex-1">
|
<div class="relative min-h-0 flex-1">
|
||||||
<div v-show="activeTab.view === 'editor'" ref="host" class="h-full min-h-0" />
|
<div v-show="activeTab?.view === 'editor'" ref="host" data-editor-host class="h-full min-h-0" />
|
||||||
|
|
||||||
|
<template v-if="activeTab">
|
||||||
<DiffViewer
|
<DiffViewer
|
||||||
v-if="activeTab.view === 'diff'"
|
v-if="activeTab.view === 'diff'"
|
||||||
:key="`diff:${activeTab.id}`"
|
:key="`diff:${activeTab.id}`"
|
||||||
@@ -45,20 +61,43 @@
|
|||||||
:version="activeVersion"
|
:version="activeVersion"
|
||||||
class="h-full"
|
class="h-full"
|
||||||
/>
|
/>
|
||||||
|
<!-- Chunk de l'éditeur introuvable (build remplacé, index.html périmé, réseau) : la zone
|
||||||
|
restait vide et muette pour toute la session. -->
|
||||||
|
<div v-else-if="monacoStatus === 'error'" class="absolute inset-0 flex items-center justify-center bg-surface-0 p-6">
|
||||||
|
<EmptyState :icon="TriangleAlert" :title="t('editor.loadFailed')" :hint="monacoErrorHint">
|
||||||
|
<template #action>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<BaseButton size="sm" :icon="RefreshCw" @click="retryMonaco">{{ t('common.retry') }}</BaseButton>
|
||||||
|
<BaseButton size="sm" variant="ghost" @click="reloadPage">{{ t('editor.reloadPage') }}</BaseButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</EmptyState>
|
||||||
|
</div>
|
||||||
|
<!-- Attente visible : téléchargement du chunk éditeur, puis lecture REST du fichier. -->
|
||||||
|
<div v-else-if="busy" class="absolute inset-0 bg-surface-0 p-3">
|
||||||
|
<p class="pb-2 text-xs text-fg-subtle">
|
||||||
|
{{ monacoStatus === 'loading' ? t('editor.loadingEditor') : t('editor.loadingFile') }}
|
||||||
|
</p>
|
||||||
|
<SkeletonRow :count="8" :height="12" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<EmptyState v-else :icon="FileCode" :title="t('ide.noFileOpen')" :hint="t('ide.noFileHint')" class="m-6" />
|
<EmptyState v-else :icon="FileCode" :title="t('ide.noFileOpen')" :hint="t('ide.noFileHint')" class="m-6" />
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ChangesView v-if="ide.centerMode === 'changes'" class="min-h-0 flex-1" />
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// Zone centrale de l'IDE : UNE seule instance Monaco partagée entre tous les onglets, avec un cache
|
// Zone centrale de l'IDE. Deux modes : « fichiers » (UNE seule instance Monaco partagée entre tous
|
||||||
// de modèles (préserve contenu, historique undo et position du curseur au changement d'onglet).
|
// les onglets, avec un cache de modèles qui préserve contenu, historique undo et position du
|
||||||
|
// curseur) et « changements » (statut git non commité de tous les projets ouverts).
|
||||||
// Les onglets « diff » réutilisent DiffViewer. Le dirty est remonté au store IDE.
|
// Les onglets « diff » réutilisent DiffViewer. Le dirty est remonté au store IDE.
|
||||||
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, useTemplateRef, watch } from 'vue';
|
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, useTemplateRef, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { FileCode, Save, TriangleAlert } from '@lucide/vue';
|
import { FileCode, GitCompare, RefreshCw, Save, TriangleAlert } from '@lucide/vue';
|
||||||
import type * as Monaco from 'monaco-editor';
|
import type * as Monaco from 'monaco-editor';
|
||||||
import { useIdeStore, type EditorTab } from '../../stores/ide';
|
import { useIdeStore, type EditorTab } from '../../stores/ide';
|
||||||
import { useWorktreesStore } from '../../stores/worktrees';
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
@@ -67,10 +106,12 @@ import { ApiError } from '../../lib/api';
|
|||||||
import { loadMonaco } from '../../composables/useMonaco';
|
import { loadMonaco } from '../../composables/useMonaco';
|
||||||
import { resolvedTheme } from '../../lib/theme';
|
import { resolvedTheme } from '../../lib/theme';
|
||||||
import EditorTabs from './EditorTabs.vue';
|
import EditorTabs from './EditorTabs.vue';
|
||||||
|
import ChangesView from './ChangesView.vue';
|
||||||
import DiffViewer from '../workspace/DiffViewer.vue';
|
import DiffViewer from '../workspace/DiffViewer.vue';
|
||||||
import SegmentedControl from '../ui/SegmentedControl.vue';
|
import SegmentedControl from '../ui/SegmentedControl.vue';
|
||||||
import BaseButton from '../ui/BaseButton.vue';
|
import BaseButton from '../ui/BaseButton.vue';
|
||||||
import EmptyState from '../ui/EmptyState.vue';
|
import EmptyState from '../ui/EmptyState.vue';
|
||||||
|
import SkeletonRow from '../ui/SkeletonRow.vue';
|
||||||
|
|
||||||
interface ModelEntry {
|
interface ModelEntry {
|
||||||
model: Monaco.editor.ITextModel;
|
model: Monaco.editor.ITextModel;
|
||||||
@@ -83,10 +124,17 @@ const ide = useIdeStore();
|
|||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
const host = useTemplateRef<HTMLDivElement>('host');
|
const host = useTemplateRef<HTMLDivElement>('host');
|
||||||
|
|
||||||
const ready = ref(false);
|
|
||||||
const saving = ref(false);
|
const saving = ref(false);
|
||||||
const conflict = ref(false);
|
const conflict = ref(false);
|
||||||
const loadError = ref<string | null>(null);
|
const loadError = ref<string | null>(null);
|
||||||
|
// Erreur de RELECTURE disque : avertissement, pas panne. Le buffer reste éditable.
|
||||||
|
const syncError = ref<string | null>(null);
|
||||||
|
// Cycle de vie de l'unique instance Monaco. 'idle' : pas encore demandée, donc chunk non tiré.
|
||||||
|
const monacoStatus = ref<'idle' | 'loading' | 'ready' | 'error'>('idle');
|
||||||
|
const monacoError = ref<string | null>(null);
|
||||||
|
// Onglet dont le contenu est en cours de lecture : borné à l'onglet, donc le voile ne reste pas
|
||||||
|
// collé après un enchaînement rapide d'onglets.
|
||||||
|
const loadingTabId = ref<string | null>(null);
|
||||||
|
|
||||||
let monaco: typeof Monaco | null = null;
|
let monaco: typeof Monaco | null = null;
|
||||||
const editor = shallowRef<Monaco.editor.IStandaloneCodeEditor | null>(null);
|
const editor = shallowRef<Monaco.editor.IStandaloneCodeEditor | null>(null);
|
||||||
@@ -113,10 +161,62 @@ const viewModel = computed<string>({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
onMounted(async () => {
|
// Bascule de MODE de la zone (icônes seules, dans la barre d'onglets), à ne pas confondre avec la
|
||||||
monaco = await loadMonaco();
|
// bascule de VUE ci-dessus (libellés texte, portée : l'onglet actif).
|
||||||
if (disposed || !host.value) return;
|
const modeOptions = computed(() => [
|
||||||
editor.value = monaco.editor.create(host.value, {
|
{ value: 'files', icon: FileCode, title: t('workspace.files') },
|
||||||
|
{ value: 'changes', icon: GitCompare, title: t('workspace.changes') },
|
||||||
|
]);
|
||||||
|
const modeModel = computed<string>({
|
||||||
|
get: () => ide.centerMode,
|
||||||
|
set: (v) => ide.setCenterMode(v === 'changes' ? 'changes' : 'files'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const ready = computed(() => monacoStatus.value === 'ready'); // n'arme QUE le bouton Enregistrer
|
||||||
|
const fileLoading = computed(() => !!activeTab.value && loadingTabId.value === activeTab.value.id);
|
||||||
|
const busy = computed(() => monacoStatus.value === 'loading' || fileLoading.value);
|
||||||
|
const monacoErrorHint = computed(() =>
|
||||||
|
monacoError.value ? `${t('editor.loadFailedHint')} (${monacoError.value})` : t('editor.loadFailedHint'),
|
||||||
|
);
|
||||||
|
|
||||||
|
let creating: Promise<Monaco.editor.IStandaloneCodeEditor | null> | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée l'unique instance Monaco à la PREMIÈRE demande d'affichage, une seule fois (appels
|
||||||
|
* concurrents partagés). Paresseux et non plus au montage, pour deux raisons : l'IDE est couramment
|
||||||
|
* monté sans aucun onglet (premier usage, tous les onglets fermés), cas où l'ancien `onMounted`
|
||||||
|
* sortait en silence sur `!host.value` et laissait l'éditeur inexistant pour toute la session ; et
|
||||||
|
* le conteneur doit être visible et mesurable au moment de la création.
|
||||||
|
*/
|
||||||
|
function ensureEditor(): Promise<Monaco.editor.IStandaloneCodeEditor | null> {
|
||||||
|
if (editor.value) return Promise.resolve(editor.value);
|
||||||
|
creating ??= createEditor().finally(() => {
|
||||||
|
creating = null; // un échec doit rester réessayable
|
||||||
|
});
|
||||||
|
return creating;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createEditor(): Promise<Monaco.editor.IStandaloneCodeEditor | null> {
|
||||||
|
monacoStatus.value = 'loading';
|
||||||
|
monacoError.value = null;
|
||||||
|
let mod: typeof Monaco;
|
||||||
|
try {
|
||||||
|
mod = await loadMonaco();
|
||||||
|
} catch (err) {
|
||||||
|
// Rejet enfin traité : l'ancien `await loadMonaco()` nu dans un onMounted async partait en rejet
|
||||||
|
// non géré, sans le moindre message à l'écran.
|
||||||
|
if (!disposed) {
|
||||||
|
monacoStatus.value = 'error';
|
||||||
|
monacoError.value = err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
monaco = mod;
|
||||||
|
// Le conteneur vient peut-être d'apparaître (v-show piloté par activeTab) et le watcher est en
|
||||||
|
// flush 'pre' : on attend le patch DOM pour que Monaco mesure une taille réelle.
|
||||||
|
await nextTick();
|
||||||
|
if (disposed || !host.value) return null;
|
||||||
|
const ed = mod.editor.create(host.value, {
|
||||||
value: '',
|
value: '',
|
||||||
theme: resolvedTheme.value === 'light' ? 'arboretum-light' : 'arboretum-dark',
|
theme: resolvedTheme.value === 'light' ? 'arboretum-light' : 'arboretum-dark',
|
||||||
automaticLayout: true,
|
automaticLayout: true,
|
||||||
@@ -129,22 +229,46 @@ onMounted(async () => {
|
|||||||
});
|
});
|
||||||
// Re-mesure après chargement de la fonte web (sinon curseur/colonnes décalés).
|
// Re-mesure après chargement de la fonte web (sinon curseur/colonnes décalés).
|
||||||
void document.fonts?.ready.then(() => {
|
void document.fonts?.ready.then(() => {
|
||||||
if (!disposed) monaco?.editor.remeasureFonts();
|
if (!disposed) mod.editor.remeasureFonts();
|
||||||
});
|
});
|
||||||
editor.value.onDidChangeModelContent(() => {
|
ed.onDidChangeModelContent(() => {
|
||||||
if (!shownTabId) return;
|
if (!shownTabId) return;
|
||||||
const entry = entries.get(shownTabId);
|
const entry = entries.get(shownTabId);
|
||||||
if (entry) ide.setTabDirty(shownTabId, entry.model.getValue() !== entry.savedContent);
|
if (entry) ide.setTabDirty(shownTabId, entry.model.getValue() !== entry.savedContent);
|
||||||
});
|
});
|
||||||
editor.value.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => void save());
|
ed.addCommand(mod.KeyMod.CtrlCmd | mod.KeyCode.KeyS, () => void save());
|
||||||
ready.value = true;
|
editor.value = ed;
|
||||||
if (activeTab.value && activeTab.value.view === 'editor') await showTab(activeTab.value);
|
monacoStatus.value = 'ready';
|
||||||
|
return ed;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function retryMonaco(): Promise<void> {
|
||||||
|
monacoStatus.value = 'idle';
|
||||||
|
monacoError.value = null;
|
||||||
|
const tab = activeTab.value;
|
||||||
|
if (tab && tab.view === 'editor') await showTab(tab);
|
||||||
|
else await ensureEditor();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recours garanti : un `import()` déjà en échec est mémorisé par la module map du navigateur, un
|
||||||
|
// nouvel essai en page ne récupère donc pas toujours. Sans éditeur il n'y a aucun buffer à perdre.
|
||||||
|
function reloadPage(): void {
|
||||||
|
location.reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restauration au montage : un onglet persisté doit s'afficher sans geste (F5, et sur mobile où
|
||||||
|
// EditorArea est monté/démonté à chaque changement de panneau). Sans onglet : rien n'est chargé.
|
||||||
|
onMounted(() => {
|
||||||
|
const tab = activeTab.value;
|
||||||
|
if (tab && tab.view === 'editor') void showTab(tab);
|
||||||
});
|
});
|
||||||
|
|
||||||
async function ensureEntry(tab: EditorTab): Promise<ModelEntry | null> {
|
async function ensureEntry(tab: EditorTab): Promise<ModelEntry | null> {
|
||||||
const cached = entries.get(tab.id);
|
const cached = entries.get(tab.id);
|
||||||
if (cached) return cached;
|
if (cached) return cached;
|
||||||
if (!monaco) return null;
|
if (!monaco) return null;
|
||||||
|
loadingTabId.value = tab.id; // lecture REST : plusieurs secondes possibles, il faut le montrer
|
||||||
|
try {
|
||||||
const res = await gitApi.readFile(tab.repoId, tab.wtPath, tab.file);
|
const res = await gitApi.readFile(tab.repoId, tab.wtPath, tab.file);
|
||||||
if (disposed) return null;
|
if (disposed) return null;
|
||||||
const uri = monaco.Uri.parse(`inmemory://arb/${encodeURIComponent(tab.id)}`);
|
const uri = monaco.Uri.parse(`inmemory://arb/${encodeURIComponent(tab.id)}`);
|
||||||
@@ -152,17 +276,24 @@ async function ensureEntry(tab: EditorTab): Promise<ModelEntry | null> {
|
|||||||
const entry: ModelEntry = { model, baseMtime: res.mtime, savedContent: res.content };
|
const entry: ModelEntry = { model, baseMtime: res.mtime, savedContent: res.content };
|
||||||
entries.set(tab.id, entry);
|
entries.set(tab.id, entry);
|
||||||
return entry;
|
return entry;
|
||||||
|
} finally {
|
||||||
|
if (loadingTabId.value === tab.id) loadingTabId.value = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Unique entonnoir « quelque chose doit s'afficher » : c'est lui qui crée l'éditeur au besoin. */
|
||||||
async function showTab(tab: EditorTab): Promise<void> {
|
async function showTab(tab: EditorTab): Promise<void> {
|
||||||
if (!editor.value) return;
|
|
||||||
loadError.value = null;
|
loadError.value = null;
|
||||||
conflict.value = false;
|
conflict.value = false;
|
||||||
// sauvegarde de la position/scroll de l'onglet quitté
|
syncError.value = null;
|
||||||
if (shownTabId && shownTabId !== tab.id) viewStates.set(shownTabId, editor.value.saveViewState());
|
// sauvegarde de la position/scroll de l'onglet quitté, avant tout await
|
||||||
|
if (editor.value && shownTabId && shownTabId !== tab.id) viewStates.set(shownTabId, editor.value.saveViewState());
|
||||||
|
const ed = await ensureEditor();
|
||||||
|
if (!ed || disposed) return;
|
||||||
try {
|
try {
|
||||||
const entry = await ensureEntry(tab);
|
const entry = await ensureEntry(tab);
|
||||||
if (!entry || disposed || !editor.value) return;
|
if (!entry || disposed || !editor.value) return;
|
||||||
|
if (activeTab.value?.id !== tab.id) return; // un autre onglet a pris la main pendant la lecture
|
||||||
editor.value.setModel(entry.model);
|
editor.value.setModel(entry.model);
|
||||||
const vs = viewStates.get(tab.id);
|
const vs = viewStates.get(tab.id);
|
||||||
if (vs) editor.value.restoreViewState(vs);
|
if (vs) editor.value.restoreViewState(vs);
|
||||||
@@ -227,6 +358,7 @@ async function reload(): Promise<void> {
|
|||||||
entry.baseMtime = res.mtime;
|
entry.baseMtime = res.mtime;
|
||||||
entry.savedContent = res.content;
|
entry.savedContent = res.content;
|
||||||
conflict.value = false;
|
conflict.value = false;
|
||||||
|
syncError.value = null;
|
||||||
ide.setTabDirty(tab.id, false);
|
ide.setTabDirty(tab.id, false);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
loadError.value = err instanceof Error ? err.message : String(err);
|
loadError.value = err instanceof Error ? err.message : String(err);
|
||||||
@@ -244,6 +376,7 @@ async function syncActiveTabFromDisk(): Promise<void> {
|
|||||||
if (!tab || tab.view !== 'editor' || saving.value) return;
|
if (!tab || tab.view !== 'editor' || saving.value) return;
|
||||||
const entry = entries.get(tab.id);
|
const entry = entries.get(tab.id);
|
||||||
if (!entry) return;
|
if (!entry) return;
|
||||||
|
syncError.value = null;
|
||||||
try {
|
try {
|
||||||
const res = await gitApi.readFile(tab.repoId, tab.wtPath, tab.file);
|
const res = await gitApi.readFile(tab.repoId, tab.wtPath, tab.file);
|
||||||
if (res.mtime === entry.baseMtime || res.content === entry.savedContent) return; // ce fichier-là n'a pas changé
|
if (res.mtime === entry.baseMtime || res.content === entry.savedContent) return; // ce fichier-là n'a pas changé
|
||||||
@@ -255,20 +388,23 @@ async function syncActiveTabFromDisk(): Promise<void> {
|
|||||||
entry.baseMtime = res.mtime;
|
entry.baseMtime = res.mtime;
|
||||||
entry.savedContent = res.content;
|
entry.savedContent = res.content;
|
||||||
ide.setTabDirty(tab.id, false);
|
ide.setTabDirty(tab.id, false);
|
||||||
} catch {
|
} catch (err) {
|
||||||
/* fichier supprimé ou illisible : on laisse l'onglet en place, la sauvegarde tranchera */
|
// Le fichier n'est plus lisible (déplacé, supprimé, droits) : on garde l'onglet et le buffer,
|
||||||
|
// mais on le DIT. Avalé en silence, l'utilisateur continuait d'éditer un fichier fantôme et ne
|
||||||
|
// l'apprenait qu'au moment de la sauvegarde.
|
||||||
|
syncError.value = `${t('editor.syncFailed')} : ${err instanceof Error ? err.message : String(err)}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(activeVersion, () => {
|
watch(activeVersion, () => void syncActiveTabFromDisk());
|
||||||
if (ready.value) void syncActiveTabFromDisk();
|
|
||||||
});
|
|
||||||
|
|
||||||
// changement d'onglet actif -> affiche le bon modèle (si vue éditeur).
|
// changement d'onglet actif -> affiche le bon modèle (si vue éditeur). Plus de garde `ready` : c'est
|
||||||
|
// showTab qui crée l'éditeur au besoin. Cette garde faisait que le PREMIER fichier ouvert n'affichait
|
||||||
|
// rien quand l'IDE avait été monté sans onglet actif.
|
||||||
watch(
|
watch(
|
||||||
() => [activeTab.value?.id, activeTab.value?.view] as const,
|
() => [activeTab.value?.id, activeTab.value?.view] as const,
|
||||||
([, view]) => {
|
([, view]) => {
|
||||||
if (ready.value && activeTab.value && view === 'editor') void showTab(activeTab.value);
|
if (activeTab.value && view === 'editor') void showTab(activeTab.value);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="no-scrollbar flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
|
<div class="flex h-[var(--ide-tab-h)] shrink-0 items-stretch border-b border-border bg-surface-1">
|
||||||
|
<div class="no-scrollbar flex min-w-0 flex-1 items-stretch overflow-x-auto">
|
||||||
<div
|
<div
|
||||||
v-for="tab in ide.editorTabs"
|
v-for="tab in ide.editorTabs"
|
||||||
:key="tab.id"
|
:key="tab.id"
|
||||||
@@ -23,6 +24,13 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Bascule de mode de la zone centrale : hors de la zone défilante, donc toujours visible, et
|
||||||
|
rendue même sans aucun onglet ouvert. -->
|
||||||
|
<div v-if="$slots.trailing" class="flex shrink-0 items-center border-l border-border px-2">
|
||||||
|
<slot name="trailing" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
|||||||
@@ -1,96 +1,109 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="flex h-full min-h-0 flex-col">
|
<div class="flex h-full min-h-0 flex-col">
|
||||||
<template v-if="activeWt">
|
<div class="label-mono flex items-center gap-1 px-3 py-2" :title="t('git.indexHint')">
|
||||||
<CommitPanel
|
<GitCompare :size="13" /> {{ t('ide.activity.git') }}
|
||||||
:repo-id="activeWt.repoId"
|
<BaseBadge v-if="pendingCount" tone="warn" class="ml-auto">{{ pendingCount }}</BaseBadge>
|
||||||
:wt="activeWt.path"
|
</div>
|
||||||
:changes="changes"
|
|
||||||
:git="activeWt.git"
|
<div class="min-h-0 flex-1 overflow-auto pb-2">
|
||||||
:truncated="truncated"
|
<!-- Les trois états distingués, comme dans l'explorateur : chargement, échec, vide. -->
|
||||||
:active="activeFile"
|
<SkeletonRow v-if="worktrees.loading && repos.length === 0" :count="4" :height="22" class="px-2 py-1" />
|
||||||
class="min-h-0 flex-1"
|
<div v-else-if="worktrees.loadError" class="px-3 py-2 text-xs">
|
||||||
@select="onSelect"
|
<p class="text-danger">{{ worktrees.loadError }}</p>
|
||||||
@changed="load"
|
<button type="button" class="mt-1 rounded px-1 text-accent hover:bg-surface-2" @click="worktrees.fetchAll()">
|
||||||
|
{{ t('common.retry') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p v-else-if="repos.length === 0" class="px-3 py-2 text-xs text-fg-subtle">{{ t('ide.noProjects') }}</p>
|
||||||
|
|
||||||
|
<div v-for="repo in repos" :key="repo.id">
|
||||||
|
<div class="flex items-center gap-1.5 px-2 py-1 text-xs">
|
||||||
|
<FolderGit2 :size="13" class="shrink-0" :style="tint(repo.id)" />
|
||||||
|
<span class="truncate font-medium" :title="repo.path">{{ repo.label }}</span>
|
||||||
|
<span v-if="dirtyFilesFor(repo.id)" class="ml-auto shrink-0 text-[10px] text-fg-subtle">
|
||||||
|
{{ t('changes.repoDirty', { n: dirtyFilesFor(repo.id) }, dirtyFilesFor(repo.id)) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p v-if="worktreesFor(repo.id).length === 0" class="px-6 py-0.5 text-[11px] text-fg-subtle">{{ t('ide.noWorktrees') }}</p>
|
||||||
|
<button
|
||||||
|
v-for="wt in worktreesFor(repo.id)"
|
||||||
|
:key="wt.path"
|
||||||
|
type="button"
|
||||||
|
class="flex h-[var(--ide-row-h)] w-full items-center gap-1.5 px-2 pl-6 text-left text-xs"
|
||||||
|
:class="isActive(wt) ? 'bg-surface-2 text-fg' : 'text-fg-muted hover:bg-surface-2/50'"
|
||||||
|
:title="wt.path"
|
||||||
|
@click="reveal(wt)"
|
||||||
|
>
|
||||||
|
<!-- L'index reste GLOBAL, volontairement : c'est la seule sortie d'une portée étroite (sinon
|
||||||
|
impossible de rejoindre un autre projet, donc portée inéchappable). On marque juste ce
|
||||||
|
qui tombe dans la portée courante. -->
|
||||||
|
<span
|
||||||
|
class="w-1 shrink-0 self-stretch rounded-full"
|
||||||
|
:class="inScope({ repoId: wt.repoId, wtPath: wt.path }) && scoped ? 'bg-accent/70' : 'bg-transparent'"
|
||||||
/>
|
/>
|
||||||
<!-- historique : ce qui est déjà acté, sous ce qui ne l'est pas encore -->
|
<component :is="wt.isMain ? Home : GitBranch" :size="13" class="shrink-0 text-fg-subtle" />
|
||||||
<CommitHistory
|
<span class="truncate font-mono">{{ wt.branch ?? t('worktrees.detached') }}</span>
|
||||||
:repo-id="activeWt.repoId"
|
<GitStatusBadge :git="wt.git" :branch="wt.branch" dense class="ml-auto shrink-0" />
|
||||||
:wt="activeWt.path"
|
<!-- Dans une sidebar de 288 px, le nom de branche passe avant tout : « à pousser » est
|
||||||
:version="worktrees.changeVersion(activeWt.repoId, activeWt.path)"
|
actionnable donc il reste, l'absence d'upstream est un simple marqueur (le détail est
|
||||||
class="max-h-[45%] shrink-0"
|
dans l'infobulle du badge et dans le bloc de la vue Changements). -->
|
||||||
/>
|
<span v-if="unpushed(wt)" class="shrink-0 text-[10px] text-warn">{{ t('changes.unpushed', { n: unpushed(wt) }) }}</span>
|
||||||
</template>
|
<span v-else-if="!wt.git.upstream" class="shrink-0 text-[10px] text-fg-subtle" :title="t('git.noUpstream')">◦</span>
|
||||||
<div v-else class="flex h-full items-center justify-center p-4">
|
</button>
|
||||||
<EmptyState :icon="GitCompare" :title="t('ide.activity.git')" :hint="t('git.noWorktreeHint')" />
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
// Panneau Git de l'IDE : cible le worktree actif (ide.activeContext) et charge ses changements.
|
// Index Git de la barre latérale : l'inventaire de TOUS les projets ouverts et de leurs worktrees,
|
||||||
// L'abonnement disque ne vit PLUS ici : ce composant est démonté dès qu'on quitte l'onglet Git, ce qui
|
// avec leur état git. Le clic ouvre le détail (fichiers, commit, push, historique) dans la vue
|
||||||
// coupait le seul `watch` de toute l'app. C'est désormais useWatchedWorktrees (monté dans App.vue) qui
|
// Changements de la zone centrale, où il y a la place de travailler.
|
||||||
// s'abonne et incrémente le jeton `changeVersion` du store, observé ci-dessous.
|
// Ce panneau ne fait AUCUN appel réseau : ahead/behind, staged, unstaged et conflits arrivent déjà
|
||||||
import { computed, ref, watch } from 'vue';
|
// dans chaque `worktree_update`. C'est aussi pour ça que l'ancien `catch {}` silencieux a disparu :
|
||||||
|
// il n'y a plus rien à charger ici. Le nombre exact de commits non poussés d'une branche sans
|
||||||
|
// upstream demanderait un `git log` par worktree : on affiche le marqueur, pas un chiffre faux.
|
||||||
|
import { computed } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { GitCompare } from '@lucide/vue';
|
import { FolderGit2, GitBranch, GitCompare, Home } from '@lucide/vue';
|
||||||
import type { FileChange } from '@arboretum/shared';
|
import type { WorktreeSummary } from '@arboretum/shared';
|
||||||
import { useIdeStore, tabId } from '../../stores/ide';
|
import { useIdeStore } from '../../stores/ide';
|
||||||
import { useWorktreesStore } from '../../stores/worktrees';
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
import { gitApi } from '../../lib/git-api';
|
import { useGroupsStore } from '../../stores/groups';
|
||||||
import CommitPanel from '../workspace/CommitPanel.vue';
|
import { dirtyFileCount, pendingWorktreeCount, sortForIndex } from '../../lib/changes-model';
|
||||||
import CommitHistory from '../workspace/CommitHistory.vue';
|
import { useContextScope } from '../../composables/useContextScope';
|
||||||
import EmptyState from '../ui/EmptyState.vue';
|
import GitStatusBadge from '../workspace/GitStatusBadge.vue';
|
||||||
|
import BaseBadge from '../ui/BaseBadge.vue';
|
||||||
|
import SkeletonRow from '../ui/SkeletonRow.vue';
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
|
const { inScope, scoped } = useContextScope();
|
||||||
|
|
||||||
const changes = ref<FileChange[]>([]);
|
/**
|
||||||
const truncated = ref(false);
|
* Ouvre le détail d'un worktree dans la zone centrale. Si ce worktree est HORS de la portée courante
|
||||||
|
* (on suit un terminal d'un autre projet), on élargit la vue : sans cela le clic ne montrerait rien,
|
||||||
const activeWt = computed(() => {
|
* et la portée serait inéchappable depuis l'index.
|
||||||
const c = ide.activeContext;
|
*/
|
||||||
if (!c) return null;
|
function reveal(wt: { repoId: string; path: string }): void {
|
||||||
return worktrees.worktrees.find((w) => w.repoId === c.repoId && w.path === c.wtPath) ?? null;
|
if (scoped.value && !inScope.value({ repoId: wt.repoId, wtPath: wt.path })) ide.changesScope = 'all';
|
||||||
});
|
ide.openChanges(wt.repoId, wt.path);
|
||||||
|
|
||||||
const activeFile = computed(() => {
|
|
||||||
const tab = ide.activeTab;
|
|
||||||
const wt = activeWt.value;
|
|
||||||
return tab && wt && tab.repoId === wt.repoId && tab.wtPath === wt.path ? tab.file : null;
|
|
||||||
});
|
|
||||||
|
|
||||||
async function load(): Promise<void> {
|
|
||||||
const wt = activeWt.value;
|
|
||||||
if (!wt) {
|
|
||||||
changes.value = [];
|
|
||||||
truncated.value = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const res = await gitApi.changes(wt.repoId, wt.path);
|
|
||||||
changes.value = res.changes;
|
|
||||||
truncated.value = res.truncated;
|
|
||||||
} catch {
|
|
||||||
/* worktree transitoire / erreur réseau : on garde l'état précédent */
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
const groupsStore = useGroupsStore();
|
||||||
|
|
||||||
function onSelect(sel: { file: string; staged: boolean }): void {
|
const repos = computed(() => worktrees.visibleRepos);
|
||||||
const wt = activeWt.value;
|
const pendingCount = computed(() => pendingWorktreeCount(repos.value, (id) => worktrees.worktreesForRepo(id)));
|
||||||
if (!wt) return;
|
|
||||||
ide.openFile(wt.repoId, wt.path, sel.file, 'diff');
|
|
||||||
ide.setTabView(tabId(wt.repoId, wt.path, sel.file), 'diff', sel.staged);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recharge à chaque changement de worktree actif ET à chaque modification disque de celui-ci.
|
const worktreesFor = (repoId: string): WorktreeSummary[] => sortForIndex(worktrees.worktreesForRepo(repoId));
|
||||||
watch(
|
const dirtyFilesFor = (repoId: string): number =>
|
||||||
() => {
|
worktrees.worktreesForRepo(repoId).reduce((sum, w) => sum + dirtyFileCount(w.git), 0);
|
||||||
const wt = activeWt.value;
|
const unpushed = (wt: WorktreeSummary): number => (wt.git.upstream ? wt.git.ahead : 0);
|
||||||
return wt ? `${wt.repoId}\0${wt.path}\0${worktrees.changeVersion(wt.repoId, wt.path)}` : null;
|
const isActive = (wt: WorktreeSummary): boolean =>
|
||||||
},
|
ide.activeContext?.repoId === wt.repoId && ide.activeContext?.wtPath === wt.path;
|
||||||
() => void load(),
|
|
||||||
{ immediate: true },
|
function tint(repoId: string): Record<string, string> {
|
||||||
);
|
const color = groupsStore.colorForRepo(repoId);
|
||||||
|
return color ? { color } : {};
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -103,7 +103,7 @@
|
|||||||
class="flex w-full items-center gap-1.5 rounded px-2 py-0.5 text-left text-[11px]"
|
class="flex w-full items-center gap-1.5 rounded px-2 py-0.5 text-left text-[11px]"
|
||||||
:class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted hover:bg-surface-2/60'"
|
:class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted hover:bg-surface-2/60'"
|
||||||
:title="sessionTitle(s)"
|
:title="sessionTitle(s)"
|
||||||
@click="ide.openTerminal(s.id)"
|
@click="(e: MouseEvent) => ide.openTerminal(s.id, { split: e.altKey })"
|
||||||
>
|
>
|
||||||
<SessionStateBadge :session="s" />
|
<SessionStateBadge :session="s" />
|
||||||
<span class="min-w-0 truncate font-mono" :class="s.live ? '' : 'text-fg-subtle'">{{ sessionLabel(s, worktrees) }}</span>
|
<span class="min-w-0 truncate font-mono" :class="s.live ? '' : 'text-fg-subtle'">{{ sessionLabel(s, worktrees) }}</span>
|
||||||
|
|||||||
@@ -10,9 +10,10 @@
|
|||||||
<!-- « À traiter » visible quel que soit le panneau mobile actif (cf. PrimarySidebar côté desktop) -->
|
<!-- « À traiter » visible quel que soit le panneau mobile actif (cf. PrimarySidebar côté desktop) -->
|
||||||
<AttentionList />
|
<AttentionList />
|
||||||
<div class="min-h-0 flex-1 overflow-hidden">
|
<div class="min-h-0 flex-1 overflow-hidden">
|
||||||
|
<!-- Pas d'index Git sur mobile : c'est une affordance de la sidebar desktop. Sur téléphone,
|
||||||
|
le panneau 'changes' est rendu par EditorArea, qui suit `ide.centerMode`. -->
|
||||||
<ProjectTree v-if="ide.mobilePanel === 'explorer'" />
|
<ProjectTree v-if="ide.mobilePanel === 'explorer'" />
|
||||||
<GitPanel v-else-if="ide.mobilePanel === 'git'" />
|
<TerminalDock v-else-if="ide.mobilePanel === 'terminal'" single />
|
||||||
<TerminalDock v-else-if="ide.mobilePanel === 'terminal'" />
|
|
||||||
<SessionsPanel v-else-if="ide.mobilePanel === 'sessions'" />
|
<SessionsPanel v-else-if="ide.mobilePanel === 'sessions'" />
|
||||||
<GroupsPanel v-else-if="ide.mobilePanel === 'groups'" />
|
<GroupsPanel v-else-if="ide.mobilePanel === 'groups'" />
|
||||||
<EditorArea v-else />
|
<EditorArea v-else />
|
||||||
@@ -49,7 +50,7 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<template v-if="ide.bottomVisible">
|
<template v-if="ide.bottomVisible">
|
||||||
<PanelSplitter v-model="ide.bottomHeight" axis="y" :min="120" :max="640" invert />
|
<PanelSplitter v-model="ide.bottomHeight" axis="y" :min="DOCK_MIN_HEIGHT" :max="dockMaxHeight(viewportHeight)" invert />
|
||||||
<section class="shrink-0 overflow-hidden border-t border-border" :style="{ height: `${ide.bottomHeight}px` }">
|
<section class="shrink-0 overflow-hidden border-t border-border" :style="{ height: `${ide.bottomHeight}px` }">
|
||||||
<TerminalDock />
|
<TerminalDock />
|
||||||
</section>
|
</section>
|
||||||
@@ -76,6 +77,7 @@ import { useI18n } from 'vue-i18n';
|
|||||||
import { Boxes, FileCode, FolderTree, GitCompare, LifeBuoy, List, LogOut, MoreVertical, Settings, SquareTerminal } from '@lucide/vue';
|
import { Boxes, FileCode, FolderTree, GitCompare, LifeBuoy, List, LogOut, MoreVertical, Settings, SquareTerminal } from '@lucide/vue';
|
||||||
import { decodeWtKey } from '@arboretum/shared';
|
import { decodeWtKey } from '@arboretum/shared';
|
||||||
import { useIdeStore, wtKey } from '../../stores/ide';
|
import { useIdeStore, wtKey } from '../../stores/ide';
|
||||||
|
import { DOCK_MIN_HEIGHT, dockMaxHeight, dockOpenHeight } from '../../lib/dock-model';
|
||||||
import { useWorktreesStore } from '../../stores/worktrees';
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
import { useSessionsStore } from '../../stores/sessions';
|
import { useSessionsStore } from '../../stores/sessions';
|
||||||
import { useModalsStore } from '../../stores/modals';
|
import { useModalsStore } from '../../stores/modals';
|
||||||
@@ -88,7 +90,6 @@ import StatusBar from './StatusBar.vue';
|
|||||||
import EditorArea from './EditorArea.vue';
|
import EditorArea from './EditorArea.vue';
|
||||||
import TerminalDock from './TerminalDock.vue';
|
import TerminalDock from './TerminalDock.vue';
|
||||||
import ProjectTree from './ProjectTree.vue';
|
import ProjectTree from './ProjectTree.vue';
|
||||||
import GitPanel from './GitPanel.vue';
|
|
||||||
import SessionsPanel from './SessionsPanel.vue';
|
import SessionsPanel from './SessionsPanel.vue';
|
||||||
import GroupsPanel from './GroupsPanel.vue';
|
import GroupsPanel from './GroupsPanel.vue';
|
||||||
import AttentionList from './AttentionList.vue';
|
import AttentionList from './AttentionList.vue';
|
||||||
@@ -121,9 +122,14 @@ let mql: MediaQueryList | null = null;
|
|||||||
const syncMobile = (): void => {
|
const syncMobile = (): void => {
|
||||||
isMobile.value = !!mql?.matches;
|
isMobile.value = !!mql?.matches;
|
||||||
};
|
};
|
||||||
|
/** Hauteur de fenêtre, suivie : les bornes du dock en dérivent (un plafond figé était trop bas). */
|
||||||
|
const viewportHeight = ref(1000);
|
||||||
// Les tailles de panneaux sont persistées : une fenêtre plus petite qu'à la session précédente
|
// Les tailles de panneaux sont persistées : une fenêtre plus petite qu'à la session précédente
|
||||||
// pouvait faire sortir la barre de statut du cadre. On reclampe au montage et à chaque resize.
|
// pouvait faire sortir la barre de statut du cadre. On reclampe au montage et à chaque resize.
|
||||||
const clampPanels = (): void => ide.clampToViewport(window.innerWidth, window.innerHeight);
|
const clampPanels = (): void => {
|
||||||
|
viewportHeight.value = window.innerHeight;
|
||||||
|
ide.clampToViewport(window.innerWidth, window.innerHeight);
|
||||||
|
};
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
mql = window.matchMedia('(max-width: 767px)');
|
mql = window.matchMedia('(max-width: 767px)');
|
||||||
syncMobile();
|
syncMobile();
|
||||||
@@ -131,6 +137,20 @@ onMounted(() => {
|
|||||||
clampPanels();
|
clampPanels();
|
||||||
window.addEventListener('resize', clampPanels);
|
window.addEventListener('resize', clampPanels);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Ouverture du dock, ou apparition d'une colonne : on garantit une hauteur exploitable sans JAMAIS
|
||||||
|
// réduire celle que l'utilisateur a réglée à la main. À 240 px un terminal n'affiche qu'une
|
||||||
|
// vingtaine de lignes, ce qui casse le rendu d'un TUI, et devient intenable à deux côte à côte.
|
||||||
|
// Côté vue et pas côté store : le store ne connaît pas le viewport (il tourne aussi sous node).
|
||||||
|
watch(
|
||||||
|
() => [ide.bottomVisible, ide.dockColumns.length] as const,
|
||||||
|
([visible, columns], previous) => {
|
||||||
|
if (!visible) return;
|
||||||
|
const [wasVisible, previousColumns] = previous ?? [false, 0];
|
||||||
|
if (visible === wasVisible && columns <= previousColumns) return;
|
||||||
|
ide.bottomHeight = Math.max(ide.bottomHeight, dockOpenHeight(window.innerHeight));
|
||||||
|
},
|
||||||
|
);
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
mql?.removeEventListener('change', syncMobile);
|
mql?.removeEventListener('change', syncMobile);
|
||||||
window.removeEventListener('resize', clampPanels);
|
window.removeEventListener('resize', clampPanels);
|
||||||
@@ -140,13 +160,17 @@ const mobilePanels = computed(() => [
|
|||||||
{ key: 'explorer', icon: FolderTree, label: t('ide.activity.explorer') },
|
{ key: 'explorer', icon: FolderTree, label: t('ide.activity.explorer') },
|
||||||
{ key: 'editor', icon: FileCode, label: t('workspace.editor') },
|
{ key: 'editor', icon: FileCode, label: t('workspace.editor') },
|
||||||
{ key: 'terminal', icon: SquareTerminal, label: t('ide.terminals') },
|
{ key: 'terminal', icon: SquareTerminal, label: t('ide.terminals') },
|
||||||
{ key: 'git', icon: GitCompare, label: t('ide.activity.git') },
|
{ key: 'changes', icon: GitCompare, label: t('workspace.changes') },
|
||||||
{ key: 'sessions', icon: List, label: t('ide.activity.sessions') },
|
{ key: 'sessions', icon: List, label: t('ide.activity.sessions') },
|
||||||
{ key: 'groups', icon: Boxes, label: t('ide.activity.groups') },
|
{ key: 'groups', icon: Boxes, label: t('ide.activity.groups') },
|
||||||
]);
|
]);
|
||||||
const mobileTitle = computed(() => mobilePanels.value.find((p) => p.key === ide.mobilePanel)?.label ?? '');
|
const mobileTitle = computed(() => mobilePanels.value.find((p) => p.key === ide.mobilePanel)?.label ?? '');
|
||||||
|
// Les deux modes de la zone centrale passent par le store : `mobilePanel` et `centerMode` y sont
|
||||||
|
// écrits au même endroit, donc ils ne peuvent pas diverger.
|
||||||
const setMobilePanel = (key: string): void => {
|
const setMobilePanel = (key: string): void => {
|
||||||
ide.mobilePanel = key;
|
if (key === 'changes') ide.setCenterMode('changes');
|
||||||
|
else if (key === 'editor') ide.setCenterMode('files');
|
||||||
|
else ide.mobilePanel = key;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Deep-link / redirections rétro-compat. /workspace/:repoId/:wt (ex. extension VS Code) cible un
|
// Deep-link / redirections rétro-compat. /workspace/:repoId/:wt (ex. extension VS Code) cible un
|
||||||
|
|||||||
@@ -32,8 +32,15 @@ const label = props.label ?? t('ide.resizePanel');
|
|||||||
|
|
||||||
const { onPointerDown } = useSplitter({
|
const { onPointerDown } = useSplitter({
|
||||||
axis: props.axis,
|
axis: props.axis,
|
||||||
min: props.min,
|
// Bornes en GETTERS, pas par valeur : elles sont désormais dérivées du viewport (plafond du dock)
|
||||||
max: props.max,
|
// et de la largeur mesurée de la piste (colonnes de terminaux). Capturées au setup, un drag
|
||||||
|
// continuait de clamper sur les bornes du PREMIER rendu, alors que le clavier lisait les vraies.
|
||||||
|
get min() {
|
||||||
|
return props.min;
|
||||||
|
},
|
||||||
|
get max() {
|
||||||
|
return props.max;
|
||||||
|
},
|
||||||
invert: props.invert,
|
invert: props.invert,
|
||||||
get: () => size.value,
|
get: () => size.value,
|
||||||
set: (v) => {
|
set: (v) => {
|
||||||
|
|||||||
@@ -61,7 +61,7 @@
|
|||||||
class="flex w-full items-center gap-1.5 rounded py-0.5 pr-2 pl-9 text-left text-[11px] hover:bg-surface-2/60"
|
class="flex w-full items-center gap-1.5 rounded py-0.5 pr-2 pl-9 text-left text-[11px] hover:bg-surface-2/60"
|
||||||
:class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted'"
|
:class="ide.activeDockSessionId === s.id ? 'bg-surface-2 text-fg' : 'text-fg-muted'"
|
||||||
:title="sessionTitle(s)"
|
:title="sessionTitle(s)"
|
||||||
@click="ide.openTerminal(s.id)"
|
@click="(e: MouseEvent) => ide.openTerminal(s.id, { split: e.altKey })"
|
||||||
>
|
>
|
||||||
<SessionStateBadge :session="s" />
|
<SessionStateBadge :session="s" />
|
||||||
<span class="min-w-0 truncate font-mono">{{ s.title ?? s.command }}</span>
|
<span class="min-w-0 truncate font-mono">{{ s.title ?? s.command }}</span>
|
||||||
@@ -113,6 +113,7 @@ import { sessionBelongsToWorktree, type RepoSummary, type SessionSummary, type W
|
|||||||
import { ApiError } from '../../lib/api';
|
import { ApiError } from '../../lib/api';
|
||||||
import { useIdeStore } from '../../stores/ide';
|
import { useIdeStore } from '../../stores/ide';
|
||||||
import { useWorktreesStore } from '../../stores/worktrees';
|
import { useWorktreesStore } from '../../stores/worktrees';
|
||||||
|
import { useContextScope } from '../../composables/useContextScope';
|
||||||
import { useSessionsStore } from '../../stores/sessions';
|
import { useSessionsStore } from '../../stores/sessions';
|
||||||
import { useGroupsStore } from '../../stores/groups';
|
import { useGroupsStore } from '../../stores/groups';
|
||||||
import { useToastsStore } from '../../stores/toasts';
|
import { useToastsStore } from '../../stores/toasts';
|
||||||
@@ -130,6 +131,7 @@ const props = defineProps<{ repo: RepoSummary }>();
|
|||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
|
const { inScope, scoped } = useContextScope();
|
||||||
const sessions = useSessionsStore();
|
const sessions = useSessionsStore();
|
||||||
const groups = useGroupsStore();
|
const groups = useGroupsStore();
|
||||||
const toasts = useToastsStore();
|
const toasts = useToastsStore();
|
||||||
@@ -246,9 +248,12 @@ function openWtMenu(e: MouseEvent, wt: WorktreeSummary): void {
|
|||||||
ctx.open(e.clientX, e.clientY, items);
|
ctx.open(e.clientX, e.clientY, items);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Le détail git vit désormais dans la zone centrale : on rend le worktree actif, on déplie son bloc
|
||||||
|
// et on bascule la vue Changements au premier plan (la sidebar n'en garde que l'index).
|
||||||
function openGitPanel(wt: WorktreeSummary): void {
|
function openGitPanel(wt: WorktreeSummary): void {
|
||||||
ide.setActiveWorktree(wt.repoId, wt.path);
|
// Hors portée courante (on suit un terminal ailleurs) : on élargit, sinon le clic n'ouvre rien.
|
||||||
ide.setActivity('git');
|
if (scoped.value && !inScope.value({ repoId: wt.repoId, wtPath: wt.path })) ide.changesScope = 'all';
|
||||||
|
ide.openChanges(wt.repoId, wt.path);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onPush(wt: WorktreeSummary): Promise<void> {
|
async function onPush(wt: WorktreeSummary): Promise<void> {
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ import {
|
|||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
MoreVertical,
|
MoreVertical,
|
||||||
SquareTerminal,
|
SquareTerminal,
|
||||||
|
SquareSplitHorizontal,
|
||||||
Eye,
|
Eye,
|
||||||
EyeOff,
|
EyeOff,
|
||||||
Trash2,
|
Trash2,
|
||||||
@@ -100,7 +101,9 @@ const rows = computed(() => store.sessions);
|
|||||||
const hasDiscovered = computed(() => store.sessions.some((s) => s.source === 'discovered' && !s.hidden));
|
const hasDiscovered = computed(() => store.sessions.some((s) => s.source === 'discovered' && !s.hidden));
|
||||||
|
|
||||||
function onRowClick(e: MouseEvent, s: SessionSummary): void {
|
function onRowClick(e: MouseEvent, s: SessionSummary): void {
|
||||||
if (s.live || s.attachable) ide.openTerminal(s.id);
|
// Alt+clic : ouvrir dans une colonne à côté plutôt qu'en onglet (raccourci du dock, sans
|
||||||
|
// raccourci clavier global : un TUI mange les combos, et le handler de la palette est en capture).
|
||||||
|
if (s.live || s.attachable) ide.openTerminal(s.id, { split: e.altKey });
|
||||||
else openRowMenu(e, s);
|
else openRowMenu(e, s);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,6 +121,9 @@ function menuFor(s: SessionSummary): ContextMenuItem[] {
|
|||||||
const items: ContextMenuItem[] = [];
|
const items: ContextMenuItem[] = [];
|
||||||
if (s.attachable) {
|
if (s.attachable) {
|
||||||
items.push({ label: t('sessions.open'), icon: SquareTerminal, onSelect: () => ide.openTerminal(s.id) });
|
items.push({ label: t('sessions.open'), icon: SquareTerminal, onSelect: () => ide.openTerminal(s.id) });
|
||||||
|
if (ide.canSplitTerminal || ide.dockSessionIds.length === 0) {
|
||||||
|
items.push({ label: t('ide.openTerminalBeside'), icon: SquareSplitHorizontal, onSelect: () => ide.openTerminal(s.id, { split: true }) });
|
||||||
|
}
|
||||||
items.push({ label: t('sessions.kill'), icon: Trash2, danger: true, onSelect: () => confirmKill(s) });
|
items.push({ label: t('sessions.kill'), icon: Trash2, danger: true, onSelect: () => confirmKill(s) });
|
||||||
} else if (s.live) {
|
} else if (s.live) {
|
||||||
items.push({ label: t('sessions.observe'), icon: Eye, onSelect: () => ide.openTerminal(s.id) });
|
items.push({ label: t('sessions.observe'), icon: Eye, onSelect: () => ide.openTerminal(s.id) });
|
||||||
|
|||||||
@@ -1,22 +1,39 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="flex h-full min-h-0 flex-col bg-surface-0">
|
<div class="flex h-full min-h-0 flex-col bg-surface-0">
|
||||||
<TerminalDockTabs />
|
<!-- Mobile : le dock occupe tout l'écran, une seule colonne visuelle. L'ÉTAT des colonnes n'est
|
||||||
|
pas touché, sinon une rotation d'écran détruirait la mise en page du bureau. -->
|
||||||
|
<template v-if="single">
|
||||||
|
<TerminalDockTabs :session-ids="ide.dockSessionIds" :active-session-id="ide.activeDockSessionId" />
|
||||||
<div class="relative min-h-0 flex-1">
|
<div class="relative min-h-0 flex-1">
|
||||||
<!-- toutes les sessions restent montées (v-show) pour préserver l'attache WS ; seule l'active
|
<div v-for="sid in ide.dockSessionIds" v-show="sid === ide.activeDockSessionId" :key="sid" class="absolute inset-0">
|
||||||
est visible. Fermer un onglet démonte réellement la TerminalView -> détache propre. -->
|
<TerminalPane :session-id="sid" />
|
||||||
<div
|
|
||||||
v-for="sid in ide.dockSessionIds"
|
|
||||||
v-show="sid === ide.activeDockSessionId"
|
|
||||||
:key="sid"
|
|
||||||
class="absolute inset-0 flex flex-col"
|
|
||||||
>
|
|
||||||
<DialogPrompt v-if="isWaiting(sid)" :session="sessionOf(sid)!" class="px-2 pt-2" />
|
|
||||||
<div class="min-h-0 flex-1">
|
|
||||||
<TerminalView :session-id="sid" :mode="modeOf(sid)" />
|
|
||||||
</div>
|
</div>
|
||||||
|
<EmptyState v-if="ide.dockSessionIds.length === 0" :icon="SquareTerminal" :title="t('ide.noTerminal')" :hint="t('ide.noTerminalHint')" class="m-6" />
|
||||||
</div>
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Desktop : une grille de colonnes redimensionnables. Les parts sont en `fr` (l'état est en
|
||||||
|
ratios) et les poignées en `auto` : aucune arithmétique de pixels dans le template. -->
|
||||||
|
<div v-else ref="track" class="grid min-h-0 flex-1" :style="{ gridTemplateColumns: gridTemplate }">
|
||||||
|
<template v-for="(column, i) in ide.dockColumns" :key="column.id">
|
||||||
|
<PanelSplitter
|
||||||
|
v-if="i > 0"
|
||||||
|
axis="x"
|
||||||
|
:model-value="splitPx(i - 1)"
|
||||||
|
:min="splitMin(i - 1)"
|
||||||
|
:max="splitMax(i - 1)"
|
||||||
|
:label="t('ide.resizeColumns')"
|
||||||
|
@update:model-value="(px: number) => ide.setDockColumnSplit(i - 1, px / usableWidth)"
|
||||||
|
/>
|
||||||
|
<TerminalDockColumn
|
||||||
|
:column="column"
|
||||||
|
:active="column.id === ide.activeDockColumnId"
|
||||||
|
:index="i"
|
||||||
|
:last="i === ide.dockColumns.length - 1"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
<EmptyState
|
<EmptyState
|
||||||
v-if="ide.dockSessionIds.length === 0"
|
v-if="ide.dockColumns.length === 0"
|
||||||
:icon="SquareTerminal"
|
:icon="SquareTerminal"
|
||||||
:title="t('ide.noTerminal')"
|
:title="t('ide.noTerminal')"
|
||||||
:hint="t('ide.noTerminalHint')"
|
:hint="t('ide.noTerminalHint')"
|
||||||
@@ -27,24 +44,49 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
// Conteneur du dock terminaux : N colonnes côte à côte (plafond MAX_DOCK_COLUMNS), séparées par des
|
||||||
|
// poignées. La hauteur du dock est pilotée par IdeShell ; la zone centrale au-dessus se réajuste
|
||||||
|
// seule (flex-1), il n'y a donc rien à recalculer ici.
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref, useTemplateRef } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { SquareTerminal } from '@lucide/vue';
|
import { SquareTerminal } from '@lucide/vue';
|
||||||
import type { SessionSummary } from '@arboretum/shared';
|
|
||||||
import { useIdeStore } from '../../stores/ide';
|
import { useIdeStore } from '../../stores/ide';
|
||||||
import { useSessionsStore } from '../../stores/sessions';
|
import { MIN_DOCK_COLUMN_RATIO } from '../../lib/dock-model';
|
||||||
import TerminalDockTabs from './TerminalDockTabs.vue';
|
import TerminalDockTabs from './TerminalDockTabs.vue';
|
||||||
import TerminalView from '../TerminalView.vue';
|
import TerminalDockColumn from './TerminalDockColumn.vue';
|
||||||
import DialogPrompt from '../DialogPrompt.vue';
|
import TerminalPane from './TerminalPane.vue';
|
||||||
|
import PanelSplitter from './PanelSplitter.vue';
|
||||||
import EmptyState from '../ui/EmptyState.vue';
|
import EmptyState from '../ui/EmptyState.vue';
|
||||||
|
|
||||||
|
withDefaults(defineProps<{ single?: boolean }>(), { single: false });
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
const sessions = useSessionsStore();
|
const track = useTemplateRef<HTMLDivElement>('track');
|
||||||
|
/** Largeur mesurée de la grille : le pont entre l'état (ratios) et le splitter (pixels). */
|
||||||
|
const trackWidth = ref(0);
|
||||||
|
let observer: ResizeObserver | null = null;
|
||||||
|
|
||||||
const sessionOf = (sid: string): SessionSummary | null => sessions.sessions.find((s) => s.id === sid) ?? null;
|
onMounted(() => {
|
||||||
const modeOf = (sid: string): 'interactive' | 'observer' => (sessionOf(sid)?.attachable ? 'interactive' : 'observer');
|
if (!track.value) return;
|
||||||
const isWaiting = (sid: string): boolean => {
|
trackWidth.value = track.value.clientWidth;
|
||||||
const s = sessionOf(sid);
|
observer = new ResizeObserver((entries) => {
|
||||||
return !!s && s.live && s.activity === 'waiting' && !!s.dialog;
|
for (const e of entries) trackWidth.value = e.contentRect.width;
|
||||||
};
|
});
|
||||||
|
observer.observe(track.value);
|
||||||
|
});
|
||||||
|
onBeforeUnmount(() => observer?.disconnect());
|
||||||
|
|
||||||
|
const gridTemplate = computed(() => ide.dockColumns.map((c) => `${c.ratio}fr`).join(' auto '));
|
||||||
|
|
||||||
|
/** Largeur du trait d'une poignée (`w-1` de PanelSplitter) : elle ne fait pas partie des colonnes. */
|
||||||
|
const SPLITTER_PX = 4;
|
||||||
|
/** Largeur réellement partagée par les colonnes (les poignées prennent leur propre place). */
|
||||||
|
const usableWidth = computed(() => Math.max(1, trackWidth.value - Math.max(0, ide.dockColumns.length - 1) * SPLITTER_PX));
|
||||||
|
|
||||||
|
const cumulative = (index: number): number => ide.dockColumns.slice(0, index + 1).reduce((sum, c) => sum + c.ratio, 0);
|
||||||
|
const splitPx = (index: number): number => Math.round(cumulative(index) * usableWidth.value);
|
||||||
|
const splitMin = (index: number): number =>
|
||||||
|
Math.round((cumulative(index - 1) + MIN_DOCK_COLUMN_RATIO) * usableWidth.value);
|
||||||
|
const splitMax = (index: number): number => Math.round((cumulative(index + 1) - MIN_DOCK_COLUMN_RATIO) * usableWidth.value);
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<template>
|
||||||
|
<!-- L'anneau suit l'ÉTAT (colonne active), pas seulement `focus-within` : il doit rester visible
|
||||||
|
quand on va cliquer dans la sidebar, puisque la frappe reviendra bien dans ce terminal. -->
|
||||||
|
<div
|
||||||
|
class="flex h-full min-h-0 min-w-0 flex-col"
|
||||||
|
:class="[
|
||||||
|
active ? 'ring-1 ring-inset ring-accent/60' : 'focus-within:ring-1 focus-within:ring-inset focus-within:ring-accent/30',
|
||||||
|
// Filet visuel entre colonnes : la poignée de redimensionnement ne se voit qu'au survol, deux
|
||||||
|
// terminaux se touchaient donc sans frontière lisible.
|
||||||
|
index > 0 ? 'border-l border-border' : '',
|
||||||
|
]"
|
||||||
|
:aria-label="t('ide.terminalColumn', { n: index + 1 })"
|
||||||
|
@pointerdown.capture="ide.focusDockColumn(column.id)"
|
||||||
|
>
|
||||||
|
<TerminalDockTabs :session-ids="column.sessionIds" :active-session-id="column.activeSessionId" :first="index === 0" :last="last" />
|
||||||
|
<div class="relative min-h-0 flex-1">
|
||||||
|
<!-- Tous les onglets de la colonne restent MONTÉS (v-show) : l'attache WS et le scrollback
|
||||||
|
survivent au changement d'onglet. Fermer un onglet démonte, donc détache proprement. -->
|
||||||
|
<div v-for="sid in column.sessionIds" v-show="sid === column.activeSessionId" :key="sid" class="absolute inset-0">
|
||||||
|
<TerminalPane :ref="(el) => registerPane(sid, el)" :session-id="sid" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Une colonne du dock : sa barre d'onglets et ses panes superposés. La frappe doit toujours arriver
|
||||||
|
// dans le terminal visible de la colonne ACTIVE, y compris quand l'activation vient d'un clic
|
||||||
|
// ailleurs (arbre, panneau, palette) : d'où le focus impératif ci-dessous.
|
||||||
|
import { watch } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import type { DockColumn } from '../../lib/dock-model';
|
||||||
|
import { useIdeStore } from '../../stores/ide';
|
||||||
|
import TerminalDockTabs from './TerminalDockTabs.vue';
|
||||||
|
import TerminalPane from './TerminalPane.vue';
|
||||||
|
|
||||||
|
const props = defineProps<{ column: DockColumn; active: boolean; index: number; last: boolean }>();
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const ide = useIdeStore();
|
||||||
|
|
||||||
|
interface PaneApi {
|
||||||
|
focus: () => void;
|
||||||
|
refit: () => void;
|
||||||
|
}
|
||||||
|
const panes = new Map<string, PaneApi>();
|
||||||
|
function registerPane(sid: string, el: unknown): void {
|
||||||
|
if (el) panes.set(sid, el as PaneApi);
|
||||||
|
else panes.delete(sid);
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.active, props.column.activeSessionId] as const,
|
||||||
|
([isActive, sid]) => {
|
||||||
|
if (!isActive) return;
|
||||||
|
// Le pane vient peut-être d'être révélé : re-mesurer avant de rendre la frappe (xterm mesuré à
|
||||||
|
// 0 tant qu'il était caché donnerait un TUI déformé).
|
||||||
|
const pane = panes.get(sid);
|
||||||
|
pane?.refit();
|
||||||
|
pane?.focus();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
</script>
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="no-scrollbar flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
|
<div class="no-scrollbar flex h-[var(--ide-tab-h)] shrink-0 items-stretch overflow-x-auto border-b border-border bg-surface-1">
|
||||||
<div class="flex shrink-0 items-center gap-1.5 px-2 label-mono">
|
<!-- Le titre et les feux tricolores n'appartiennent qu'à la première colonne : répétés, ils
|
||||||
|
mangeraient la place des onglets et brouilleraient la lecture du dock. -->
|
||||||
|
<div v-if="first" class="flex shrink-0 items-center gap-1.5 px-2 label-mono">
|
||||||
<span class="flex items-center gap-1" aria-hidden="true">
|
<span class="flex items-center gap-1" aria-hidden="true">
|
||||||
<span class="h-2 w-2 rounded-full bg-danger" />
|
<span class="h-2 w-2 rounded-full bg-danger" />
|
||||||
<span class="h-2 w-2 rounded-full bg-warn" />
|
<span class="h-2 w-2 rounded-full bg-warn" />
|
||||||
@@ -10,16 +12,27 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
v-for="sid in ide.dockSessionIds"
|
v-for="sid in sessionIds"
|
||||||
:key="sid"
|
:key="sid"
|
||||||
class="group flex cursor-pointer items-center gap-1.5 border-l border-border px-2.5 text-xs select-none"
|
class="group flex cursor-pointer items-center gap-1.5 border-l border-border px-2.5 text-xs select-none"
|
||||||
:class="sid === ide.activeDockSessionId ? 'bg-surface-0 text-fg' : 'text-fg-muted hover:bg-surface-2/50'"
|
:class="sid === activeSessionId ? 'bg-surface-0 text-fg' : 'text-fg-muted hover:bg-surface-2/50'"
|
||||||
:title="titleFor(sid)"
|
:title="titleFor(sid)"
|
||||||
@click="ide.focusTerminal(sid)"
|
@click="ide.focusTerminal(sid)"
|
||||||
@mousedown.middle.prevent="ide.closeTerminal(sid)"
|
@mousedown.middle.prevent="ide.closeTerminal(sid)"
|
||||||
>
|
>
|
||||||
<SessionStateBadge v-if="sessionOf(sid)" :session="sessionOf(sid)!" />
|
<SessionStateBadge v-if="sessionOf(sid)" :session="sessionOf(sid)!" />
|
||||||
<span class="truncate font-mono">{{ titleFor(sid) }}</span>
|
<span class="truncate font-mono">{{ titleFor(sid) }}</span>
|
||||||
|
<button
|
||||||
|
v-if="sessionIds.length > 1"
|
||||||
|
type="button"
|
||||||
|
class="flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-surface-3"
|
||||||
|
:class="canSplit ? '' : 'cursor-not-allowed opacity-40 group-hover:opacity-40'"
|
||||||
|
:disabled="!canSplit"
|
||||||
|
:title="canSplit ? t('ide.splitTerminal') : t('ide.splitTerminalFull')"
|
||||||
|
@click.stop="ide.moveTerminal(sid, { split: true })"
|
||||||
|
>
|
||||||
|
<SquareSplitHorizontal :size="13" />
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="ml-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-surface-3"
|
class="ml-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-0 group-hover:opacity-100 hover:bg-surface-3"
|
||||||
@@ -30,9 +43,21 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Fusion et repli ne concernent que la dernière colonne : sinon trois chevrons s'alignent. -->
|
||||||
<button
|
<button
|
||||||
|
v-if="last && ide.dockColumns.length > 1"
|
||||||
type="button"
|
type="button"
|
||||||
class="ml-auto shrink-0 px-2 text-fg-subtle transition-colors hover:bg-surface-2 hover:text-fg"
|
class="ml-auto shrink-0 px-2 text-fg-subtle transition-colors hover:bg-surface-2 hover:text-fg"
|
||||||
|
:title="t('ide.mergeColumns')"
|
||||||
|
@click="ide.mergeDockColumns()"
|
||||||
|
>
|
||||||
|
<Columns2 :size="14" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="last"
|
||||||
|
type="button"
|
||||||
|
class="shrink-0 px-2 text-fg-subtle transition-colors hover:bg-surface-2 hover:text-fg"
|
||||||
|
:class="ide.dockColumns.length > 1 ? '' : 'ml-auto'"
|
||||||
:title="t('common.close')"
|
:title="t('common.close')"
|
||||||
@click="ide.toggleBottom()"
|
@click="ide.toggleBottom()"
|
||||||
>
|
>
|
||||||
@@ -42,8 +67,11 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
// Barre d'onglets d'UNE colonne du dock. En mode `single` (mobile), la colonne couvre tout le dock :
|
||||||
|
// on lui passe alors la liste complète des sessions.
|
||||||
|
import { computed } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { ChevronDown, X } from '@lucide/vue';
|
import { ChevronDown, Columns2, SquareSplitHorizontal, X } from '@lucide/vue';
|
||||||
import type { SessionSummary } from '@arboretum/shared';
|
import type { SessionSummary } from '@arboretum/shared';
|
||||||
import { useIdeStore } from '../../stores/ide';
|
import { useIdeStore } from '../../stores/ide';
|
||||||
import { useSessionsStore } from '../../stores/sessions';
|
import { useSessionsStore } from '../../stores/sessions';
|
||||||
@@ -51,11 +79,27 @@ import { useWorktreesStore } from '../../stores/worktrees';
|
|||||||
import { sessionLabel } from '../../lib/session-label';
|
import { sessionLabel } from '../../lib/session-label';
|
||||||
import SessionStateBadge from '../SessionStateBadge.vue';
|
import SessionStateBadge from '../SessionStateBadge.vue';
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
sessionIds: string[];
|
||||||
|
activeSessionId: string | null;
|
||||||
|
/** première colonne : porte le titre du dock. */
|
||||||
|
first?: boolean;
|
||||||
|
/** dernière colonne : porte les actions globales (fusion, repli). */
|
||||||
|
last?: boolean;
|
||||||
|
}>(),
|
||||||
|
{ first: true, last: true },
|
||||||
|
);
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
const sessions = useSessionsStore();
|
const sessions = useSessionsStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
|
|
||||||
|
const canSplit = computed(() => ide.canSplitTerminal);
|
||||||
|
const sessionIds = computed(() => props.sessionIds);
|
||||||
|
const activeSessionId = computed(() => props.activeSessionId);
|
||||||
|
|
||||||
const sessionOf = (sid: string): SessionSummary | null => sessions.sessions.find((s) => s.id === sid) ?? null;
|
const sessionOf = (sid: string): SessionSummary | null => sessions.sessions.find((s) => s.id === sid) ?? null;
|
||||||
|
|
||||||
// Libellé compact, mutualisé avec les panneaux (lib/session-label) : le calcul était dupliqué ici, avec
|
// Libellé compact, mutualisé avec les panneaux (lib/session-label) : le calcul était dupliqué ici, avec
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
<template>
|
||||||
|
<!-- Tant que la liste des sessions n'est pas revenue, on n'attache RIEN : `attachable` serait lu
|
||||||
|
sur une liste vide, l'attache partirait en mode observateur (lecture seule) et le terminal
|
||||||
|
resterait muet pour toujours, sans que rien ne le dise. -->
|
||||||
|
<div v-if="!sessions.loaded" class="flex h-full items-center justify-center px-4">
|
||||||
|
<SkeletonRow class="w-full max-w-md" />
|
||||||
|
</div>
|
||||||
|
<EmptyState v-else-if="!session" :icon="SquareTerminal" :title="t('terminal.sessionEnded')" class="m-6" />
|
||||||
|
<div v-else class="flex h-full min-h-0 flex-col">
|
||||||
|
<DialogPrompt v-if="isWaiting" :session="session" class="px-2 pt-2" />
|
||||||
|
<div class="min-h-0 flex-1">
|
||||||
|
<TerminalView ref="view" :key="`${sessionId}|${mode}`" :session-id="sessionId" :mode="mode" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
// Un pane du dock : le dialogue en attente (réponse sans clavier) au-dessus du terminal.
|
||||||
|
// Extrait de TerminalDock pour qu'une colonne puisse en empiler plusieurs, et pour exposer au
|
||||||
|
// parent le focus du terminal (la frappe doit suivre la colonne active).
|
||||||
|
import { computed, useTemplateRef } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { SquareTerminal } from '@lucide/vue';
|
||||||
|
import { useSessionsStore } from '../../stores/sessions';
|
||||||
|
import TerminalView from '../TerminalView.vue';
|
||||||
|
import DialogPrompt from '../DialogPrompt.vue';
|
||||||
|
import EmptyState from '../ui/EmptyState.vue';
|
||||||
|
import SkeletonRow from '../ui/SkeletonRow.vue';
|
||||||
|
|
||||||
|
const props = defineProps<{ sessionId: string }>();
|
||||||
|
|
||||||
|
const { t } = useI18n();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
const view = useTemplateRef<{ focus: () => void; refit: () => void }>('view');
|
||||||
|
|
||||||
|
const session = computed(() => sessions.sessions.find((s) => s.id === props.sessionId) ?? null);
|
||||||
|
// Une session non attachable (découverte, ou morte) reste lisible : on l'ouvre en observateur.
|
||||||
|
const mode = computed<'interactive' | 'observer'>(() => (session.value?.attachable ? 'interactive' : 'observer'));
|
||||||
|
const isWaiting = computed(() => {
|
||||||
|
const s = session.value;
|
||||||
|
return !!s && s.live && s.activity === 'waiting' && !!s.dialog;
|
||||||
|
});
|
||||||
|
|
||||||
|
defineExpose({
|
||||||
|
focus: (): void => view.value?.focus(),
|
||||||
|
refit: (): void => view.value?.refit(),
|
||||||
|
});
|
||||||
|
</script>
|
||||||
@@ -7,6 +7,8 @@
|
|||||||
class="inline-flex items-center gap-1.5 rounded-[9px] px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60"
|
class="inline-flex items-center gap-1.5 rounded-[9px] px-2.5 py-1 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/60"
|
||||||
:class="opt.value === modelValue ? 'bg-surface-2 text-fg' : 'text-fg-muted hover:text-fg'"
|
:class="opt.value === modelValue ? 'bg-surface-2 text-fg' : 'text-fg-muted hover:text-fg'"
|
||||||
:aria-pressed="opt.value === modelValue"
|
:aria-pressed="opt.value === modelValue"
|
||||||
|
:title="opt.title ?? opt.label"
|
||||||
|
:aria-label="opt.label ? undefined : opt.title"
|
||||||
@click="emit('update:modelValue', opt.value)"
|
@click="emit('update:modelValue', opt.value)"
|
||||||
>
|
>
|
||||||
<component :is="opt.icon" v-if="opt.icon" :size="15" />
|
<component :is="opt.icon" v-if="opt.icon" :size="15" />
|
||||||
@@ -23,6 +25,8 @@ export interface SegmentOption {
|
|||||||
value: string;
|
value: string;
|
||||||
label?: string;
|
label?: string;
|
||||||
icon?: Component;
|
icon?: Component;
|
||||||
|
/** Infobulle : indispensable quand l'option n'a qu'une icône (sert aussi d'aria-label). */
|
||||||
|
title?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
defineProps<{ modelValue: string; options: SegmentOption[] }>();
|
defineProps<{ modelValue: string; options: SegmentOption[] }>();
|
||||||
|
|||||||
@@ -80,7 +80,10 @@ const props = defineProps<{ repoId: string; wt: string; version: number }>();
|
|||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
|
|
||||||
const PAGE = 30;
|
const PAGE = 30;
|
||||||
const open = persistedRef<boolean>('arb.history.open', false);
|
// Repli mémorisé PAR worktree : la clé était globale, donc un seul clic aurait déplié les N
|
||||||
|
// historiques de la vue Changements et lancé N `git log`. La clé est lue une fois au setup, les
|
||||||
|
// appelants doivent donc poser un `:key` par worktree (c'est le cas des blocs).
|
||||||
|
const open = persistedRef<boolean>(`arb.history.open:${props.repoId}\0${props.wt}`, false);
|
||||||
const commits = ref<CommitEntry[]>([]);
|
const commits = ref<CommitEntry[]>([]);
|
||||||
const unpushedCount = ref(0);
|
const unpushedCount = ref(0);
|
||||||
const hasUpstream = ref(false);
|
const hasUpstream = ref(false);
|
||||||
|
|||||||
@@ -1,10 +1,16 @@
|
|||||||
<template>
|
<template>
|
||||||
<!-- pas de bordure haute : ce panneau est le premier enfant du panneau Git (le trait était un
|
<!-- Layout « bloc » : ce panneau est monté une fois par worktree dans une vue qui défile, donc sa
|
||||||
vestige de l'ancien layout, où il vivait sous le contenu). -->
|
hauteur suit son contenu et c'est la LISTE qui est bornée. Un `h-full` avec une liste `flex-1`
|
||||||
<div class="flex h-full flex-col">
|
ne fonctionnerait que dans un parent à hauteur définie. -->
|
||||||
<!-- en-tête + actions distantes -->
|
<div class="flex flex-col">
|
||||||
|
<!-- Actions distantes. Pas de titre : le bloc qui monte ce panneau nomme déjà le worktree, et
|
||||||
|
répéter « Changements » sous l'en-tête de la vue Changements ne disait rien de plus. -->
|
||||||
<div class="flex items-center gap-1 px-2 py-1 label-mono">
|
<div class="flex items-center gap-1 px-2 py-1 label-mono">
|
||||||
<GitCompare :size="13" /> {{ t('workspace.changes') }}
|
<!-- L'upstream nomme le contexte des deux boutons de droite : sans lui, cette ligne était une
|
||||||
|
barre d'icônes orpheline. -->
|
||||||
|
<span class="min-w-0 truncate normal-case" :class="git.upstream ? 'text-fg-subtle' : 'text-fg-subtle/70'">
|
||||||
|
{{ git.upstream ?? t('git.noUpstream') }}
|
||||||
|
</span>
|
||||||
<span v-if="git.ahead" class="text-accent">↑{{ git.ahead }}</span>
|
<span v-if="git.ahead" class="text-accent">↑{{ git.ahead }}</span>
|
||||||
<span v-if="git.behind" class="text-warn">↓{{ git.behind }}</span>
|
<span v-if="git.behind" class="text-warn">↓{{ git.behind }}</span>
|
||||||
<span class="ml-auto flex items-center gap-1">
|
<span class="ml-auto flex items-center gap-1">
|
||||||
@@ -13,7 +19,7 @@
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="min-h-0 flex-1 overflow-auto">
|
<div class="max-h-[50vh] overflow-auto">
|
||||||
<!-- fichiers indexés (staged) -->
|
<!-- fichiers indexés (staged) -->
|
||||||
<div v-if="staged.length" class="px-1">
|
<div v-if="staged.length" class="px-1">
|
||||||
<div class="flex items-center px-1 py-0.5 text-[11px] text-fg-subtle">
|
<div class="flex items-center px-1 py-0.5 text-[11px] text-fg-subtle">
|
||||||
@@ -67,9 +73,9 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { ArrowDownToLine, Check, Download, GitCompare, Minus, Plus, Undo2, Upload } from '@lucide/vue';
|
import { ArrowDownToLine, Check, Download, Minus, Plus, Undo2, Upload } from '@lucide/vue';
|
||||||
import type { FileChange, WorktreeGitStatus, WorktreeSummary } from '@arboretum/shared';
|
import type { FileChange, WorktreeGitStatus, WorktreeSummary } from '@arboretum/shared';
|
||||||
import { gitApi } from '../../lib/git-api';
|
import { gitApi } from '../../lib/git-api';
|
||||||
import { ApiError } from '../../lib/api';
|
import { ApiError } from '../../lib/api';
|
||||||
@@ -90,10 +96,33 @@ const amend = ref(false);
|
|||||||
const busy = ref<string | null>(null);
|
const busy = ref<string | null>(null);
|
||||||
const error = ref<string | null>(null);
|
const error = ref<string | null>(null);
|
||||||
const discardArmed = ref<string | null>(null);
|
const discardArmed = ref<string | null>(null);
|
||||||
const canRebase = ref(false);
|
// Un `git pull --ff-only` a échoué : la divergence est constatée, on propose le rebase même si les
|
||||||
|
// compteurs ne l'annoncent pas encore.
|
||||||
|
const ffFailed = ref(false);
|
||||||
|
|
||||||
const canCommit = computed(() => !busy.value && staged.value.length > 0 && (amend.value || message.value.trim() !== ''));
|
// Le serveur autorise l'amend d'un message seul (sans rien d'indexé) : l'exiger ici privait d'une
|
||||||
const canPush = computed(() => !!props.git && props.git.behind === 0); // push simple (ff) ; le serveur gère l'upstream
|
// correction de message pourtant sans risque.
|
||||||
|
const canCommit = computed(() =>
|
||||||
|
!busy.value &&
|
||||||
|
(amend.value
|
||||||
|
? message.value.trim() !== '' || staged.value.length > 0
|
||||||
|
: staged.value.length > 0 && message.value.trim() !== ''),
|
||||||
|
);
|
||||||
|
// Ne rien pousser n'a aucun sens, et être en retard n'empêche pas de pousser (git tranche, et son
|
||||||
|
// refus s'affiche ci-dessous). Sans upstream, le serveur publie la branche via `push -u origin`.
|
||||||
|
const canPush = computed(() => !busy.value && (!props.git.upstream || props.git.ahead > 0));
|
||||||
|
// Pas de garde `busy` ici : le bouton porte déjà son propre indicateur de chargement, et le faire
|
||||||
|
// disparaître pendant le rebase serait déroutant.
|
||||||
|
const canRebase = computed(() => ffFailed.value || props.git.behind > 0);
|
||||||
|
|
||||||
|
// Une confirmation destructive ne doit pas survivre à un rechargement de liste ni à un changement de
|
||||||
|
// worktree : la ligne sous le curseur peut avoir changé d'identité entre l'armement et le clic.
|
||||||
|
watch(
|
||||||
|
() => [props.repoId, props.wt, props.changes] as const,
|
||||||
|
() => {
|
||||||
|
discardArmed.value = null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
function select(c: FileChange, stagedSide: boolean): void {
|
function select(c: FileChange, stagedSide: boolean): void {
|
||||||
emit('select', { file: c.path, staged: stagedSide });
|
emit('select', { file: c.path, staged: stagedSide });
|
||||||
@@ -140,11 +169,11 @@ async function onCommit(): Promise<void> {
|
|||||||
const onPush = () => run('push', () => store.pushWorktree(props.repoId, props.wt).then((worktree) => ({ worktree }))).catch(() => {});
|
const onPush = () => run('push', () => store.pushWorktree(props.repoId, props.wt).then((worktree) => ({ worktree }))).catch(() => {});
|
||||||
|
|
||||||
async function onPull(mode: 'ff-only' | 'rebase'): Promise<void> {
|
async function onPull(mode: 'ff-only' | 'rebase'): Promise<void> {
|
||||||
canRebase.value = false;
|
|
||||||
try {
|
try {
|
||||||
await run(mode === 'rebase' ? 'rebase' : 'pull', () => gitApi.pull(props.repoId, props.wt, mode));
|
await run(mode === 'rebase' ? 'rebase' : 'pull', () => gitApi.pull(props.repoId, props.wt, mode));
|
||||||
|
ffFailed.value = false;
|
||||||
} catch {
|
} catch {
|
||||||
if (mode === 'ff-only') canRebase.value = true; // ff impossible (divergence) → proposer le rebase
|
if (mode === 'ff-only') ffFailed.value = true; // ff impossible (divergence) → proposer le rebase
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { computed, type ComputedRef } from 'vue';
|
||||||
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { useIdeStore } from '../stores/ide';
|
||||||
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
import { useGroupsStore } from '../stores/groups';
|
||||||
|
import { resolveScope, SCOPE_ALL, scopeContains, type ContextScope } from '../lib/context-scope';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Portée de travail courante, dérivée des données live. Le store IDE ne persiste que la PRÉFÉRENCE
|
||||||
|
* (`changesScope`) : une portée persistée finirait par désigner un groupe ou un worktree disparu.
|
||||||
|
*
|
||||||
|
* Sans état interne : appelable par plusieurs composants, chacun ayant son cache de computed sur les
|
||||||
|
* mêmes dépendances (le coût est négligeable, et un singleton de module ne marcherait pas ici,
|
||||||
|
* puisque ces getters dépendent de Pinia).
|
||||||
|
*/
|
||||||
|
export interface ContextScopeApi {
|
||||||
|
/** Portée EFFECTIVE, jamais nulle : 'all' est le repli. */
|
||||||
|
scope: ComputedRef<ContextScope>;
|
||||||
|
/** Portée que le terminal focalisé imposerait, même en mode « tout voir » : sert à libeller la bascule. */
|
||||||
|
followed: ComputedRef<ContextScope | null>;
|
||||||
|
/** Libellé humain de la portée effective. */
|
||||||
|
label: ComputedRef<string>;
|
||||||
|
/** true quand la vue est réellement restreinte (donc « rien à voir » peut être trompeur). */
|
||||||
|
scoped: ComputedRef<boolean>;
|
||||||
|
/** Prédicat prêt à injecter dans `groupWorktreesByRepo` / `pendingWorktreeCount`. */
|
||||||
|
inScope: ComputedRef<(w: { repoId: string; wtPath: string }) => boolean>;
|
||||||
|
toggle: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useContextScope(): ContextScopeApi {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const groups = useGroupsStore();
|
||||||
|
|
||||||
|
const groupRefs = computed(() => groups.groups.map((g) => ({ id: g.id, repoIds: g.repoIds })));
|
||||||
|
|
||||||
|
const followed = computed<ContextScope | null>(() => {
|
||||||
|
const sid = ide.activeDockSessionId;
|
||||||
|
const session = sid ? (sessions.sessions.find((s) => s.id === sid) ?? null) : null;
|
||||||
|
return resolveScope(session, worktrees.worktrees, groupRefs.value);
|
||||||
|
});
|
||||||
|
|
||||||
|
const scope = computed<ContextScope>(() => {
|
||||||
|
if (ide.changesScope === 'all') return SCOPE_ALL;
|
||||||
|
// SEUL le terminal focalisé restreint la vue. Se rabattre sur `activeContext` (l'onglet éditeur)
|
||||||
|
// serait un rétrécissement surprise : ouvrir un fichier réduirait la vue Changements à ce projet
|
||||||
|
// alors que son intérêt est justement d'être multi-projet. Pas de terminal = pas de contexte de
|
||||||
|
// travail = tout voir. Les colonnes du dock étant persistées, la portée survit à un dock replié.
|
||||||
|
return followed.value ?? SCOPE_ALL;
|
||||||
|
});
|
||||||
|
|
||||||
|
const scoped = computed(() => scope.value.kind !== 'all');
|
||||||
|
|
||||||
|
const label = computed(() => {
|
||||||
|
const s = scope.value;
|
||||||
|
if (s.kind === 'all') return t('changes.scope.allLabel');
|
||||||
|
if (s.kind === 'group') {
|
||||||
|
const g = groups.groups.find((x) => x.id === s.groupId);
|
||||||
|
return t('changes.scope.group', { name: g?.label ?? s.groupId });
|
||||||
|
}
|
||||||
|
const wt = worktrees.worktrees.find((w) => w.repoId === s.repoId && w.path === s.wtPath);
|
||||||
|
const repo = worktrees.repos.find((r) => r.id === s.repoId);
|
||||||
|
const branch = wt?.branch ?? s.wtPath.split('/').filter(Boolean).pop() ?? s.wtPath;
|
||||||
|
return repo ? `${repo.label} · ${branch}` : branch;
|
||||||
|
});
|
||||||
|
|
||||||
|
const inScope = computed(() => (w: { repoId: string; wtPath: string }) => scopeContains(scope.value, w, groupRefs.value));
|
||||||
|
|
||||||
|
return { scope, followed, label, scoped, inScope, toggle: () => ide.toggleChangesScope() };
|
||||||
|
}
|
||||||
@@ -1,10 +1,27 @@
|
|||||||
// Chargement paresseux de Monaco : le gros paquet n'est tiré qu'à la première ouverture d'un
|
// Chargement paresseux de Monaco : le gros paquet n'est tiré qu'à la première ouverture d'un
|
||||||
// fichier dans l'IDE. Mémoïsé (un seul import partagé entre toutes les instances d'éditeur).
|
// fichier dans l'IDE. Le SUCCÈS est mémoïsé (un seul import partagé entre tous les appelants) ;
|
||||||
|
// l'ÉCHEC ne l'est PAS.
|
||||||
import type * as Monaco from 'monaco-editor';
|
import type * as Monaco from 'monaco-editor';
|
||||||
|
|
||||||
|
type MonacoImporter = () => Promise<typeof Monaco>;
|
||||||
|
|
||||||
|
const defaultImporter: MonacoImporter = () => import('../lib/monaco-setup').then((m) => m.monaco);
|
||||||
|
|
||||||
let monacoPromise: Promise<typeof Monaco> | null = null;
|
let monacoPromise: Promise<typeof Monaco> | null = null;
|
||||||
|
|
||||||
export function loadMonaco(): Promise<typeof Monaco> {
|
/**
|
||||||
monacoPromise ??= import('../lib/monaco-setup').then((m) => m.monaco);
|
* Mémoïser un rejet condamnait l'éditeur pour toute la session : un chunk absent (index.html
|
||||||
return monacoPromise;
|
* périmé après une mise à jour) ou une coupure réseau rendait tout nouvel essai instantanément
|
||||||
|
* perdant, sans le moindre message à l'écran. On oublie donc la promesse en échec pour qu'un
|
||||||
|
* « Réessayer » refasse un véritable import.
|
||||||
|
*
|
||||||
|
* `importer` n'existe que pour les tests (aucun appelant applicatif ne le passe) : il permet de
|
||||||
|
* vérifier ce contrat sans charger monaco-editor dans un environnement node.
|
||||||
|
*/
|
||||||
|
export function loadMonaco(importer: MonacoImporter = defaultImporter): Promise<typeof Monaco> {
|
||||||
|
const pending = (monacoPromise ??= importer());
|
||||||
|
return pending.catch((err: unknown) => {
|
||||||
|
if (monacoPromise === pending) monacoPromise = null;
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useSessionsStore } from '../stores/sessions';
|
|||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
import { useGroupsStore } from '../stores/groups';
|
import { useGroupsStore } from '../stores/groups';
|
||||||
import { useSettingsStore } from '../stores/settings';
|
import { useSettingsStore } from '../stores/settings';
|
||||||
|
import { useChangesStore } from '../stores/changes';
|
||||||
import { wsClient } from '../lib/ws-client';
|
import { wsClient } from '../lib/ws-client';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -18,6 +19,7 @@ export function useRealtimeBootstrap(): void {
|
|||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
const groups = useGroupsStore();
|
const groups = useGroupsStore();
|
||||||
const settings = useSettingsStore();
|
const settings = useSettingsStore();
|
||||||
|
const changes = useChangesStore();
|
||||||
|
|
||||||
let started = false;
|
let started = false;
|
||||||
|
|
||||||
@@ -27,6 +29,9 @@ export function useRealtimeBootstrap(): void {
|
|||||||
void sessions.fetchSessions();
|
void sessions.fetchSessions();
|
||||||
void groups.fetchGroups();
|
void groups.fetchGroups();
|
||||||
void settings.fetch(); // alimente l'icône de nav Gitea et la vue Réglages
|
void settings.fetch(); // alimente l'icône de nav Gitea et la vue Réglages
|
||||||
|
// Les listes de fichiers modifiés ne sont jamais diffusées par WS : après une coupure, celles
|
||||||
|
// déjà chargées sont suspectes. On les repérime (les blocs visibles rechargeront).
|
||||||
|
changes.invalidateAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
function start(): void {
|
function start(): void {
|
||||||
@@ -46,6 +51,7 @@ export function useRealtimeBootstrap(): void {
|
|||||||
sessions.stopRealtime();
|
sessions.stopRealtime();
|
||||||
groups.stopRealtime();
|
groups.stopRealtime();
|
||||||
settings.stopRealtime();
|
settings.stopRealtime();
|
||||||
|
changes.reset();
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { watch } from 'vue';
|
||||||
|
import { useIdeStore } from '../stores/ide';
|
||||||
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
import { useGroupsStore } from '../stores/groups';
|
||||||
|
import { resolveScope } from '../lib/context-scope';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Le terminal focalisé impose le contexte de travail (worktree actif). C'était le chaînon manquant :
|
||||||
|
* `openTerminal` / `focusTerminal` ne posent PAS `activeContext`, et ne peuvent pas le faire, le store
|
||||||
|
* IDE ne connaissant ni les cwd ni les groupes. La corrélation vit donc ici, où les données live sont
|
||||||
|
* disponibles.
|
||||||
|
*
|
||||||
|
* PROPRIÉTAIRE UNIQUE de cette écriture : monté une seule fois dans la coquille IDE. Deux montages
|
||||||
|
* se battraient pour `activeContext`.
|
||||||
|
*
|
||||||
|
* Cas d'une session de GROUPE : on ne touche pas à `activeContext` (un groupe n'a pas de worktree
|
||||||
|
* unique, et écraser le contexte ferait perdre le fichier ouvert) ; la portée de groupe est portée par
|
||||||
|
* `useContextScope`, qui lit le terminal focalisé directement.
|
||||||
|
*
|
||||||
|
* Effet de bord voulu : la barre de statut (badge git) et la priorité 1 des abonnements FS suivent
|
||||||
|
* désormais le terminal, sans une ligne de plus dans ces fichiers.
|
||||||
|
*/
|
||||||
|
export function useTerminalContext(): void {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const groups = useGroupsStore();
|
||||||
|
|
||||||
|
watch(
|
||||||
|
// La liste des sessions compte comme dépendance : au boot, le terminal est connu avant sa session.
|
||||||
|
() => [ide.activeDockSessionId, sessions.sessions.length, worktrees.worktrees.length] as const,
|
||||||
|
([sid]) => {
|
||||||
|
if (!sid) return;
|
||||||
|
const session = sessions.sessions.find((s) => s.id === sid);
|
||||||
|
if (!session) return;
|
||||||
|
const scope = resolveScope(
|
||||||
|
session,
|
||||||
|
worktrees.worktrees,
|
||||||
|
groups.groups.map((g) => ({ id: g.id, repoIds: g.repoIds })),
|
||||||
|
);
|
||||||
|
if (scope?.kind !== 'worktree') return;
|
||||||
|
if (ide.activeContext?.repoId === scope.repoId && ide.activeContext?.wtPath === scope.wtPath) return;
|
||||||
|
ide.setActiveWorktree(scope.repoId, scope.wtPath);
|
||||||
|
},
|
||||||
|
{ immediate: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import { computed, onScopeDispose, watch } from 'vue';
|
import { computed, onScopeDispose, watch } from 'vue';
|
||||||
import { useIdeStore } from '../stores/ide';
|
import { parseWtKey, useIdeStore } from '../stores/ide';
|
||||||
import { useWorktreesStore } from '../stores/worktrees';
|
import { useWorktreesStore } from '../stores/worktrees';
|
||||||
|
import { useSessionsStore } from '../stores/sessions';
|
||||||
|
import { worktreesForSession } from '../lib/context-scope';
|
||||||
import { wsClient } from '../lib/ws-client';
|
import { wsClient } from '../lib/ws-client';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,6 +29,7 @@ export const MAX_WATCHED = 40;
|
|||||||
export function useWatchedWorktrees(): void {
|
export function useWatchedWorktrees(): void {
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
|
||||||
/** Abonnements en cours, clé `repoId\0path` → fonction de désabonnement. */
|
/** Abonnements en cours, clé `repoId\0path` → fonction de désabonnement. */
|
||||||
const active = new Map<string, () => void>();
|
const active = new Map<string, () => void>();
|
||||||
@@ -43,6 +46,26 @@ export function useWatchedWorktrees(): void {
|
|||||||
// Le worktree actif d'abord : il doit survivre au plafond.
|
// Le worktree actif d'abord : il doit survivre au plafond.
|
||||||
const ctx = ide.activeContext;
|
const ctx = ide.activeContext;
|
||||||
if (ctx) add(ctx.repoId, ctx.wtPath);
|
if (ctx) add(ctx.repoId, ctx.wtPath);
|
||||||
|
// Worktrees des terminaux VISIBLES (l'onglet actif de chaque colonne du dock) : on travaille
|
||||||
|
// dedans, donc leur statut git doit rester frais, sinon les compteurs du bloc Changements d'à
|
||||||
|
// côté restent figés pendant la session. Une session de groupe compte pour TOUS ses répertoires
|
||||||
|
// reliés. Le serveur épingle déjà le watcher FS d'une session vivante (`syncSessionPin`) ; ce
|
||||||
|
// `watch` client sert à RECEVOIR l'événement, poussé de façon ciblée aux seuls abonnés.
|
||||||
|
for (const sid of ide.visibleDockSessionIds) {
|
||||||
|
const session = sessions.sessions.find((s) => s.id === sid);
|
||||||
|
if (!session) continue;
|
||||||
|
for (const w of worktreesForSession(session, worktrees.worktrees)) add(w.repoId, w.path);
|
||||||
|
}
|
||||||
|
// Blocs dépliés de la vue Changements : ils affichent une liste de fichiers modifiés, donc ils
|
||||||
|
// ont besoin du même jeton d'invalidation que l'arbre de fichiers. Priorité juste après le
|
||||||
|
// worktree actif : en mode « changements », c'est précisément ce que l'utilisateur regarde.
|
||||||
|
for (const key of ide.changesExpanded) {
|
||||||
|
const ref = parseWtKey(key);
|
||||||
|
if (!ref) continue;
|
||||||
|
if (worktrees.worktrees.some((w) => w.repoId === ref.repoId && w.path === ref.wtPath)) {
|
||||||
|
add(ref.repoId, ref.wtPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Worktrees dont l'arbre de fichiers est déplié : ils peuvent l'être depuis le panneau Groupes,
|
// Worktrees dont l'arbre de fichiers est déplié : ils peuvent l'être depuis le panneau Groupes,
|
||||||
// sans que leur dépôt soit déplié dans l'Explorateur. Sans eux, cet arbre-là ne recevrait aucun
|
// sans que leur dépôt soit déplié dans l'Explorateur. Sans eux, cet arbre-là ne recevrait aucun
|
||||||
// `worktree_changes` et resterait figé sur son premier chargement.
|
// `worktree_changes` et resterait figé sur son premier chargement.
|
||||||
|
|||||||
@@ -260,6 +260,12 @@ export default {
|
|||||||
noFileHint: 'Pick a file in the tree to edit it, or a changed file to view its diff.',
|
noFileHint: 'Pick a file in the tree to edit it, or a changed file to view its diff.',
|
||||||
terminals: 'Terminals',
|
terminals: 'Terminals',
|
||||||
resizePanel: 'Resize panel',
|
resizePanel: 'Resize panel',
|
||||||
|
resizeColumns: 'Resize terminal columns',
|
||||||
|
splitTerminal: 'Open beside',
|
||||||
|
splitTerminalFull: 'Three columns at most',
|
||||||
|
mergeColumns: 'Merge columns',
|
||||||
|
terminalColumn: 'Terminal column {n}',
|
||||||
|
openTerminalBeside: 'Open a terminal beside',
|
||||||
loadFailed: 'Could not load.',
|
loadFailed: 'Could not load.',
|
||||||
noTerminal: 'No terminal open',
|
noTerminal: 'No terminal open',
|
||||||
noTerminalHint: 'Open a Claude session from the tree to attach a terminal here.',
|
noTerminalHint: 'Open a Claude session from the tree to attach a terminal here.',
|
||||||
@@ -293,6 +299,12 @@ export default {
|
|||||||
conflict: 'This file changed on disk since you opened it.',
|
conflict: 'This file changed on disk since you opened it.',
|
||||||
reload: 'Reload',
|
reload: 'Reload',
|
||||||
overwrite: 'Overwrite',
|
overwrite: 'Overwrite',
|
||||||
|
loadingEditor: 'Loading the code editor…',
|
||||||
|
loadingFile: 'Loading file…',
|
||||||
|
loadFailed: 'The code editor could not be loaded.',
|
||||||
|
loadFailedHint: 'Check your connection, then retry. If it keeps failing, reload the page.',
|
||||||
|
reloadPage: 'Reload page',
|
||||||
|
syncFailed: 'This file can no longer be read on disk (moved, deleted, or not readable).',
|
||||||
},
|
},
|
||||||
diff: {
|
diff: {
|
||||||
binary: 'Binary file. No text diff.',
|
binary: 'Binary file. No text diff.',
|
||||||
@@ -306,6 +318,7 @@ export default {
|
|||||||
unstaged: 'unstaged',
|
unstaged: 'unstaged',
|
||||||
conflicts: 'conflicts',
|
conflicts: 'conflicts',
|
||||||
noWorktreeHint: 'Pick a worktree in the explorer to see its changes.',
|
noWorktreeHint: 'Pick a worktree in the explorer to see its changes.',
|
||||||
|
indexHint: 'Every open project and its worktrees. Pick one to review, commit and push it.',
|
||||||
locked: 'locked worktree',
|
locked: 'locked worktree',
|
||||||
prunable: 'stale worktree (prunable)',
|
prunable: 'stale worktree (prunable)',
|
||||||
detached: 'detached HEAD',
|
detached: 'detached HEAD',
|
||||||
@@ -333,6 +346,29 @@ export default {
|
|||||||
pushUnsupported: 'unavailable (requires HTTPS; on iOS, install the PWA first)',
|
pushUnsupported: 'unavailable (requires HTTPS; on iOS, install the PWA first)',
|
||||||
pwaHint: 'On mobile, install Arboretum as an app (“Add to Home Screen”) for full-screen access and notifications.',
|
pwaHint: 'On mobile, install Arboretum as an app (“Add to Home Screen”) for full-screen access and notifications.',
|
||||||
},
|
},
|
||||||
|
changes: {
|
||||||
|
title: 'Changes',
|
||||||
|
summary: 'nothing to commit | 1 worktree to review | {n} worktrees to review',
|
||||||
|
repoDirty: 'no change | 1 changed file | {n} changed files',
|
||||||
|
allClean: 'Everything is committed and pushed',
|
||||||
|
allCleanHint: 'No uncommitted change in your open projects. Show clean worktrees to review them anyway.',
|
||||||
|
scope: {
|
||||||
|
follow: 'Follow the focused terminal',
|
||||||
|
all: 'Show every project',
|
||||||
|
allLabel: 'All projects',
|
||||||
|
group: 'Group {name}',
|
||||||
|
emptyInScope: 'Nothing to review in this scope',
|
||||||
|
emptyInScopeHint: 'This terminal works on a clean tree. Show every project to see the rest.',
|
||||||
|
},
|
||||||
|
showClean: 'Show clean worktrees',
|
||||||
|
hideClean: 'Hide clean worktrees',
|
||||||
|
expandAll: 'Expand all',
|
||||||
|
collapseAll: 'Collapse all',
|
||||||
|
unpushed: '{n} to push',
|
||||||
|
openInEditor: 'Open in an editor tab',
|
||||||
|
loadFailed: 'Could not read the changes of this worktree.',
|
||||||
|
clean: 'clean',
|
||||||
|
},
|
||||||
history: {
|
history: {
|
||||||
title: 'History',
|
title: 'History',
|
||||||
empty: 'No commit on this branch.',
|
empty: 'No commit on this branch.',
|
||||||
@@ -415,6 +451,9 @@ export default {
|
|||||||
openFullscreen: 'Open fullscreen',
|
openFullscreen: 'Open fullscreen',
|
||||||
group: 'Group',
|
group: 'Group',
|
||||||
covers: 'covers',
|
covers: 'covers',
|
||||||
|
connecting: 'Connecting to the terminal...',
|
||||||
|
waitingForOutput: 'No output received yet.',
|
||||||
|
refreshScreen: 'Refresh screen',
|
||||||
},
|
},
|
||||||
push: {
|
push: {
|
||||||
enable: 'Enable notifications',
|
enable: 'Enable notifications',
|
||||||
@@ -546,6 +585,7 @@ export default {
|
|||||||
newSession: 'New session',
|
newSession: 'New session',
|
||||||
addRepo: 'Add repo',
|
addRepo: 'Add repo',
|
||||||
newGroup: 'New group',
|
newGroup: 'New group',
|
||||||
|
splitTerminal: 'Split the terminal dock',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
toast: {
|
toast: {
|
||||||
|
|||||||
@@ -262,6 +262,12 @@ const fr: typeof en = {
|
|||||||
noFileHint: 'Choisissez un fichier dans l’arbre pour l’éditer, ou un fichier modifié pour voir son diff.',
|
noFileHint: 'Choisissez un fichier dans l’arbre pour l’éditer, ou un fichier modifié pour voir son diff.',
|
||||||
terminals: 'Terminaux',
|
terminals: 'Terminaux',
|
||||||
resizePanel: 'Redimensionner le panneau',
|
resizePanel: 'Redimensionner le panneau',
|
||||||
|
resizeColumns: 'Redimensionner les colonnes de terminaux',
|
||||||
|
splitTerminal: 'Ouvrir à côté',
|
||||||
|
splitTerminalFull: 'Trois colonnes au maximum',
|
||||||
|
mergeColumns: 'Fusionner les colonnes',
|
||||||
|
terminalColumn: 'Colonne de terminaux {n}',
|
||||||
|
openTerminalBeside: 'Ouvrir un terminal à côté',
|
||||||
loadFailed: 'Chargement impossible.',
|
loadFailed: 'Chargement impossible.',
|
||||||
noTerminal: 'Aucun terminal ouvert',
|
noTerminal: 'Aucun terminal ouvert',
|
||||||
noTerminalHint: 'Ouvrez une session Claude depuis l’arbre pour y attacher un terminal.',
|
noTerminalHint: 'Ouvrez une session Claude depuis l’arbre pour y attacher un terminal.',
|
||||||
@@ -295,6 +301,12 @@ const fr: typeof en = {
|
|||||||
conflict: 'Ce fichier a changé sur le disque depuis son ouverture.',
|
conflict: 'Ce fichier a changé sur le disque depuis son ouverture.',
|
||||||
reload: 'Recharger',
|
reload: 'Recharger',
|
||||||
overwrite: 'Écraser',
|
overwrite: 'Écraser',
|
||||||
|
loadingEditor: 'Chargement de l’éditeur de code…',
|
||||||
|
loadingFile: 'Chargement du fichier…',
|
||||||
|
loadFailed: 'L’éditeur de code n’a pas pu être chargé.',
|
||||||
|
loadFailedHint: 'Vérifiez votre connexion puis réessayez. Si l’échec persiste, rechargez la page.',
|
||||||
|
reloadPage: 'Recharger la page',
|
||||||
|
syncFailed: 'Ce fichier n’est plus lisible sur le disque (déplacé, supprimé, ou droits insuffisants).',
|
||||||
},
|
},
|
||||||
diff: {
|
diff: {
|
||||||
binary: 'Fichier binaire. Pas de diff texte.',
|
binary: 'Fichier binaire. Pas de diff texte.',
|
||||||
@@ -308,6 +320,7 @@ const fr: typeof en = {
|
|||||||
unstaged: 'non indexé',
|
unstaged: 'non indexé',
|
||||||
conflicts: 'conflits',
|
conflicts: 'conflits',
|
||||||
noWorktreeHint: 'Sélectionnez un worktree dans l’explorateur pour voir ses changements.',
|
noWorktreeHint: 'Sélectionnez un worktree dans l’explorateur pour voir ses changements.',
|
||||||
|
indexHint: 'Tous vos projets ouverts et leurs worktrees. Choisissez-en un pour le relire, le committer et le pousser.',
|
||||||
locked: 'worktree verrouillé',
|
locked: 'worktree verrouillé',
|
||||||
prunable: 'worktree orphelin (à nettoyer)',
|
prunable: 'worktree orphelin (à nettoyer)',
|
||||||
detached: 'HEAD détaché',
|
detached: 'HEAD détaché',
|
||||||
@@ -335,6 +348,29 @@ const fr: typeof en = {
|
|||||||
pushUnsupported: 'non disponibles (nécessite HTTPS ; sur iOS, installez la PWA)',
|
pushUnsupported: 'non disponibles (nécessite HTTPS ; sur iOS, installez la PWA)',
|
||||||
pwaHint: 'Sur mobile, installez Arboretum comme application (« Ajouter à l’écran d’accueil ») pour un accès plein écran et les notifications.',
|
pwaHint: 'Sur mobile, installez Arboretum comme application (« Ajouter à l’écran d’accueil ») pour un accès plein écran et les notifications.',
|
||||||
},
|
},
|
||||||
|
changes: {
|
||||||
|
title: 'Changements',
|
||||||
|
summary: 'rien à committer | 1 worktree à relire | {n} worktrees à relire',
|
||||||
|
repoDirty: 'aucun changement | 1 fichier modifié | {n} fichiers modifiés',
|
||||||
|
allClean: 'Tout est committé et poussé',
|
||||||
|
allCleanHint: 'Aucun changement non committé dans vos projets ouverts. Affichez les worktrees propres pour les relire quand même.',
|
||||||
|
scope: {
|
||||||
|
follow: 'Suivre le terminal actif',
|
||||||
|
all: 'Voir tous les projets',
|
||||||
|
allLabel: 'Tous les projets',
|
||||||
|
group: 'Groupe {name}',
|
||||||
|
emptyInScope: 'Rien à traiter dans cette portée',
|
||||||
|
emptyInScopeHint: 'Ce terminal travaille sur un arbre propre. Affichez tous les projets pour voir le reste.',
|
||||||
|
},
|
||||||
|
showClean: 'Afficher les worktrees propres',
|
||||||
|
hideClean: 'Masquer les worktrees propres',
|
||||||
|
expandAll: 'Tout déplier',
|
||||||
|
collapseAll: 'Tout replier',
|
||||||
|
unpushed: '{n} à pousser',
|
||||||
|
openInEditor: 'Ouvrir dans un onglet',
|
||||||
|
loadFailed: 'Impossible de lire les changements de ce worktree.',
|
||||||
|
clean: 'propre',
|
||||||
|
},
|
||||||
history: {
|
history: {
|
||||||
title: 'Historique',
|
title: 'Historique',
|
||||||
empty: 'Aucun commit sur cette branche.',
|
empty: 'Aucun commit sur cette branche.',
|
||||||
@@ -418,6 +454,9 @@ const fr: typeof en = {
|
|||||||
openFullscreen: 'Ouvrir en plein écran',
|
openFullscreen: 'Ouvrir en plein écran',
|
||||||
group: 'Groupe',
|
group: 'Groupe',
|
||||||
covers: 'couvre',
|
covers: 'couvre',
|
||||||
|
connecting: 'Connexion au terminal...',
|
||||||
|
waitingForOutput: 'Aucune sortie reçue pour l’instant.',
|
||||||
|
refreshScreen: 'Rafraîchir l’écran',
|
||||||
},
|
},
|
||||||
push: {
|
push: {
|
||||||
enable: 'Activer les notifications',
|
enable: 'Activer les notifications',
|
||||||
@@ -549,6 +588,7 @@ const fr: typeof en = {
|
|||||||
newSession: 'Nouvelle session',
|
newSession: 'Nouvelle session',
|
||||||
addRepo: 'Ajouter un dépôt',
|
addRepo: 'Ajouter un dépôt',
|
||||||
newGroup: 'Nouveau groupe',
|
newGroup: 'Nouveau groupe',
|
||||||
|
splitTerminal: 'Diviser le dock terminal',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
toast: {
|
toast: {
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// Règles d'affichage de la vue « Changements » (zone centrale) et de l'index Git (barre latérale).
|
||||||
|
// Fonctions pures : elles ne touchent ni aux stores ni au réseau, et sont testées en isolation.
|
||||||
|
import type { RepoSummary, WorktreeGitStatus, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Un worktree « a du travail » : quelque chose à indexer, à committer, à résoudre, ou à pousser.
|
||||||
|
* `ahead > 0` compte, la vue servant aussi à pousser un worktree propre mais en avance. Les
|
||||||
|
* compteurs fins sont OPTIONNELS dans le protocole (champs additifs P7) : `dirtyCount` reste le
|
||||||
|
* filet. `behind` seul ne compte pas : rien à faire de notre côté, c'est un pull.
|
||||||
|
*/
|
||||||
|
export function hasPendingWork(git: WorktreeGitStatus): boolean {
|
||||||
|
return (
|
||||||
|
git.dirtyCount > 0 ||
|
||||||
|
(git.stagedCount ?? 0) > 0 ||
|
||||||
|
(git.unstagedCount ?? 0) > 0 ||
|
||||||
|
(git.conflictCount ?? 0) > 0 ||
|
||||||
|
git.ahead > 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nombre de fichiers modifiés d'un worktree, tel qu'affiché sans lire la liste (compteurs WS). */
|
||||||
|
export function dirtyFileCount(git: WorktreeGitStatus): number {
|
||||||
|
const fine = (git.stagedCount ?? 0) + (git.unstagedCount ?? 0);
|
||||||
|
return Math.max(git.dirtyCount, fine);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RepoChangesGroup {
|
||||||
|
repo: RepoSummary;
|
||||||
|
worktrees: WorktreeSummary[];
|
||||||
|
/** Somme des fichiers modifiés des worktrees retenus, pour l'en-tête du dépôt. */
|
||||||
|
dirtyFiles: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupOptions {
|
||||||
|
/** Inclure les worktrees propres et à jour (audit) plutôt que le seul travail en cours. */
|
||||||
|
showClean: boolean;
|
||||||
|
/** Worktree actif : toujours affiché, même propre, pour que la vue ne se vide pas après un commit. */
|
||||||
|
active: { repoId: string; wtPath: string } | null;
|
||||||
|
/**
|
||||||
|
* Filtre de PORTÉE (terminal focalisé, ou son groupe). Il s'applique en ET : un worktree hors
|
||||||
|
* portée reste masqué même s'il a du travail en attente, et même s'il est le worktree actif, sinon
|
||||||
|
* une portée de groupe laisserait fuir un worktree étranger. Prédicat INJECTÉ : ce modèle n'a pas
|
||||||
|
* à connaître les groupes. Absent = aucun filtrage, donc le comportement d'origine.
|
||||||
|
*/
|
||||||
|
inScope?: (w: { repoId: string; wtPath: string }) => boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regroupe les worktrees par dépôt pour la vue Changements. `repos` doit déjà être filtré et trié
|
||||||
|
* (worktrees.visibleRepos) et `forRepo` renvoyer les worktrees d'un dépôt (main d'abord). Un dépôt
|
||||||
|
* dont aucun worktree n'est retenu disparaît entièrement : pas d'en-tête orphelin.
|
||||||
|
*/
|
||||||
|
export function groupWorktreesByRepo(
|
||||||
|
repos: RepoSummary[],
|
||||||
|
forRepo: (repoId: string) => WorktreeSummary[],
|
||||||
|
opts: GroupOptions,
|
||||||
|
): RepoChangesGroup[] {
|
||||||
|
const groups: RepoChangesGroup[] = [];
|
||||||
|
for (const repo of repos) {
|
||||||
|
const kept = forRepo(repo.id).filter(
|
||||||
|
(w) =>
|
||||||
|
(!opts.inScope || opts.inScope({ repoId: w.repoId, wtPath: w.path })) &&
|
||||||
|
(opts.showClean ||
|
||||||
|
hasPendingWork(w.git) ||
|
||||||
|
(!!opts.active && opts.active.repoId === w.repoId && opts.active.wtPath === w.path)),
|
||||||
|
);
|
||||||
|
if (kept.length === 0) continue;
|
||||||
|
groups.push({
|
||||||
|
repo,
|
||||||
|
worktrees: kept,
|
||||||
|
dirtyFiles: kept.reduce((sum, w) => sum + dirtyFileCount(w.git), 0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ordre de l'index : ce qui demande une action d'abord, puis le worktree principal, puis le chemin. */
|
||||||
|
export function sortForIndex(list: WorktreeSummary[]): WorktreeSummary[] {
|
||||||
|
return [...list].sort(
|
||||||
|
(a, b) =>
|
||||||
|
Number(hasPendingWork(b.git)) - Number(hasPendingWork(a.git)) ||
|
||||||
|
Number(b.isMain) - Number(a.isMain) ||
|
||||||
|
a.path.localeCompare(b.path),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nombre de worktrees à traiter, tous dépôts visibles confondus. `inScope` optionnel pour le compteur
|
||||||
|
* d'en-tête de la vue Changements ; le badge de la barre d'activité l'omet volontairement : c'est une
|
||||||
|
* NOTIFICATION, sa raison d'être est de signaler le travail qu'on n'est pas en train de regarder.
|
||||||
|
*/
|
||||||
|
export function pendingWorktreeCount(
|
||||||
|
repos: RepoSummary[],
|
||||||
|
forRepo: (repoId: string) => WorktreeSummary[],
|
||||||
|
inScope?: (w: { repoId: string; wtPath: string }) => boolean,
|
||||||
|
): number {
|
||||||
|
let n = 0;
|
||||||
|
for (const repo of repos) {
|
||||||
|
for (const w of forRepo(repo.id)) {
|
||||||
|
if (inScope && !inScope({ repoId: w.repoId, wtPath: w.path })) continue;
|
||||||
|
if (hasPendingWork(w.git)) n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// Portée de travail déduite du terminal focalisé : « je regarde ce terminal, montre-moi SES fichiers
|
||||||
|
// et SES commits ». Sans cela, la vue Changements listait tous les projets ouverts et on se perdait
|
||||||
|
// entre eux.
|
||||||
|
//
|
||||||
|
// Fonctions PURES, sans store ni réseau. La corrélation chemin ↔ worktree reste celle de
|
||||||
|
// @arboretum/shared (path-match) : une seule règle pour le daemon, le web et l'extension VS Code.
|
||||||
|
import { findWorktreeForCwd, sessionDirs } from '@arboretum/shared';
|
||||||
|
|
||||||
|
export type ContextScope =
|
||||||
|
| { kind: 'all' }
|
||||||
|
| { kind: 'worktree'; repoId: string; wtPath: string }
|
||||||
|
| { kind: 'group'; groupId: string };
|
||||||
|
|
||||||
|
export const SCOPE_ALL: ContextScope = { kind: 'all' };
|
||||||
|
|
||||||
|
/** Appartenance minimale requise d'un groupe : le modèle n'a pas besoin de tout GroupSummary. */
|
||||||
|
export interface GroupRef {
|
||||||
|
id: string;
|
||||||
|
repoIds: string[];
|
||||||
|
}
|
||||||
|
export interface WorktreeRefLike {
|
||||||
|
repoId: string;
|
||||||
|
path: string;
|
||||||
|
}
|
||||||
|
export interface SessionLike {
|
||||||
|
cwd: string;
|
||||||
|
addedDirs?: string[] | null;
|
||||||
|
groupId?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dirsOf = (s: SessionLike): string[] => sessionDirs({ cwd: s.cwd, ...(s.addedDirs ? { addedDirs: s.addedDirs } : {}) });
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tous les worktrees qu'une session occupe : son cwd et ses répertoires reliés, chacun rattaché au
|
||||||
|
* worktree le plus spécifique qui le contient, dédupliqués. Deux consommateurs : la résolution de
|
||||||
|
* portée ci-dessous, et les abonnements FS (un terminal visible doit rafraîchir son statut git).
|
||||||
|
*/
|
||||||
|
export function worktreesForSession<T extends WorktreeRefLike>(session: SessionLike, all: T[]): T[] {
|
||||||
|
const out: T[] = [];
|
||||||
|
for (const dir of dirsOf(session)) {
|
||||||
|
const w = findWorktreeForCwd(dir, all);
|
||||||
|
if (w && !out.includes(w)) out.push(w);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Portée qu'impose une session (règle produit : « terminal actif, sinon groupe ») :
|
||||||
|
* 1. `groupId` renseigné -> GROUPE. Une session de groupe a pour cwd le PARENT COMMUN des dépôts :
|
||||||
|
* le rattacher à un worktree n'aurait aucun sens, on ne consulte donc même pas les chemins.
|
||||||
|
* 2. la session couvre 2 dépôts ou plus -> GROUPE qui les contient TOUS ; à défaut d'un tel groupe,
|
||||||
|
* 'all' (mieux vaut tout montrer que cacher la moitié du travail en cours).
|
||||||
|
* 3. sinon -> le WORKTREE le plus spécifique contenant son cwd (ce qui rattache correctement les
|
||||||
|
* terminaux « Démarrer le projet » lancés dans un sous-répertoire).
|
||||||
|
* 4. session absente, ou cwd hors de tout worktree connu -> null : à l'appelant de se rabattre.
|
||||||
|
* Un `groupId` qui ne correspond à aucun groupe connu donne 'all', jamais une portée vide.
|
||||||
|
*/
|
||||||
|
export function resolveScope(session: SessionLike | null, worktrees: WorktreeRefLike[], groups: GroupRef[]): ContextScope | null {
|
||||||
|
if (!session) return null;
|
||||||
|
if (session.groupId) {
|
||||||
|
return groups.some((g) => g.id === session.groupId) ? { kind: 'group', groupId: session.groupId } : SCOPE_ALL;
|
||||||
|
}
|
||||||
|
const covered = worktreesForSession(session, worktrees);
|
||||||
|
const repoIds = [...new Set(covered.map((w) => w.repoId))];
|
||||||
|
if (repoIds.length > 1) {
|
||||||
|
const common = groups.find((g) => repoIds.every((id) => g.repoIds.includes(id)));
|
||||||
|
return common ? { kind: 'group', groupId: common.id } : SCOPE_ALL;
|
||||||
|
}
|
||||||
|
const only = covered[0];
|
||||||
|
return only ? { kind: 'worktree', repoId: only.repoId, wtPath: only.path } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le worktree tombe-t-il dans la portée ? Primitive du filtre de la vue Changements. */
|
||||||
|
export function scopeContains(scope: ContextScope, w: { repoId: string; wtPath: string }, groups: GroupRef[]): boolean {
|
||||||
|
if (scope.kind === 'all') return true;
|
||||||
|
if (scope.kind === 'worktree') return scope.repoId === w.repoId && scope.wtPath === w.wtPath;
|
||||||
|
const group = groups.find((g) => g.id === scope.groupId);
|
||||||
|
return !!group && group.repoIds.includes(w.repoId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Worktrees couverts par la portée. */
|
||||||
|
export function worktreesInScope<T extends WorktreeRefLike>(scope: ContextScope, all: T[], groups: GroupRef[]): T[] {
|
||||||
|
if (scope.kind === 'all') return all;
|
||||||
|
return all.filter((w) => scopeContains(scope, { repoId: w.repoId, wtPath: w.path }, groups));
|
||||||
|
}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
// Algèbre des colonnes du dock terminaux, et géométrie verticale du dock.
|
||||||
|
//
|
||||||
|
// Fonctions PURES : chacune reçoit l'état et rend un NOUVEL état. C'est exactement le contrat d'un
|
||||||
|
// `persistedRef`, dont le watch n'est pas profond : seule une réassignation déclenche l'écriture.
|
||||||
|
//
|
||||||
|
// INVARIANTS (vérifiés par `expectDockInvariants` dans les tests) :
|
||||||
|
// 1. une session vit dans AU PLUS une colonne. Deux panes sur la même session voudraient dire deux
|
||||||
|
// attaches WS : la seconde serait non-controlling et le PTY resterait figé sur la géométrie de
|
||||||
|
// la première, donc affichage déformé garanti.
|
||||||
|
// 2. aucune colonne vide.
|
||||||
|
// 3. `activeSessionId` est toujours membre de `sessionIds`.
|
||||||
|
// 4. `activeColumnId` désigne une colonne existante ; il est null si et seulement si `columns` est vide.
|
||||||
|
// 5. la somme des `ratio` vaut 1, et chaque ratio est >= MIN_DOCK_COLUMN_RATIO.
|
||||||
|
|
||||||
|
export interface DockColumn {
|
||||||
|
/** Id stable : clé de rendu de la colonne, et cible d'un déplacement de pane. */
|
||||||
|
id: string;
|
||||||
|
/** Onglets de la colonne, dans l'ordre d'affichage. */
|
||||||
|
sessionIds: string[];
|
||||||
|
/** Onglet visible de cette colonne. */
|
||||||
|
activeSessionId: string;
|
||||||
|
/** Part de la largeur du dock. Des px seraient faux dès que le dock change de largeur. */
|
||||||
|
ratio: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DockState {
|
||||||
|
columns: DockColumn[];
|
||||||
|
activeColumnId: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Au-delà de trois colonnes, un xterm n'a plus assez de colonnes de texte pour un TUI. */
|
||||||
|
export const MAX_DOCK_COLUMNS = 3;
|
||||||
|
/** Part minimale d'une colonne : borne l'état PERSISTÉ (le splitter clampe en plus, en px). */
|
||||||
|
export const MIN_DOCK_COLUMN_RATIO = 0.15;
|
||||||
|
|
||||||
|
export const EMPTY_DOCK: DockState = { columns: [], activeColumnId: null };
|
||||||
|
|
||||||
|
let idSeq = 0;
|
||||||
|
/**
|
||||||
|
* Id de colonne unique. PAS `crypto.randomUUID` : il exige un contexte sécurisé, or le daemon se
|
||||||
|
* sert très souvent en http simple sur une IP de LAN (accès distant, mode serveur web).
|
||||||
|
*/
|
||||||
|
export function newColumnId(): string {
|
||||||
|
idSeq += 1;
|
||||||
|
return `c${Date.now().toString(36)}${idSeq.toString(36)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function findPane(s: DockState, sessionId: string): { index: number; column: DockColumn } | null {
|
||||||
|
for (const [index, column] of s.columns.entries()) {
|
||||||
|
if (column.sessionIds.includes(sessionId)) return { index, column };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function activeColumnOf(s: DockState): DockColumn | null {
|
||||||
|
return s.columns.find((c) => c.id === s.activeColumnId) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Renormalise les ratios (somme 1, plancher MIN) : appelé après toute création/suppression. */
|
||||||
|
function normalize(columns: DockColumn[]): DockColumn[] {
|
||||||
|
if (columns.length === 0) return [];
|
||||||
|
const floor = Math.min(MIN_DOCK_COLUMN_RATIO, 1 / columns.length);
|
||||||
|
const raised = columns.map((c) => ({ ...c, ratio: Math.max(floor, c.ratio > 0 ? c.ratio : floor) }));
|
||||||
|
const total = raised.reduce((sum, c) => sum + c.ratio, 0);
|
||||||
|
return raised.map((c) => ({ ...c, ratio: c.ratio / total }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recale `activeColumnId` sur une colonne qui existe (ou null quand il n'y en a plus). */
|
||||||
|
function withActiveColumn(columns: DockColumn[], preferredId: string | null): DockState {
|
||||||
|
if (columns.length === 0) return EMPTY_DOCK;
|
||||||
|
const id = columns.some((c) => c.id === preferredId) ? preferredId : columns[0]!.id;
|
||||||
|
return { columns, activeColumnId: id };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ajoute une session au dock.
|
||||||
|
* - `'tab'` : nouvel onglet de la colonne active (comportement historique du dock).
|
||||||
|
* - `'split'` : nouvelle colonne insérée APRÈS l'active, à qui elle prend la moitié de sa part ;
|
||||||
|
* les autres colonnes ne bougent pas.
|
||||||
|
* Une session DÉJÀ ouverte est déplacée, jamais dupliquée (invariant 1). Au plafond de colonnes, un
|
||||||
|
* `'split'` retombe en onglet plutôt que d'échouer sans rien dire.
|
||||||
|
*/
|
||||||
|
export function addPane(s: DockState, sessionId: string, mode: 'tab' | 'split', makeId: () => string = newColumnId): DockState {
|
||||||
|
if (findPane(s, sessionId)) {
|
||||||
|
return mode === 'split' ? movePane(s, sessionId, { split: true }, makeId) : focusPane(s, sessionId);
|
||||||
|
}
|
||||||
|
if (s.columns.length === 0) {
|
||||||
|
const column: DockColumn = { id: makeId(), sessionIds: [sessionId], activeSessionId: sessionId, ratio: 1 };
|
||||||
|
return { columns: [column], activeColumnId: column.id };
|
||||||
|
}
|
||||||
|
const activeIndex = Math.max(
|
||||||
|
0,
|
||||||
|
s.columns.findIndex((c) => c.id === s.activeColumnId),
|
||||||
|
);
|
||||||
|
if (mode === 'tab' || s.columns.length >= MAX_DOCK_COLUMNS) {
|
||||||
|
const columns = s.columns.map((c, i) =>
|
||||||
|
i === activeIndex ? { ...c, sessionIds: [...c.sessionIds, sessionId], activeSessionId: sessionId } : c,
|
||||||
|
);
|
||||||
|
return withActiveColumn(columns, s.columns[activeIndex]!.id);
|
||||||
|
}
|
||||||
|
const host = s.columns[activeIndex]!;
|
||||||
|
const half = host.ratio / 2;
|
||||||
|
const created: DockColumn = { id: makeId(), sessionIds: [sessionId], activeSessionId: sessionId, ratio: half };
|
||||||
|
const columns = [...s.columns];
|
||||||
|
columns[activeIndex] = { ...host, ratio: half };
|
||||||
|
columns.splice(activeIndex + 1, 0, created);
|
||||||
|
return { columns: normalize(columns), activeColumnId: created.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rend visible un pane et active SA colonne (la frappe doit suivre). */
|
||||||
|
export function focusPane(s: DockState, sessionId: string): DockState {
|
||||||
|
const found = findPane(s, sessionId);
|
||||||
|
if (!found) return s;
|
||||||
|
if (found.column.activeSessionId === sessionId && s.activeColumnId === found.column.id) return s;
|
||||||
|
const columns = s.columns.map((c) => (c.id === found.column.id ? { ...c, activeSessionId: sessionId } : c));
|
||||||
|
return { columns, activeColumnId: found.column.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function focusColumn(s: DockState, columnId: string): DockState {
|
||||||
|
if (s.activeColumnId === columnId || !s.columns.some((c) => c.id === columnId)) return s;
|
||||||
|
return { ...s, activeColumnId: columnId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retire un pane. Une colonne vidée disparaît et lègue sa part à son voisin de gauche (à défaut, de
|
||||||
|
* droite) : la largeur totale reste occupée, sans trou.
|
||||||
|
*/
|
||||||
|
export function closePane(s: DockState, sessionId: string): DockState {
|
||||||
|
const found = findPane(s, sessionId);
|
||||||
|
if (!found) return s;
|
||||||
|
const rest = found.column.sessionIds.filter((id) => id !== sessionId);
|
||||||
|
if (rest.length > 0) {
|
||||||
|
const idx = found.column.sessionIds.indexOf(sessionId);
|
||||||
|
const nextActive =
|
||||||
|
found.column.activeSessionId === sessionId ? (rest[idx] ?? rest[idx - 1] ?? rest[0]!) : found.column.activeSessionId;
|
||||||
|
const columns = s.columns.map((c) => (c.id === found.column.id ? { ...c, sessionIds: rest, activeSessionId: nextActive } : c));
|
||||||
|
return withActiveColumn(columns, s.activeColumnId);
|
||||||
|
}
|
||||||
|
const heirIndex = found.index > 0 ? found.index - 1 : found.index + 1;
|
||||||
|
const columns = s.columns
|
||||||
|
.map((c, i) => (i === heirIndex ? { ...c, ratio: c.ratio + found.column.ratio } : c))
|
||||||
|
.filter((_, i) => i !== found.index);
|
||||||
|
const preferred = s.activeColumnId === found.column.id ? (columns[Math.max(0, Math.min(heirIndex, columns.length - 1))]?.id ?? null) : s.activeColumnId;
|
||||||
|
return withActiveColumn(normalize(columns), preferred);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Déplace un pane vers une autre colonne, ou dans une colonne neuve détachée à droite. */
|
||||||
|
export function movePane(
|
||||||
|
s: DockState,
|
||||||
|
sessionId: string,
|
||||||
|
target: { columnId: string } | { split: true },
|
||||||
|
makeId: () => string = newColumnId,
|
||||||
|
): DockState {
|
||||||
|
const found = findPane(s, sessionId);
|
||||||
|
if (!found) return s;
|
||||||
|
if ('columnId' in target) {
|
||||||
|
if (target.columnId === found.column.id || !s.columns.some((c) => c.id === target.columnId)) return s;
|
||||||
|
const detached = closePane(s, sessionId);
|
||||||
|
const columns = detached.columns.map((c) =>
|
||||||
|
c.id === target.columnId ? { ...c, sessionIds: [...c.sessionIds, sessionId], activeSessionId: sessionId } : c,
|
||||||
|
);
|
||||||
|
return withActiveColumn(columns, target.columnId);
|
||||||
|
}
|
||||||
|
// Déjà seul dans sa colonne : le détacher ne changerait rien (et créerait une colonne vide).
|
||||||
|
if (found.column.sessionIds.length === 1) return focusPane(s, sessionId);
|
||||||
|
if (s.columns.length >= MAX_DOCK_COLUMNS) return focusPane(s, sessionId);
|
||||||
|
const detached = closePane(s, sessionId);
|
||||||
|
const hostIndex = detached.columns.findIndex((c) => c.id === found.column.id);
|
||||||
|
const anchor = hostIndex >= 0 ? hostIndex : detached.columns.length - 1;
|
||||||
|
const host = detached.columns[anchor]!;
|
||||||
|
const half = host.ratio / 2;
|
||||||
|
const created: DockColumn = { id: makeId(), sessionIds: [sessionId], activeSessionId: sessionId, ratio: half };
|
||||||
|
const columns = [...detached.columns];
|
||||||
|
columns[anchor] = { ...host, ratio: half };
|
||||||
|
columns.splice(anchor + 1, 0, created);
|
||||||
|
return { columns: normalize(columns), activeColumnId: created.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Déplace la frontière entre les colonnes `index` et `index + 1`. `ratioOfTrack` est la part visée
|
||||||
|
* par le bord droit de la colonne de gauche, mesurée sur la largeur TOTALE. La somme de la PAIRE est
|
||||||
|
* préservée : tirer une poignée ne fait jamais bouger une colonne qu'on n'a pas saisie.
|
||||||
|
*/
|
||||||
|
export function setSplit(s: DockState, index: number, ratioOfTrack: number): DockState {
|
||||||
|
const left = s.columns[index];
|
||||||
|
const right = s.columns[index + 1];
|
||||||
|
if (!left || !right) return s;
|
||||||
|
const before = s.columns.slice(0, index).reduce((sum, c) => sum + c.ratio, 0);
|
||||||
|
const pair = left.ratio + right.ratio;
|
||||||
|
const wanted = ratioOfTrack - before;
|
||||||
|
const leftRatio = Math.min(pair - MIN_DOCK_COLUMN_RATIO, Math.max(MIN_DOCK_COLUMN_RATIO, wanted));
|
||||||
|
const columns = s.columns.map((c, i) => {
|
||||||
|
if (i === index) return { ...c, ratio: leftRatio };
|
||||||
|
if (i === index + 1) return { ...c, ratio: pair - leftRatio };
|
||||||
|
return c;
|
||||||
|
});
|
||||||
|
return { ...s, columns };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Réconciliation avec la réalité : sessions mortes retirées, colonnes vidées supprimées, onglets
|
||||||
|
* actifs réparés, ratios renormalisés. Idempotente.
|
||||||
|
*/
|
||||||
|
export function prunePanes(s: DockState, liveSessionIds: Set<string>): DockState {
|
||||||
|
const columns: DockColumn[] = [];
|
||||||
|
for (const c of s.columns) {
|
||||||
|
const sessionIds = c.sessionIds.filter((id) => liveSessionIds.has(id));
|
||||||
|
if (sessionIds.length === 0) continue;
|
||||||
|
const activeSessionId = sessionIds.includes(c.activeSessionId) ? c.activeSessionId : sessionIds[0]!;
|
||||||
|
columns.push({ ...c, sessionIds, activeSessionId });
|
||||||
|
}
|
||||||
|
if (columns.length === s.columns.length && columns.every((c, i) => c.sessionIds.length === s.columns[i]!.sessionIds.length)) {
|
||||||
|
// rien n'a bougé : on rend l'état d'origine (pas de réassignation, donc pas d'écriture inutile)
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
return withActiveColumn(normalize(columns), s.activeColumnId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tout ramener en une colonne : échappatoire utilisateur, et repli sûr d'un état douteux. */
|
||||||
|
export function mergeColumns(s: DockState): DockState {
|
||||||
|
if (s.columns.length <= 1) return s;
|
||||||
|
const active = activeColumnOf(s);
|
||||||
|
const first = s.columns[0]!;
|
||||||
|
const sessionIds = s.columns.flatMap((c) => c.sessionIds);
|
||||||
|
const activeSessionId = active?.activeSessionId ?? first.activeSessionId;
|
||||||
|
const column: DockColumn = { id: first.id, sessionIds, activeSessionId, ratio: 1 };
|
||||||
|
return { columns: [column], activeColumnId: column.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Migration silencieuse de l'ancien dock mono-colonne (`arb.ide.dock`) vers les colonnes. */
|
||||||
|
export function migrateDock(sessionIds: string[], activeSessionId: string | null, makeId: () => string = newColumnId): DockState {
|
||||||
|
if (sessionIds.length === 0) return EMPTY_DOCK;
|
||||||
|
const active = activeSessionId && sessionIds.includes(activeSessionId) ? activeSessionId : sessionIds[0]!;
|
||||||
|
const column: DockColumn = { id: makeId(), sessionIds: [...sessionIds], activeSessionId: active, ratio: 1 };
|
||||||
|
return { columns: [column], activeColumnId: column.id };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- géométrie verticale du dock ----
|
||||||
|
// Bornes UNIQUES : elles étaient dupliquées entre le template d'IdeShell et le clamp du store, avec
|
||||||
|
// un plafond figé de 640 px qui est ridicule sur un écran haut (et intenable à deux terminaux).
|
||||||
|
|
||||||
|
export const DOCK_MIN_HEIGHT = 120;
|
||||||
|
|
||||||
|
/** Plafond : 80 % du viewport, en laissant toujours de quoi voir la zone centrale. */
|
||||||
|
export function dockMaxHeight(viewportHeight: number): number {
|
||||||
|
return Math.max(DOCK_MIN_HEIGHT, Math.min(Math.round(viewportHeight * 0.8), viewportHeight - 200));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hauteur à garantir quand le dock s'ouvre ou gagne une colonne : ~45 % du viewport. À 240 px un
|
||||||
|
* terminal n'affiche qu'une vingtaine de lignes, ce qui casse le rendu d'un TUI.
|
||||||
|
*/
|
||||||
|
export function dockOpenHeight(viewportHeight: number): number {
|
||||||
|
return Math.max(DOCK_MIN_HEIGHT, Math.min(Math.round(viewportHeight * 0.45), dockMaxHeight(viewportHeight)));
|
||||||
|
}
|
||||||
@@ -5,12 +5,45 @@
|
|||||||
// avancés (TS/JSON) dégradent proprement : suffisant pour éditer + sauver dans le navigateur.
|
// avancés (TS/JSON) dégradent proprement : suffisant pour éditer + sauver dans le navigateur.
|
||||||
import * as monaco from 'monaco-editor';
|
import * as monaco from 'monaco-editor';
|
||||||
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
|
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
|
||||||
|
import TsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
|
||||||
|
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
|
||||||
|
import CssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
|
||||||
|
import HtmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
|
||||||
import type { ResolvedTheme } from './theme';
|
import type { ResolvedTheme } from './theme';
|
||||||
|
|
||||||
|
// Un worker par famille de langage. Ne fournir que le worker de base ne « dégradait » PAS
|
||||||
|
// proprement : dès qu'on ouvrait un .ts, le service TypeScript appelait un worker qui ne connaissait
|
||||||
|
// pas ses méthodes, et chaque ouverture jetait un rejet non géré dans la console (getSyntacticDiagnostics,
|
||||||
|
// provideInlayHints, ...). Ces workers sont des chunks séparés, téléchargés seulement quand un fichier
|
||||||
|
// du langage correspondant est ouvert.
|
||||||
(self as unknown as { MonacoEnvironment: monaco.Environment }).MonacoEnvironment = {
|
(self as unknown as { MonacoEnvironment: monaco.Environment }).MonacoEnvironment = {
|
||||||
getWorker: () => new EditorWorker(),
|
getWorker: (_id: string, label: string) => {
|
||||||
|
if (label === 'typescript' || label === 'javascript') return new TsWorker();
|
||||||
|
if (label === 'json') return new JsonWorker();
|
||||||
|
if (label === 'css' || label === 'scss' || label === 'less') return new CssWorker();
|
||||||
|
if (label === 'html' || label === 'handlebars' || label === 'razor') return new HtmlWorker();
|
||||||
|
return new EditorWorker();
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Les diagnostics SÉMANTIQUES restent coupés, workers ou pas : le worker ne voit qu'un fichier isolé,
|
||||||
|
// sans tsconfig ni node_modules, donc il signalerait des dizaines de fausses erreurs (imports non
|
||||||
|
// résolus) sur du code parfaitement valide. On garde la coloration, la complétion de base et le
|
||||||
|
// pliage ; la vraie vérification de types reste le rôle du terminal.
|
||||||
|
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
||||||
|
noSemanticValidation: true,
|
||||||
|
noSyntaxValidation: true,
|
||||||
|
noSuggestionDiagnostics: true,
|
||||||
|
});
|
||||||
|
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
|
||||||
|
noSemanticValidation: true,
|
||||||
|
noSyntaxValidation: true,
|
||||||
|
noSuggestionDiagnostics: true,
|
||||||
|
});
|
||||||
|
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({ validate: false });
|
||||||
|
monaco.languages.css.cssDefaults.setOptions({ validate: false });
|
||||||
|
monaco.languages.html.htmlDefaults.setOptions({});
|
||||||
|
|
||||||
// Deux thèmes « Emerald » (hex concrets : Monaco n'accepte pas de var CSS). Les couleurs de token
|
// Deux thèmes « Emerald » (hex concrets : Monaco n'accepte pas de var CSS). Les couleurs de token
|
||||||
// (rules) sont SANS '#', les couleurs de chrome (colors) AVEC '#'. À garder synchronisé avec style.css.
|
// (rules) sont SANS '#', les couleurs de chrome (colors) AVEC '#'. À garder synchronisé avec style.css.
|
||||||
monaco.editor.defineTheme('arboretum-dark', {
|
monaco.editor.defineTheme('arboretum-dark', {
|
||||||
|
|||||||
@@ -21,3 +21,29 @@ export function persistedRef<T>(key: string, initial: T): Ref<T> {
|
|||||||
});
|
});
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lecture BRUTE d'une clé, sans créer de ref ni s'abonner : sert aux migrations de FORME d'état,
|
||||||
|
* où l'on doit lire l'ancienne clé une fois pour construire la nouvelle.
|
||||||
|
*/
|
||||||
|
export function readPersisted<T>(key: string, fallback: T): T {
|
||||||
|
try {
|
||||||
|
const raw = localStorage.getItem(key);
|
||||||
|
return raw == null ? fallback : (JSON.parse(raw) as T);
|
||||||
|
} catch {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Oubli d'une clé, une fois sa migration faite. Indispensable : laissée en place, un onglet resté
|
||||||
|
* ouvert sur l'ancienne version de l'app la réécrirait et la migration rejouerait au démarrage
|
||||||
|
* suivant, écrasant l'état neuf.
|
||||||
|
*/
|
||||||
|
export function forgetPersisted(key: string): void {
|
||||||
|
try {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
} catch {
|
||||||
|
/* localStorage indisponible : rien à oublier */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,6 +24,11 @@ export interface TerminalSink {
|
|||||||
reset(): void;
|
reset(): void;
|
||||||
onDetached(reason: DetachReason): void;
|
onDetached(reason: DetachReason): void;
|
||||||
onControlChanged(controlling: boolean): void;
|
onControlChanged(controlling: boolean): void;
|
||||||
|
/**
|
||||||
|
* Erreur serveur portant SUR ce canal (frappe refusée, canal inconnu). Optionnel, mais sans lui
|
||||||
|
* ces refus se perdaient dans un `console.warn` : l'utilisateur tapait et rien ne se passait.
|
||||||
|
*/
|
||||||
|
onChannelError?(code: string, message: string): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SessionEvent = Extract<ServerMessage, { type: 'session_update' | 'session_exit' | 'session_archived' }>;
|
export type SessionEvent = Extract<ServerMessage, { type: 'session_update' | 'session_exit' | 'session_archived' }>;
|
||||||
@@ -42,6 +47,8 @@ export interface AttachOptions {
|
|||||||
cols: number;
|
cols: number;
|
||||||
rows: number;
|
rows: number;
|
||||||
sink: TerminalSink;
|
sink: TerminalSink;
|
||||||
|
/** false = attache d'écriture seule, sans affichage (cf. le champ `screen` du protocole). */
|
||||||
|
screen?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const BACKOFF_MIN_MS = 500;
|
const BACKOFF_MIN_MS = 500;
|
||||||
@@ -72,6 +79,7 @@ export class Attachment {
|
|||||||
readonly sink: TerminalSink,
|
readonly sink: TerminalSink,
|
||||||
cols: number,
|
cols: number,
|
||||||
rows: number,
|
rows: number,
|
||||||
|
readonly screen = true,
|
||||||
) {
|
) {
|
||||||
this.cols = cols;
|
this.cols = cols;
|
||||||
this.rows = rows;
|
this.rows = rows;
|
||||||
@@ -172,7 +180,7 @@ export class WsClient {
|
|||||||
|
|
||||||
/** résout sur le prochain 'attached' corrélé ; rejette si la session est introuvable/terminée */
|
/** résout sur le prochain 'attached' corrélé ; rejette si la session est introuvable/terminée */
|
||||||
attach(opts: AttachOptions): Promise<Attachment> {
|
attach(opts: AttachOptions): Promise<Attachment> {
|
||||||
const att = new Attachment(this, opts.sessionId, opts.mode, opts.sink, opts.cols, opts.rows);
|
const att = new Attachment(this, opts.sessionId, opts.mode, opts.sink, opts.cols, opts.rows, opts.screen ?? true);
|
||||||
const promise = new Promise<Attachment>((resolve, reject) => {
|
const promise = new Promise<Attachment>((resolve, reject) => {
|
||||||
att.pending = { resolve, reject };
|
att.pending = { resolve, reject };
|
||||||
});
|
});
|
||||||
@@ -343,7 +351,7 @@ export class WsClient {
|
|||||||
|
|
||||||
private sendAttach(att: Attachment): void {
|
private sendAttach(att: Attachment): void {
|
||||||
this.awaitingAttached.push(att);
|
this.awaitingAttached.push(att);
|
||||||
this.sendControl({ type: 'attach', sessionId: att.sessionId, mode: att.mode, cols: att.cols, rows: att.rows });
|
this.sendControl({ type: 'attach', sessionId: att.sessionId, mode: att.mode, cols: att.cols, rows: att.rows, screen: att.screen });
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleMessage(ev: MessageEvent): void {
|
private handleMessage(ev: MessageEvent): void {
|
||||||
@@ -531,6 +539,8 @@ export class WsClient {
|
|||||||
case 'error': {
|
case 'error': {
|
||||||
if (msg.channel !== undefined) {
|
if (msg.channel !== undefined) {
|
||||||
console.warn(`[ws] channel ${msg.channel}: ${msg.code}: ${msg.message}`);
|
console.warn(`[ws] channel ${msg.channel}: ${msg.code}: ${msg.message}`);
|
||||||
|
// Remonté au terminal concerné : une frappe refusée doit se voir, pas seulement en console.
|
||||||
|
this.byChannel.get(msg.channel)?.sink.onChannelError?.(msg.code, msg.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// un échec d'attach est la seule erreur sans canal corrélable à une requête
|
// un échec d'attach est la seule erreur sans canal corrélable à une requête
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { defineStore } from 'pinia';
|
||||||
|
import { ref } from 'vue';
|
||||||
|
import type { FileChange } from '@arboretum/shared';
|
||||||
|
import { gitApi } from '../lib/git-api';
|
||||||
|
import { useWorktreesStore } from './worktrees';
|
||||||
|
import { wtKey } from './ide';
|
||||||
|
|
||||||
|
// Cache des listes de fichiers modifiés, par worktree. Le protocole ne diffuse JAMAIS de
|
||||||
|
// FileChange[] en WS (REST uniquement) et aucun store ne les gardait : chaque composant refetchait
|
||||||
|
// pour lui-même, et la liste mourait avec lui. Une vue qui affiche N dépôts a besoin de l'inverse :
|
||||||
|
// un cache partagé, invalidé par le jeton `worktrees.changeVersion` (incrémenté à chaque
|
||||||
|
// `worktree_changes`), et une politique de charge explicite.
|
||||||
|
//
|
||||||
|
// Politique d'erreur de cette surface : une erreur de CHARGEMENT reste en place avec un
|
||||||
|
// « Réessayer » (jamais avalée en silence, ce que faisait l'ancien panneau Git) ; une erreur de
|
||||||
|
// MUTATION s'affiche dans le panneau qui l'a déclenchée (CommitPanel) ; une action lancée hors
|
||||||
|
// panneau (menu contextuel, palette) passe par un toast.
|
||||||
|
|
||||||
|
export interface ChangesEntry {
|
||||||
|
changes: FileChange[];
|
||||||
|
truncated: boolean;
|
||||||
|
/** Valeur de changeVersion au DÉBUT du chargement : un worktree_changes en vol repérime l'entrée. */
|
||||||
|
version: number;
|
||||||
|
loading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chargements simultanés autorisés. Un dépliage massif ne doit pas ouvrir N requêtes `changes` (donc
|
||||||
|
* N `git status` côté daemon) d'un coup : les demandes sont mises en file et dépilées par paquets.
|
||||||
|
*/
|
||||||
|
export const MAX_CONCURRENT_LOADS = 3;
|
||||||
|
|
||||||
|
interface Pending {
|
||||||
|
repoId: string;
|
||||||
|
wtPath: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useChangesStore = defineStore('changes', () => {
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const entries = ref<Record<string, ChangesEntry>>({});
|
||||||
|
// File d'attente et compteur non réactifs : détails d'ordonnancement, pas de l'état de vue.
|
||||||
|
const queue: Pending[] = [];
|
||||||
|
let running = 0;
|
||||||
|
|
||||||
|
function entry(repoId: string, wtPath: string): ChangesEntry | null {
|
||||||
|
return entries.value[wtKey(repoId, wtPath)] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entrée absente, en erreur, ou plus ancienne que le jeton du worktree. */
|
||||||
|
function isStale(repoId: string, wtPath: string): boolean {
|
||||||
|
const e = entries.value[wtKey(repoId, wtPath)];
|
||||||
|
if (!e) return true;
|
||||||
|
return !e.loading && (e.error !== null || e.version < worktrees.changeVersion(repoId, wtPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
function patch(key: string, next: Partial<ChangesEntry>): void {
|
||||||
|
const prev = entries.value[key] ?? { changes: [], truncated: false, version: -1, loading: false, error: null };
|
||||||
|
entries.value = { ...entries.value, [key]: { ...prev, ...next } };
|
||||||
|
}
|
||||||
|
|
||||||
|
function pump(): void {
|
||||||
|
while (running < MAX_CONCURRENT_LOADS) {
|
||||||
|
const next = queue.shift();
|
||||||
|
if (!next) return;
|
||||||
|
running++;
|
||||||
|
void load(next).finally(() => {
|
||||||
|
running--;
|
||||||
|
pump();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function load({ repoId, wtPath }: Pending): Promise<void> {
|
||||||
|
const key = wtKey(repoId, wtPath);
|
||||||
|
const version = worktrees.changeVersion(repoId, wtPath);
|
||||||
|
patch(key, { loading: true, error: null });
|
||||||
|
try {
|
||||||
|
const res = await gitApi.changes(repoId, wtPath);
|
||||||
|
patch(key, { changes: res.changes, truncated: res.truncated, version, loading: false, error: null });
|
||||||
|
} catch (err) {
|
||||||
|
// On conserve la liste précédente : un écran qui se vide est moins lisible qu'une liste
|
||||||
|
// périmée surmontée d'un message.
|
||||||
|
patch(key, { loading: false, error: err instanceof Error ? err.message : String(err) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Demande (idempotente) le chargement si l'entrée est absente ou périmée. */
|
||||||
|
function request(repoId: string, wtPath: string): void {
|
||||||
|
if (!isStale(repoId, wtPath)) return;
|
||||||
|
if (queue.some((q) => q.repoId === repoId && q.wtPath === wtPath)) return;
|
||||||
|
const e = entries.value[wtKey(repoId, wtPath)];
|
||||||
|
if (e?.loading) return;
|
||||||
|
queue.push({ repoId, wtPath });
|
||||||
|
pump();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Force le rechargement (après une mutation locale) sans vider l'affichage courant. */
|
||||||
|
function invalidate(repoId: string, wtPath: string): void {
|
||||||
|
const key = wtKey(repoId, wtPath);
|
||||||
|
if (entries.value[key]) patch(key, { version: -1 });
|
||||||
|
request(repoId, wtPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reconnexion WS : le protocole ne rejoue rien, donc toute liste chargée avant est suspecte. */
|
||||||
|
function invalidateAll(): void {
|
||||||
|
const stale: Record<string, ChangesEntry> = {};
|
||||||
|
for (const [key, e] of Object.entries(entries.value)) stale[key] = { ...e, version: -1 };
|
||||||
|
entries.value = stale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bloc replié : on libère (bornage mémoire sur un parc de dépôts important). */
|
||||||
|
function forget(repoId: string, wtPath: string): void {
|
||||||
|
const key = wtKey(repoId, wtPath);
|
||||||
|
if (!entries.value[key]) return;
|
||||||
|
const next = { ...entries.value };
|
||||||
|
delete next[key];
|
||||||
|
entries.value = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
function reset(): void {
|
||||||
|
entries.value = {};
|
||||||
|
queue.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { entries, entry, isStale, request, invalidate, invalidateAll, forget, reset };
|
||||||
|
});
|
||||||
+202
-32
@@ -1,6 +1,23 @@
|
|||||||
import { defineStore } from 'pinia';
|
import { defineStore } from 'pinia';
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { persistedRef } from '../lib/persisted-ref';
|
import { forgetPersisted, persistedRef, readPersisted } from '../lib/persisted-ref';
|
||||||
|
import {
|
||||||
|
activeColumnOf,
|
||||||
|
addPane,
|
||||||
|
closePane,
|
||||||
|
DOCK_MIN_HEIGHT,
|
||||||
|
dockMaxHeight,
|
||||||
|
focusColumn,
|
||||||
|
focusPane,
|
||||||
|
MAX_DOCK_COLUMNS,
|
||||||
|
mergeColumns,
|
||||||
|
migrateDock,
|
||||||
|
movePane,
|
||||||
|
prunePanes,
|
||||||
|
setSplit,
|
||||||
|
type DockColumn,
|
||||||
|
type DockState,
|
||||||
|
} from '../lib/dock-model';
|
||||||
|
|
||||||
// Store d'état « IDE » : onglets éditeur, terminaux du dock, panneaux, arbre.
|
// Store d'état « IDE » : onglets éditeur, terminaux du dock, panneaux, arbre.
|
||||||
// Ne stocke QUE des références (ids / chemins) et de l'état de vue, jamais de copie de
|
// Ne stocke QUE des références (ids / chemins) et de l'état de vue, jamais de copie de
|
||||||
@@ -14,6 +31,16 @@ import { persistedRef } from '../lib/persisted-ref';
|
|||||||
|
|
||||||
export type ActivityView = 'explorer' | 'git' | 'sessions' | 'groups';
|
export type ActivityView = 'explorer' | 'git' | 'sessions' | 'groups';
|
||||||
export type EditorView = 'editor' | 'diff';
|
export type EditorView = 'editor' | 'diff';
|
||||||
|
/** Mode de la zone centrale : lecture/édition de fichiers, ou changements non commités par projet. */
|
||||||
|
export type CenterMode = 'files' | 'changes';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Panneaux du layout mobile (sous md, IdeShell n'affiche qu'un panneau, choisi par `mobilePanel`).
|
||||||
|
* Liste blanche : une valeur inconnue laissait l'utilisateur sur un panneau fantôme. Doit rester
|
||||||
|
* alignée sur la chaîne de rendu et la nav de `components/ide/IdeShell.vue`.
|
||||||
|
*/
|
||||||
|
export const MOBILE_PANELS = ['explorer', 'editor', 'changes', 'terminal', 'sessions', 'groups'] as const;
|
||||||
|
export type MobilePanel = (typeof MOBILE_PANELS)[number];
|
||||||
|
|
||||||
export interface EditorTab {
|
export interface EditorTab {
|
||||||
/** Clé composite stable : repoId + wtPath + fichier relatif. */
|
/** Clé composite stable : repoId + wtPath + fichier relatif. */
|
||||||
@@ -38,13 +65,21 @@ export function tabId(repoId: string, wtPath: string, file: string): string {
|
|||||||
export function wtKey(repoId: string, wtPath: string): string {
|
export function wtKey(repoId: string, wtPath: string): string {
|
||||||
return `${repoId}${SEP}${wtPath}`;
|
return `${repoId}${SEP}${wtPath}`;
|
||||||
}
|
}
|
||||||
|
/** Inverse de `wtKey` : les consommateurs d'un ensemble de clés (useWatchedWorktrees) en ont besoin. */
|
||||||
|
export function parseWtKey(key: string): WorktreeRef | null {
|
||||||
|
const i = key.indexOf(SEP);
|
||||||
|
if (i <= 0 || i === key.length - 1) return null;
|
||||||
|
return { repoId: key.slice(0, i), wtPath: key.slice(i + 1) };
|
||||||
|
}
|
||||||
|
|
||||||
export const useIdeStore = defineStore('ide', () => {
|
export const useIdeStore = defineStore('ide', () => {
|
||||||
// --- état persisté (références + vue) ---
|
// --- état persisté (références + vue) ---
|
||||||
const editorTabs = persistedRef<EditorTab[]>('arb.ide.tabs', []);
|
const editorTabs = persistedRef<EditorTab[]>('arb.ide.tabs', []);
|
||||||
const activeTabId = persistedRef<string | null>('arb.ide.activeTab', null);
|
const activeTabId = persistedRef<string | null>('arb.ide.activeTab', null);
|
||||||
const dockSessionIds = persistedRef<string[]>('arb.ide.dock', []);
|
// Dock terminaux : des COLONNES d'onglets, pas une liste plate (plusieurs terminaux visibles côte
|
||||||
const activeDockSessionId = persistedRef<string | null>('arb.ide.activeDock', null);
|
// à côte). L'algèbre vit dans lib/dock-model.ts ; ici on ne fait qu'orchestrer et persister.
|
||||||
|
const dockColumns = persistedRef<DockColumn[]>('arb.ide.dockColumns', []);
|
||||||
|
const activeDockColumnId = persistedRef<string | null>('arb.ide.dockColumn', null);
|
||||||
const activeActivity = persistedRef<ActivityView>('arb.ide.activity', 'explorer');
|
const activeActivity = persistedRef<ActivityView>('arb.ide.activity', 'explorer');
|
||||||
const activeContext = persistedRef<WorktreeRef | null>('arb.ide.context', null);
|
const activeContext = persistedRef<WorktreeRef | null>('arb.ide.context', null);
|
||||||
|
|
||||||
@@ -58,10 +93,52 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
const expandedGroupIds = persistedRef<string[]>('arb.ide.expandedGroups', []);
|
const expandedGroupIds = persistedRef<string[]>('arb.ide.expandedGroups', []);
|
||||||
const mobilePanel = persistedRef<string>('arb.ide.mobilePanel', 'explorer');
|
const mobilePanel = persistedRef<string>('arb.ide.mobilePanel', 'explorer');
|
||||||
|
|
||||||
|
const centerMode = persistedRef<CenterMode>('arb.ide.centerMode', 'files');
|
||||||
|
/** Blocs dépliés de la vue Changements, en clés `wtKey`. Réassigné (persistedRef non profond). */
|
||||||
|
const changesExpanded = persistedRef<string[]>('arb.ide.changesExpanded', []);
|
||||||
|
/** Afficher aussi les worktrees propres et à jour (bruit par défaut, utile pour un audit). */
|
||||||
|
const changesShowClean = persistedRef<boolean>('arb.ide.changesShowClean', false);
|
||||||
|
/**
|
||||||
|
* Portée de la vue Changements : suivre le terminal focalisé (défaut) ou tout voir. Seule la
|
||||||
|
* PRÉFÉRENCE est persistée : la portée effective est résolue contre les données live par
|
||||||
|
* `composables/useContextScope` (le store ne connaît ni les cwd ni les groupes). Persister la
|
||||||
|
* portée elle-même désignerait tôt ou tard un groupe ou un worktree disparu.
|
||||||
|
*/
|
||||||
|
const changesScope = persistedRef<'follow' | 'all'>('arb.ide.changesScope', 'follow');
|
||||||
|
|
||||||
|
// Migration des valeurs de `mobilePanel` devenues invalides. `setActivity` posait 'sidebar', que
|
||||||
|
// le layout mobile ne savait pas rendre (il retombait sur la zone centrale, sans que le bon
|
||||||
|
// bouton de nav ne s'allume) ; et le panneau 'git' est désormais l'index de la sidebar desktop,
|
||||||
|
// son rôle mobile étant tenu par la vue Changements.
|
||||||
|
if (mobilePanel.value === 'git') mobilePanel.value = 'changes';
|
||||||
|
else if (!MOBILE_PANELS.includes(mobilePanel.value as MobilePanel)) mobilePanel.value = 'explorer';
|
||||||
|
|
||||||
|
// Migration silencieuse de l'ancien dock mono-colonne (`arb.ide.dock` / `arb.ide.activeDock`, déjà
|
||||||
|
// en localStorage chez les utilisateurs) : une colonne unique, ordre et onglet actif conservés. Les
|
||||||
|
// anciennes clés sont ensuite OUBLIÉES, sinon un onglet resté ouvert sur la version précédente les
|
||||||
|
// réécrirait et la migration rejouerait au démarrage suivant, écrasant l'état neuf.
|
||||||
|
if (dockColumns.value.length === 0) {
|
||||||
|
const legacy = readPersisted<string[]>('arb.ide.dock', []);
|
||||||
|
if (legacy.length > 0) applyDock(migrateDock(legacy, readPersisted<string | null>('arb.ide.activeDock', null)));
|
||||||
|
}
|
||||||
|
forgetPersisted('arb.ide.dock');
|
||||||
|
forgetPersisted('arb.ide.activeDock');
|
||||||
|
|
||||||
// --- état volatile ---
|
// --- état volatile ---
|
||||||
const dirty = ref<Record<string, boolean>>({}); // id d'onglet -> modifié non sauvegardé
|
const dirty = ref<Record<string, boolean>>({}); // id d'onglet -> modifié non sauvegardé
|
||||||
|
|
||||||
// --- getters ---
|
// --- getters ---
|
||||||
|
// `dockSessionIds` / `activeDockSessionId` restent l'API publique du dock (barre de statut, arbre,
|
||||||
|
// panneaux, rendu mobile) : ils sont désormais DÉRIVÉS des colonnes. Aucun code externe ne les
|
||||||
|
// écrit, donc le passage aux colonnes ne casse aucun consommateur.
|
||||||
|
const activeDockColumn = computed(() => activeColumnOf({ columns: dockColumns.value, activeColumnId: activeDockColumnId.value }));
|
||||||
|
const dockSessionIds = computed<string[]>(() => dockColumns.value.flatMap((c) => c.sessionIds));
|
||||||
|
/** Onglet visible de CHAQUE colonne : les terminaux réellement à l'écran (portée git, watchers FS). */
|
||||||
|
const visibleDockSessionIds = computed<string[]>(() => dockColumns.value.map((c) => c.activeSessionId));
|
||||||
|
/** Terminal focalisé = onglet visible de la colonne active. */
|
||||||
|
const activeDockSessionId = computed<string | null>(() => activeDockColumn.value?.activeSessionId ?? null);
|
||||||
|
const canSplitTerminal = computed(() => dockColumns.value.length > 0 && dockColumns.value.length < MAX_DOCK_COLUMNS);
|
||||||
|
|
||||||
const activeTab = computed(() => editorTabs.value.find((t) => t.id === activeTabId.value) ?? null);
|
const activeTab = computed(() => editorTabs.value.find((t) => t.id === activeTabId.value) ?? null);
|
||||||
const tabsCount = computed(() => editorTabs.value.length);
|
const tabsCount = computed(() => editorTabs.value.length);
|
||||||
const hasUnsaved = computed(() => Object.values(dirty.value).some(Boolean));
|
const hasUnsaved = computed(() => Object.values(dirty.value).some(Boolean));
|
||||||
@@ -74,6 +151,9 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- actions onglets ---
|
// --- actions onglets ---
|
||||||
|
// `setCenterMode('files')` n'est pas décoratif : sans lui, ouvrir un fichier depuis la vue
|
||||||
|
// Changements n'aurait AUCUN effet visible (l'éditeur est masqué), et sur mobile le layout
|
||||||
|
// resterait sur l'explorateur (cf. openTerminal, même piège).
|
||||||
function openFile(repoId: string, wtPath: string, file: string, view: EditorView = 'editor'): void {
|
function openFile(repoId: string, wtPath: string, file: string, view: EditorView = 'editor'): void {
|
||||||
const id = tabId(repoId, wtPath, file);
|
const id = tabId(repoId, wtPath, file);
|
||||||
const existing = editorTabs.value.find((t) => t.id === id);
|
const existing = editorTabs.value.find((t) => t.id === id);
|
||||||
@@ -84,6 +164,7 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
}
|
}
|
||||||
activeTabId.value = id;
|
activeTabId.value = id;
|
||||||
activeContext.value = { repoId, wtPath };
|
activeContext.value = { repoId, wtPath };
|
||||||
|
setCenterMode('files');
|
||||||
}
|
}
|
||||||
|
|
||||||
function setTabView(id: string, view: EditorView, diffStaged?: boolean): void {
|
function setTabView(id: string, view: EditorView, diffStaged?: boolean): void {
|
||||||
@@ -98,6 +179,7 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
if (!tab) return;
|
if (!tab) return;
|
||||||
activeTabId.value = id;
|
activeTabId.value = id;
|
||||||
activeContext.value = { repoId: tab.repoId, wtPath: tab.wtPath };
|
activeContext.value = { repoId: tab.repoId, wtPath: tab.wtPath };
|
||||||
|
setCenterMode('files');
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeTab(id: string): void {
|
function closeTab(id: string): void {
|
||||||
@@ -142,38 +224,108 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
// rend une ressource « active » doit donc aussi amener le bon panneau au premier plan. Sans ça,
|
// rend une ressource « active » doit donc aussi amener le bon panneau au premier plan. Sans ça,
|
||||||
// ouvrir un terminal depuis l'arbre, un panneau, la palette ou un modal ne produisait AUCUN effet
|
// ouvrir un terminal depuis l'arbre, un panneau, la palette ou un modal ne produisait AUCUN effet
|
||||||
// visible sur mobile. On centralise ici plutôt que dans les ~10 points d'appel.
|
// visible sur mobile. On centralise ici plutôt que dans les ~10 points d'appel.
|
||||||
function openTerminal(sessionId: string): void {
|
|
||||||
if (!dockSessionIds.value.includes(sessionId)) {
|
/** Vue lecture de l'état du dock, telle que l'attend l'algèbre pure. */
|
||||||
dockSessionIds.value = [...dockSessionIds.value, sessionId];
|
function dockState(): DockState {
|
||||||
|
return { columns: dockColumns.value, activeColumnId: activeDockColumnId.value };
|
||||||
}
|
}
|
||||||
activeDockSessionId.value = sessionId;
|
/** Écriture (réassignation immuable : persistedRef n'observe pas en profondeur). */
|
||||||
|
function applyDock(next: DockState): void {
|
||||||
|
if (next.columns !== dockColumns.value) dockColumns.value = next.columns;
|
||||||
|
if (next.activeColumnId !== activeDockColumnId.value) activeDockColumnId.value = next.activeColumnId;
|
||||||
|
}
|
||||||
|
/** Le dock doit être visible ET au premier plan sur mobile dès qu'on y met quelque chose. */
|
||||||
|
function revealDock(): void {
|
||||||
bottomVisible.value = true;
|
bottomVisible.value = true;
|
||||||
mobilePanel.value = 'terminal';
|
mobilePanel.value = 'terminal';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** `split` : ouvre le terminal dans une NOUVELLE colonne à côté, au lieu d'un onglet de plus. */
|
||||||
|
function openTerminal(sessionId: string, opts?: { split?: boolean }): void {
|
||||||
|
applyDock(addPane(dockState(), sessionId, opts?.split ? 'split' : 'tab'));
|
||||||
|
revealDock();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Détache un pane déjà ouvert dans sa propre colonne (par défaut, celui qui est focalisé). */
|
||||||
|
function splitTerminal(sessionId?: string): void {
|
||||||
|
const target = sessionId ?? activeDockSessionId.value;
|
||||||
|
if (!target) return;
|
||||||
|
applyDock(movePane(dockState(), target, { split: true }));
|
||||||
|
revealDock();
|
||||||
|
}
|
||||||
|
|
||||||
|
function moveTerminal(sessionId: string, target: { columnId: string } | { split: true }): void {
|
||||||
|
applyDock(movePane(dockState(), sessionId, target));
|
||||||
|
revealDock();
|
||||||
|
}
|
||||||
|
|
||||||
function focusTerminal(sessionId: string): void {
|
function focusTerminal(sessionId: string): void {
|
||||||
if (!dockSessionIds.value.includes(sessionId)) return;
|
const next = focusPane(dockState(), sessionId);
|
||||||
activeDockSessionId.value = sessionId;
|
if (next === dockState() && !dockColumns.value.some((c) => c.sessionIds.includes(sessionId))) return;
|
||||||
bottomVisible.value = true;
|
applyDock(next);
|
||||||
mobilePanel.value = 'terminal';
|
revealDock();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rend une colonne active : c'est elle qui reçoit la frappe et qui définit le contexte de travail. */
|
||||||
|
function focusDockColumn(columnId: string): void {
|
||||||
|
applyDock(focusColumn(dockState(), columnId));
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeTerminal(sessionId: string): void {
|
function closeTerminal(sessionId: string): void {
|
||||||
const idx = dockSessionIds.value.indexOf(sessionId);
|
const next = closePane(dockState(), sessionId);
|
||||||
if (idx < 0) return;
|
applyDock(next);
|
||||||
const next = dockSessionIds.value.filter((s) => s !== sessionId);
|
if (next.columns.length === 0) bottomVisible.value = false;
|
||||||
dockSessionIds.value = next;
|
|
||||||
if (activeDockSessionId.value === sessionId) {
|
|
||||||
activeDockSessionId.value = next[idx] ?? next[idx - 1] ?? null;
|
|
||||||
}
|
}
|
||||||
if (next.length === 0) bottomVisible.value = false;
|
|
||||||
|
/** Déplace la frontière entre les colonnes `index` et `index+1` (part visée par la gauche). */
|
||||||
|
function setDockColumnSplit(index: number, ratioOfTrack: number): void {
|
||||||
|
applyDock(setSplit(dockState(), index, ratioOfTrack));
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeDockColumns(): void {
|
||||||
|
applyDock(mergeColumns(dockState()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- actions zone centrale ---
|
||||||
|
/**
|
||||||
|
* Bascule le mode de la zone centrale. SEUL écrivain de `mobilePanel` pour ces deux modes : les
|
||||||
|
* deux états ne peuvent donc pas diverger (cf. openTerminal, le layout mobile suit `mobilePanel`).
|
||||||
|
*/
|
||||||
|
function setCenterMode(mode: CenterMode): void {
|
||||||
|
centerMode.value = mode;
|
||||||
|
mobilePanel.value = mode === 'changes' ? 'changes' : 'editor';
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleChangesWt(key: string): void {
|
||||||
|
changesExpanded.value = changesExpanded.value.includes(key)
|
||||||
|
? changesExpanded.value.filter((k) => k !== key)
|
||||||
|
: [...changesExpanded.value, key];
|
||||||
|
}
|
||||||
|
function setChangesExpanded(keys: string[]): void {
|
||||||
|
changesExpanded.value = [...keys];
|
||||||
|
}
|
||||||
|
function toggleChangesScope(): void {
|
||||||
|
changesScope.value = changesScope.value === 'all' ? 'follow' : 'all';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rend un worktree actif, déplie son bloc et amène la vue Changements au premier plan. */
|
||||||
|
function openChanges(repoId: string, wtPath: string): void {
|
||||||
|
activeContext.value = { repoId, wtPath };
|
||||||
|
const key = wtKey(repoId, wtPath);
|
||||||
|
if (!changesExpanded.value.includes(key)) changesExpanded.value = [...changesExpanded.value, key];
|
||||||
|
setCenterMode('changes');
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- actions panneaux / activité ---
|
// --- actions panneaux / activité ---
|
||||||
|
// Les 4 vues d'activité sont aussi des panneaux mobiles, à une exception : 'git' est l'index de la
|
||||||
|
// sidebar desktop, dont le rôle mobile est tenu par la vue Changements de la zone centrale.
|
||||||
|
const mobilePanelForActivity = (view: ActivityView): MobilePanel => (view === 'git' ? 'changes' : view);
|
||||||
|
|
||||||
function setActivity(view: ActivityView): void {
|
function setActivity(view: ActivityView): void {
|
||||||
activeActivity.value = view;
|
activeActivity.value = view;
|
||||||
leftVisible.value = true;
|
leftVisible.value = true;
|
||||||
mobilePanel.value = 'sidebar'; // cf. openTerminal : le layout mobile suit mobilePanel
|
if (view === 'git') centerMode.value = 'changes';
|
||||||
|
mobilePanel.value = mobilePanelForActivity(view);
|
||||||
}
|
}
|
||||||
function toggleActivity(view: ActivityView): void {
|
function toggleActivity(view: ActivityView): void {
|
||||||
// Re-clic sur la vue active alors que le panneau est ouvert : on replie le panneau gauche.
|
// Re-clic sur la vue active alors que le panneau est ouvert : on replie le panneau gauche.
|
||||||
@@ -183,7 +335,8 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
}
|
}
|
||||||
activeActivity.value = view;
|
activeActivity.value = view;
|
||||||
leftVisible.value = true;
|
leftVisible.value = true;
|
||||||
mobilePanel.value = 'sidebar';
|
if (view === 'git') centerMode.value = 'changes';
|
||||||
|
mobilePanel.value = mobilePanelForActivity(view);
|
||||||
}
|
}
|
||||||
function setActiveWorktree(repoId: string, wtPath: string): void {
|
function setActiveWorktree(repoId: string, wtPath: string): void {
|
||||||
activeContext.value = { repoId, wtPath };
|
activeContext.value = { repoId, wtPath };
|
||||||
@@ -227,9 +380,10 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
function clampToViewport(width: number, height: number): void {
|
function clampToViewport(width: number, height: number): void {
|
||||||
const maxLeft = Math.max(200, Math.min(560, Math.round(width * 0.5)));
|
const maxLeft = Math.max(200, Math.min(560, Math.round(width * 0.5)));
|
||||||
if (leftWidth.value > maxLeft) leftWidth.value = maxLeft;
|
if (leftWidth.value > maxLeft) leftWidth.value = maxLeft;
|
||||||
// on garde toujours de la place pour la zone centrale et la barre de statut.
|
// Bornes du dock : une seule source (lib/dock-model), partagée avec le splitter du template.
|
||||||
const maxBottom = Math.max(120, Math.min(640, height - 200));
|
const maxBottom = dockMaxHeight(height);
|
||||||
if (bottomHeight.value > maxBottom) bottomHeight.value = maxBottom;
|
if (bottomHeight.value > maxBottom) bottomHeight.value = maxBottom;
|
||||||
|
if (bottomHeight.value < DOCK_MIN_HEIGHT) bottomHeight.value = DOCK_MIN_HEIGHT;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -249,22 +403,19 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
activeTabId.value = keptTabs[keptTabs.length - 1]?.id ?? null;
|
activeTabId.value = keptTabs[keptTabs.length - 1]?.id ?? null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const keptDock = dockSessionIds.value.filter((s) => liveSessionIds.has(s));
|
// Le modèle maintient ses invariants (colonne vidée supprimée, onglet visible réparé, ratios
|
||||||
if (keptDock.length !== dockSessionIds.value.length) {
|
// renormalisés) et rend l'état d'origine quand rien n'a bougé : pas d'écriture inutile.
|
||||||
dockSessionIds.value = keptDock;
|
const prunedDock = prunePanes(dockState(), liveSessionIds);
|
||||||
if (activeDockSessionId.value && !keptDock.includes(activeDockSessionId.value)) {
|
applyDock(prunedDock);
|
||||||
activeDockSessionId.value = keptDock[keptDock.length - 1] ?? null;
|
if (prunedDock.columns.length === 0) bottomVisible.value = false;
|
||||||
}
|
|
||||||
if (keptDock.length === 0) bottomVisible.value = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
// état
|
// état
|
||||||
editorTabs,
|
editorTabs,
|
||||||
activeTabId,
|
activeTabId,
|
||||||
dockSessionIds,
|
dockColumns,
|
||||||
activeDockSessionId,
|
activeDockColumnId,
|
||||||
activeActivity,
|
activeActivity,
|
||||||
activeContext,
|
activeContext,
|
||||||
leftWidth,
|
leftWidth,
|
||||||
@@ -275,7 +426,16 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
expandedWtPaths,
|
expandedWtPaths,
|
||||||
expandedGroupIds,
|
expandedGroupIds,
|
||||||
mobilePanel,
|
mobilePanel,
|
||||||
|
centerMode,
|
||||||
|
changesExpanded,
|
||||||
|
changesShowClean,
|
||||||
|
changesScope,
|
||||||
// getters
|
// getters
|
||||||
|
dockSessionIds,
|
||||||
|
visibleDockSessionIds,
|
||||||
|
activeDockSessionId,
|
||||||
|
activeDockColumn,
|
||||||
|
canSplitTerminal,
|
||||||
activeTab,
|
activeTab,
|
||||||
tabsCount,
|
tabsCount,
|
||||||
hasUnsaved,
|
hasUnsaved,
|
||||||
@@ -289,8 +449,18 @@ export const useIdeStore = defineStore('ide', () => {
|
|||||||
moveTab,
|
moveTab,
|
||||||
setTabDirty,
|
setTabDirty,
|
||||||
openTerminal,
|
openTerminal,
|
||||||
|
splitTerminal,
|
||||||
|
moveTerminal,
|
||||||
focusTerminal,
|
focusTerminal,
|
||||||
|
focusDockColumn,
|
||||||
closeTerminal,
|
closeTerminal,
|
||||||
|
setDockColumnSplit,
|
||||||
|
mergeDockColumns,
|
||||||
|
setCenterMode,
|
||||||
|
toggleChangesWt,
|
||||||
|
setChangesExpanded,
|
||||||
|
toggleChangesScope,
|
||||||
|
openChanges,
|
||||||
setActivity,
|
setActivity,
|
||||||
toggleActivity,
|
toggleActivity,
|
||||||
setActiveWorktree,
|
setActiveWorktree,
|
||||||
|
|||||||
@@ -7,6 +7,10 @@ import { wsClient, type SessionEvent } from '../lib/ws-client';
|
|||||||
export const useSessionsStore = defineStore('sessions', () => {
|
export const useSessionsStore = defineStore('sessions', () => {
|
||||||
const sessions = ref<SessionSummary[]>([]);
|
const sessions = ref<SessionSummary[]>([]);
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
|
// true dès que la PREMIÈRE liste est revenue (succès ou échec). Un consommateur qui attache un
|
||||||
|
// terminal doit l'attendre : sur une liste encore vide, il déduirait « session non attachable »
|
||||||
|
// et s'attacherait en observateur, à vie et sans le savoir (frappe refusée, écran muet).
|
||||||
|
const loaded = ref(false);
|
||||||
const loadError = ref<string | null>(null);
|
const loadError = ref<string | null>(null);
|
||||||
// false (défaut) : les sessions masquées sont exclues ; true : on les inclut (mode « afficher les masquées »).
|
// false (défaut) : les sessions masquées sont exclues ; true : on les inclut (mode « afficher les masquées »).
|
||||||
const showHidden = ref(false);
|
const showHidden = ref(false);
|
||||||
@@ -85,6 +89,7 @@ export const useSessionsStore = defineStore('sessions', () => {
|
|||||||
loadError.value = err instanceof Error ? err.message : String(err);
|
loadError.value = err instanceof Error ? err.message : String(err);
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
|
loaded.value = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,6 +194,7 @@ export const useSessionsStore = defineStore('sessions', () => {
|
|||||||
return {
|
return {
|
||||||
sessions,
|
sessions,
|
||||||
loading,
|
loading,
|
||||||
|
loaded,
|
||||||
loadError,
|
loadError,
|
||||||
showHidden,
|
showHidden,
|
||||||
showArchived,
|
showArchived,
|
||||||
|
|||||||
@@ -180,13 +180,6 @@ export const useWorktreesStore = defineStore('worktrees', () => {
|
|||||||
return api.get<RepoBranchesResponse>(`/api/v1/repos/${repoId}/branches`);
|
return api.get<RepoBranchesResponse>(`/api/v1/repos/${repoId}/branches`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Commit (add -A + commit) dans un worktree ; le worktree mis à jour arrive aussi par WS. */
|
|
||||||
async function commitWorktree(repoId: string, path: string, message: string): Promise<WorktreeSummary> {
|
|
||||||
const res = await api.post<WorktreeResponse>(`/api/v1/repos/${repoId}/worktrees/commit`, { path, message });
|
|
||||||
upsertWorktree(res.worktree);
|
|
||||||
return res.worktree;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Push de la branche d'un worktree (upstream auto si absent). */
|
/** Push de la branche d'un worktree (upstream auto si absent). */
|
||||||
async function pushWorktree(repoId: string, path: string): Promise<WorktreeSummary> {
|
async function pushWorktree(repoId: string, path: string): Promise<WorktreeSummary> {
|
||||||
const res = await api.post<WorktreeResponse>(`/api/v1/repos/${repoId}/worktrees/push`, { path });
|
const res = await api.post<WorktreeResponse>(`/api/v1/repos/${repoId}/worktrees/push`, { path });
|
||||||
@@ -232,7 +225,6 @@ export const useWorktreesStore = defineStore('worktrees', () => {
|
|||||||
deleteWorktree,
|
deleteWorktree,
|
||||||
prune,
|
prune,
|
||||||
fetchBranches,
|
fetchBranches,
|
||||||
commitWorktree,
|
|
||||||
pushWorktree,
|
pushWorktree,
|
||||||
promoteWorktree,
|
promoteWorktree,
|
||||||
startRealtime,
|
startRealtime,
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ const en: HelpSection[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'The IDE layout',
|
title: 'The IDE layout',
|
||||||
body: 'Everything lives in one window: the activity bar on the left switches between Explorer, Git, Sessions and Groups; the centre holds editor tabs; the bottom dock holds terminals. Drag the separators to resize, or focus them and use the arrow keys.',
|
body: 'Everything lives in one window: the activity bar on the left switches between Explorer, Git, Sessions and Groups; the centre holds editor tabs; the bottom dock holds terminals. Drag the separators to resize, or focus them and use the arrow keys. The two buttons on the right of the tab bar switch the centre between Files and Changes.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Remote access',
|
title: 'Remote access',
|
||||||
@@ -92,19 +92,19 @@ const en: HelpSection[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Diffs',
|
title: 'Diffs',
|
||||||
body: 'The Git panel lists changed files; click one to see its unified diff. Every diff tab switches between Editor and Diff, and refreshes on its own when the file changes on disk.',
|
body: 'Changes is the working surface: one block per worktree, across every open project. Click a changed file to unfold its unified diff right under the list, or send it to a full-width editor tab. Diffs refresh on their own when the file changes on disk. The Git panel in the sidebar is the index: it shows what every project is worth and opens the matching block.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Stage & commit',
|
title: 'Stage & commit',
|
||||||
body: 'Stage or unstage file by file, or all at once, then commit the index only, or everything. Amend rewrites the last commit (refused once pushed). Discard is destructive and asks for a confirmation click.',
|
body: 'Stage or unstage file by file, or all at once, then commit the index. Amend rewrites the last commit, message only if you want (refused once pushed). Discard is destructive and asks for a confirmation click. Every project keeps its own block, so a commit never mixes two repositories.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'History',
|
title: 'History',
|
||||||
body: 'The History section under the Git panel lists the branch commits, marks those not pushed yet, and unfolds the full diff of any commit in place. Its counter answers the question that matters before removing a worktree: is there local work that would be lost?',
|
body: 'Each block carries its own History section, folded until you need it: the branch commits, those not pushed yet, and the full diff of any commit unfolded in place. Its counter answers the question that matters before removing a worktree: is there local work that would be lost?',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Fetch, pull & push',
|
title: 'Fetch, pull & push',
|
||||||
body: 'Fetch and pull (fast-forward only, or rebase) live in the Git panel header. Push publishes the branch and sets its upstream on first push.',
|
body: 'Fetch and pull (fast-forward only, or rebase) live in the header of each block. Push publishes the branch and sets its upstream on first push; it stays greyed out when there is nothing to publish.',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -269,7 +269,7 @@ const fr: HelpSection[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'L’organisation de l’IDE',
|
title: 'L’organisation de l’IDE',
|
||||||
body: 'Tout tient dans une seule fenêtre : la barre d’activité à gauche bascule entre Explorateur, Git, Sessions et Groupes ; le centre porte les onglets d’éditeur ; le dock du bas porte les terminaux. Les séparateurs se déplacent à la souris, ou au clavier avec les flèches une fois focalisés.',
|
body: 'Tout tient dans une seule fenêtre : la barre d’activité à gauche bascule entre Explorateur, Git, Sessions et Groupes ; le centre porte les onglets d’éditeur ; le dock du bas porte les terminaux. Les séparateurs se déplacent à la souris, ou au clavier avec les flèches une fois focalisés. Les deux boutons à droite de la barre d’onglets basculent le centre entre Fichiers et Changements.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Accès distant',
|
title: 'Accès distant',
|
||||||
@@ -331,19 +331,19 @@ const fr: HelpSection[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Diffs',
|
title: 'Diffs',
|
||||||
body: 'Le panneau Git liste les fichiers modifiés ; un clic affiche son diff unifié. Chaque onglet bascule entre Éditeur et Diff, et se rafraîchit seul quand le fichier change sur le disque.',
|
body: 'La vue Changements est la surface de travail : un bloc par worktree, pour tous vos projets ouverts. Un clic sur un fichier modifié déplie son diff unifié juste sous la liste, ou l’envoie dans un onglet pleine largeur. Les diffs se rafraîchissent seuls quand le fichier change sur le disque. Le panneau Git de la barre latérale est l’index : il montre ce que vaut chaque projet et ouvre le bloc correspondant.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Indexer & committer',
|
title: 'Indexer & committer',
|
||||||
body: 'Indexez ou désindexez fichier par fichier, ou tout d’un coup, puis committez l’index seul ou l’ensemble. « Amender » réécrit le dernier commit (refusé s’il est déjà poussé). « Abandonner » est destructif et demande une confirmation.',
|
body: 'Indexez ou désindexez fichier par fichier, ou tout d’un coup, puis committez l’index. « Amender » réécrit le dernier commit, son message seul si vous le souhaitez (refusé s’il est déjà poussé). « Abandonner » est destructif et demande une confirmation. Chaque projet garde son bloc : un commit ne mélange jamais deux dépôts.',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Historique',
|
title: 'Historique',
|
||||||
body: 'La section Historique, sous le panneau Git, liste les commits de la branche, marque ceux qui ne sont pas encore poussés, et déplie sur place le diff complet de n’importe lequel. Son compteur répond à la question qui compte avant de supprimer un worktree : reste-t-il du travail local qui serait perdu ?',
|
body: 'Chaque bloc porte sa propre section Historique, repliée jusqu’à ce que vous en ayez besoin : les commits de la branche, ceux qui ne sont pas encore poussés, et le diff complet de n’importe lequel déplié sur place. Son compteur répond à la question qui compte avant de supprimer un worktree : reste-t-il du travail local qui serait perdu ?',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'Fetch, pull & push',
|
title: 'Fetch, pull & push',
|
||||||
body: 'Fetch et pull (fast-forward seul, ou rebase) sont dans l’en-tête du panneau Git. Push publie la branche et pose son upstream au premier envoi.',
|
body: 'Fetch et pull (fast-forward seul, ou rebase) sont dans l’en-tête de chaque bloc. Push publie la branche et pose son upstream au premier envoi ; il reste grisé quand il n’y a rien à publier.',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,170 @@
|
|||||||
|
// Règles d'affichage de la vue Changements et de l'index Git. Fonctions pures, testées sans DOM.
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { RepoSummary, WorktreeGitStatus, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import {
|
||||||
|
dirtyFileCount,
|
||||||
|
groupWorktreesByRepo,
|
||||||
|
hasPendingWork,
|
||||||
|
pendingWorktreeCount,
|
||||||
|
sortForIndex,
|
||||||
|
} from '../src/lib/changes-model';
|
||||||
|
|
||||||
|
const git = (over: Partial<WorktreeGitStatus> = {}): WorktreeGitStatus => ({
|
||||||
|
ahead: 0,
|
||||||
|
behind: 0,
|
||||||
|
dirtyCount: 0,
|
||||||
|
upstream: 'origin/main',
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
const wt = (path: string, over: Partial<WorktreeSummary> = {}): WorktreeSummary => ({
|
||||||
|
repoId: 'r1',
|
||||||
|
path,
|
||||||
|
branch: path.split('/').pop() ?? null,
|
||||||
|
head: 'abc1234',
|
||||||
|
detached: false,
|
||||||
|
locked: false,
|
||||||
|
prunable: false,
|
||||||
|
isMain: false,
|
||||||
|
git: git(),
|
||||||
|
sessions: [],
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
|
||||||
|
const repo = (id: string, label = id): RepoSummary =>
|
||||||
|
({ id, path: `/repos/${id}`, label, hidden: false, valid: true }) as unknown as RepoSummary;
|
||||||
|
|
||||||
|
describe('hasPendingWork', () => {
|
||||||
|
it('un worktree propre et à jour n a rien à traiter', () => {
|
||||||
|
expect(hasPendingWork(git())).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détecte chaque forme de travail en attente', () => {
|
||||||
|
expect(hasPendingWork(git({ dirtyCount: 2 }))).toBe(true);
|
||||||
|
expect(hasPendingWork(git({ stagedCount: 1 }))).toBe(true);
|
||||||
|
expect(hasPendingWork(git({ unstagedCount: 1 }))).toBe(true);
|
||||||
|
expect(hasPendingWork(git({ conflictCount: 1 }))).toBe(true);
|
||||||
|
expect(hasPendingWork(git({ ahead: 3 }))).toBe(true); // rien à committer mais à pousser
|
||||||
|
});
|
||||||
|
|
||||||
|
it('être en retard ne demande rien de notre côté', () => {
|
||||||
|
expect(hasPendingWork(git({ behind: 5 }))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('les compteurs fins étant optionnels dans le protocole, dirtyCount reste le filet', () => {
|
||||||
|
// Cas d'un daemon plus ancien : ni stagedCount ni unstagedCount, seulement dirtyCount.
|
||||||
|
expect(hasPendingWork({ ahead: 0, behind: 0, dirtyCount: 4, upstream: null })).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('dirtyFileCount', () => {
|
||||||
|
it('prend le maximum entre dirtyCount et la somme des compteurs fins', () => {
|
||||||
|
expect(dirtyFileCount(git({ dirtyCount: 3 }))).toBe(3);
|
||||||
|
expect(dirtyFileCount(git({ dirtyCount: 3, stagedCount: 2, unstagedCount: 2 }))).toBe(4);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('groupWorktreesByRepo', () => {
|
||||||
|
const repos = [repo('r1', 'alpha'), repo('r2', 'beta')];
|
||||||
|
const byRepo: Record<string, WorktreeSummary[]> = {
|
||||||
|
r1: [
|
||||||
|
wt('/wt/main', { isMain: true, git: git({ dirtyCount: 2, unstagedCount: 2 }) }),
|
||||||
|
wt('/wt/feature'),
|
||||||
|
],
|
||||||
|
r2: [wt('/wt/clean', { repoId: 'r2' })],
|
||||||
|
};
|
||||||
|
const forRepo = (id: string): WorktreeSummary[] => byRepo[id] ?? [];
|
||||||
|
|
||||||
|
it('ne garde que ce qui a du travail, et masque un dépôt sans worktree retenu', () => {
|
||||||
|
const groups = groupWorktreesByRepo(repos, forRepo, { showClean: false, active: null });
|
||||||
|
expect(groups).toHaveLength(1);
|
||||||
|
expect(groups[0]?.repo.id).toBe('r1');
|
||||||
|
expect(groups[0]?.worktrees.map((w) => w.path)).toEqual(['/wt/main']);
|
||||||
|
expect(groups[0]?.dirtyFiles).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('showClean inclut tout', () => {
|
||||||
|
const groups = groupWorktreesByRepo(repos, forRepo, { showClean: true, active: null });
|
||||||
|
expect(groups.map((g) => g.repo.id)).toEqual(['r1', 'r2']);
|
||||||
|
expect(groups[0]?.worktrees).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('le worktree actif reste affiché même propre (la vue ne se vide pas après un commit)', () => {
|
||||||
|
const groups = groupWorktreesByRepo(repos, forRepo, {
|
||||||
|
showClean: false,
|
||||||
|
active: { repoId: 'r2', wtPath: '/wt/clean' },
|
||||||
|
});
|
||||||
|
expect(groups.map((g) => g.repo.id)).toEqual(['r1', 'r2']);
|
||||||
|
expect(groups[1]?.worktrees.map((w) => w.path)).toEqual(['/wt/clean']);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Portée : le terminal focalisé (ou son groupe) restreint la vue. Le filtre est un ET, sinon un
|
||||||
|
// worktree étranger fuirait dans une portée de groupe.
|
||||||
|
it('inScope masque un worktree sale hors portée', () => {
|
||||||
|
const groups = groupWorktreesByRepo(repos, forRepo, {
|
||||||
|
showClean: false,
|
||||||
|
active: null,
|
||||||
|
inScope: (w) => w.repoId === 'r2',
|
||||||
|
});
|
||||||
|
expect(groups).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('inScope PRIME sur active et sur showClean', () => {
|
||||||
|
const onlyR1 = (w: { repoId: string }): boolean => w.repoId === 'r1';
|
||||||
|
const withActive = groupWorktreesByRepo(repos, forRepo, {
|
||||||
|
showClean: false,
|
||||||
|
active: { repoId: 'r2', wtPath: '/wt/clean' },
|
||||||
|
inScope: onlyR1,
|
||||||
|
});
|
||||||
|
expect(withActive.map((g) => g.repo.id)).toEqual(['r1']);
|
||||||
|
|
||||||
|
const withClean = groupWorktreesByRepo(repos, forRepo, { showClean: true, active: null, inScope: onlyR1 });
|
||||||
|
expect(withClean.map((g) => g.repo.id)).toEqual(['r1']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('inScope absent : comportement inchangé', () => {
|
||||||
|
const sansPortee = groupWorktreesByRepo(repos, forRepo, { showClean: true, active: null });
|
||||||
|
const portéeTotale = groupWorktreesByRepo(repos, forRepo, { showClean: true, active: null, inScope: () => true });
|
||||||
|
expect(portéeTotale).toEqual(sansPortee);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pendingWorktreeCount · portée', () => {
|
||||||
|
it('compte tout par défaut, et se restreint quand inScope est fourni', () => {
|
||||||
|
const repos = [repo('r1', 'alpha'), repo('r2', 'beta')];
|
||||||
|
const byRepo: Record<string, WorktreeSummary[]> = {
|
||||||
|
r1: [wt('/wt/main', { git: git({ dirtyCount: 1 }) })],
|
||||||
|
r2: [wt('/wt/other', { repoId: 'r2', git: git({ ahead: 2 }) })],
|
||||||
|
};
|
||||||
|
const forRepo = (id: string): WorktreeSummary[] => byRepo[id] ?? [];
|
||||||
|
expect(pendingWorktreeCount(repos, forRepo)).toBe(2);
|
||||||
|
expect(pendingWorktreeCount(repos, forRepo, (w) => w.repoId === 'r1')).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('sortForIndex', () => {
|
||||||
|
it('ce qui demande une action d abord, puis le principal, puis le chemin', () => {
|
||||||
|
const list = [
|
||||||
|
wt('/b/clean'),
|
||||||
|
wt('/a/main', { isMain: true }),
|
||||||
|
wt('/c/dirty', { git: git({ dirtyCount: 1 }) }),
|
||||||
|
];
|
||||||
|
expect(sortForIndex(list).map((w) => w.path)).toEqual(['/c/dirty', '/a/main', '/b/clean']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne mute pas la liste reçue', () => {
|
||||||
|
const list = [wt('/b'), wt('/a')];
|
||||||
|
sortForIndex(list);
|
||||||
|
expect(list.map((w) => w.path)).toEqual(['/b', '/a']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pendingWorktreeCount', () => {
|
||||||
|
it('compte les worktrees à traiter, tous dépôts visibles confondus', () => {
|
||||||
|
const forRepo = (id: string): WorktreeSummary[] =>
|
||||||
|
id === 'r1'
|
||||||
|
? [wt('/a', { git: git({ dirtyCount: 1 }) }), wt('/b')]
|
||||||
|
: [wt('/c', { repoId: 'r2', git: git({ ahead: 2 }) })];
|
||||||
|
expect(pendingWorktreeCount([repo('r1'), repo('r2')], forRepo)).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
// Cache des listes de fichiers modifiés : invalidation par jeton, plafond de chargements simultanés,
|
||||||
|
// et erreur qui reste visible au lieu d'être avalée (le défaut de l'ancien panneau Git).
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { createPinia, setActivePinia } from 'pinia';
|
||||||
|
import type { FileChange, WorktreeChangesResponse } from '@arboretum/shared';
|
||||||
|
|
||||||
|
interface Deferred {
|
||||||
|
resolve: (res: WorktreeChangesResponse) => void;
|
||||||
|
reject: (err: Error) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let calls: string[] = [];
|
||||||
|
let inFlight = 0;
|
||||||
|
let maxInFlight = 0;
|
||||||
|
let deferreds: Deferred[] = [];
|
||||||
|
/** Quand true, chaque appel reste en vol jusqu'à résolution explicite (test du plafond). */
|
||||||
|
let manual = false;
|
||||||
|
let failNext = false;
|
||||||
|
|
||||||
|
vi.mock('../src/lib/git-api', () => ({
|
||||||
|
gitApi: {
|
||||||
|
changes: (repoId: string, wt: string): Promise<WorktreeChangesResponse> => {
|
||||||
|
calls.push(`${repoId}\0${wt}`);
|
||||||
|
inFlight++;
|
||||||
|
maxInFlight = Math.max(maxInFlight, inFlight);
|
||||||
|
const settle = <T,>(p: Promise<T>): Promise<T> =>
|
||||||
|
p.finally(() => {
|
||||||
|
inFlight--;
|
||||||
|
});
|
||||||
|
if (manual) {
|
||||||
|
return settle(
|
||||||
|
new Promise<WorktreeChangesResponse>((resolve, reject) => {
|
||||||
|
deferreds.push({ resolve, reject });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (failNext) {
|
||||||
|
failNext = false;
|
||||||
|
return settle(Promise.reject(new Error('boom')));
|
||||||
|
}
|
||||||
|
return settle(Promise.resolve({ repoId, path: wt, changes: [], truncated: false }));
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
const { useChangesStore, MAX_CONCURRENT_LOADS } = await import('../src/stores/changes');
|
||||||
|
const { useWorktreesStore } = await import('../src/stores/worktrees');
|
||||||
|
|
||||||
|
function fakeStorage() {
|
||||||
|
const m = new Map<string, string>();
|
||||||
|
return {
|
||||||
|
getItem: (k: string) => (m.has(k) ? (m.get(k) as string) : null),
|
||||||
|
setItem: (k: string, v: string) => void m.set(k, v),
|
||||||
|
removeItem: (k: string) => void m.delete(k),
|
||||||
|
clear: () => m.clear(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Laisse la file se dépiler (les chargements sont enchaînés par des microtâches). */
|
||||||
|
const settle = async (): Promise<void> => {
|
||||||
|
for (let i = 0; i < 20; i++) await Promise.resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('store changes', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
calls = [];
|
||||||
|
deferreds = [];
|
||||||
|
inFlight = 0;
|
||||||
|
maxInFlight = 0;
|
||||||
|
manual = false;
|
||||||
|
failNext = false;
|
||||||
|
(globalThis as unknown as { localStorage: unknown }).localStorage = fakeStorage();
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne recharge pas une entrée fraîche, recharge dès que le jeton bouge', async () => {
|
||||||
|
const changes = useChangesStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
|
||||||
|
changes.request('r1', '/wt/a');
|
||||||
|
await settle();
|
||||||
|
expect(calls).toHaveLength(1);
|
||||||
|
|
||||||
|
changes.request('r1', '/wt/a'); // rien n'a bougé
|
||||||
|
await settle();
|
||||||
|
expect(calls).toHaveLength(1);
|
||||||
|
|
||||||
|
worktrees.noteChange('r1', '/wt/a'); // le disque a bougé
|
||||||
|
changes.request('r1', '/wt/a');
|
||||||
|
await settle();
|
||||||
|
expect(calls).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('invalidate force le rechargement sans jeton', async () => {
|
||||||
|
const changes = useChangesStore();
|
||||||
|
changes.request('r1', '/wt/a');
|
||||||
|
await settle();
|
||||||
|
changes.invalidate('r1', '/wt/a');
|
||||||
|
await settle();
|
||||||
|
expect(calls).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('une erreur reste visible et la liste précédente est conservée', async () => {
|
||||||
|
const changes = useChangesStore();
|
||||||
|
const seeded: FileChange[] = [
|
||||||
|
{
|
||||||
|
path: 'src/x.ts',
|
||||||
|
indexStatus: '.',
|
||||||
|
worktreeStatus: 'M',
|
||||||
|
staged: false,
|
||||||
|
unstaged: true,
|
||||||
|
untracked: false,
|
||||||
|
conflicted: false,
|
||||||
|
insertions: 1,
|
||||||
|
deletions: 0,
|
||||||
|
binary: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
// premier chargement réussi, puis échec
|
||||||
|
changes.request('r1', '/wt/a');
|
||||||
|
await settle();
|
||||||
|
changes.entries['r1\0/wt/a'] = { ...changes.entries['r1\0/wt/a']!, changes: seeded };
|
||||||
|
|
||||||
|
failNext = true;
|
||||||
|
changes.invalidate('r1', '/wt/a');
|
||||||
|
await settle();
|
||||||
|
|
||||||
|
const entry = changes.entry('r1', '/wt/a');
|
||||||
|
expect(entry?.error).toBe('boom');
|
||||||
|
expect(entry?.changes).toEqual(seeded); // pas d'écran qui se vide
|
||||||
|
expect(entry?.loading).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne dépasse jamais le plafond de chargements simultanés', async () => {
|
||||||
|
manual = true;
|
||||||
|
const changes = useChangesStore();
|
||||||
|
for (let i = 0; i < 10; i++) changes.request('r1', `/wt/${i}`);
|
||||||
|
await settle();
|
||||||
|
expect(maxInFlight).toBe(MAX_CONCURRENT_LOADS);
|
||||||
|
expect(calls).toHaveLength(MAX_CONCURRENT_LOADS);
|
||||||
|
|
||||||
|
// on libère tout : la file se dépile jusqu'au bout
|
||||||
|
while (deferreds.length > 0) {
|
||||||
|
const d = deferreds.shift();
|
||||||
|
d?.resolve({ repoId: 'r1', path: '/wt/x', changes: [], truncated: false });
|
||||||
|
await settle();
|
||||||
|
}
|
||||||
|
expect(calls).toHaveLength(10);
|
||||||
|
expect(maxInFlight).toBe(MAX_CONCURRENT_LOADS);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('forget libère, invalidateAll repérime, reset vide', async () => {
|
||||||
|
const changes = useChangesStore();
|
||||||
|
changes.request('r1', '/wt/a');
|
||||||
|
changes.request('r1', '/wt/b');
|
||||||
|
await settle();
|
||||||
|
expect(Object.keys(changes.entries)).toHaveLength(2);
|
||||||
|
|
||||||
|
changes.forget('r1', '/wt/a');
|
||||||
|
expect(changes.entry('r1', '/wt/a')).toBeNull();
|
||||||
|
|
||||||
|
expect(changes.isStale('r1', '/wt/b')).toBe(false);
|
||||||
|
changes.invalidateAll();
|
||||||
|
expect(changes.isStale('r1', '/wt/b')).toBe(true);
|
||||||
|
|
||||||
|
changes.reset();
|
||||||
|
expect(Object.keys(changes.entries)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
// Portée déduite du terminal focalisé. Le piège central : une session de GROUPE a pour cwd le parent
|
||||||
|
// commun des dépôts, donc la rattacher par chemin donnerait un worktree arbitraire (ou rien).
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { resolveScope, SCOPE_ALL, scopeContains, worktreesForSession, worktreesInScope } from '../src/lib/context-scope';
|
||||||
|
|
||||||
|
const wt = (repoId: string, path: string): { repoId: string; path: string } => ({ repoId, path });
|
||||||
|
|
||||||
|
const WORKTREES = [
|
||||||
|
wt('api', '/repos/api'),
|
||||||
|
wt('api', '/repos/api/.worktrees/feature'),
|
||||||
|
wt('web', '/repos/web'),
|
||||||
|
wt('docs', '/ailleurs/docs'),
|
||||||
|
];
|
||||||
|
const GROUPS = [
|
||||||
|
{ id: 'stack', repoIds: ['api', 'web'] },
|
||||||
|
{ id: 'tout', repoIds: ['api', 'web', 'docs'] },
|
||||||
|
];
|
||||||
|
|
||||||
|
describe('resolveScope', () => {
|
||||||
|
it('session de groupe : portée GROUPE, jamais un worktree (cwd = parent commun)', () => {
|
||||||
|
const scope = resolveScope({ cwd: '/repos', addedDirs: ['/repos/api', '/repos/web'], groupId: 'stack' }, WORKTREES, GROUPS);
|
||||||
|
expect(scope).toEqual({ kind: 'group', groupId: 'stack' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('groupId inconnu des données live : tout voir plutôt qu’une portée vide', () => {
|
||||||
|
expect(resolveScope({ cwd: '/repos', groupId: 'disparu' }, WORKTREES, GROUPS)).toEqual(SCOPE_ALL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('session multi-dépôts SANS groupId : groupe qui les contient tous', () => {
|
||||||
|
const scope = resolveScope({ cwd: '/repos/api', addedDirs: ['/repos/web'] }, WORKTREES, GROUPS);
|
||||||
|
expect(scope).toEqual({ kind: 'group', groupId: 'stack' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('multi-dépôts sans groupe commun : tout voir', () => {
|
||||||
|
const scope = resolveScope({ cwd: '/repos/api', addedDirs: ['/ailleurs/docs'] }, WORKTREES, [{ id: 'stack', repoIds: ['api', 'web'] }]);
|
||||||
|
expect(scope).toEqual(SCOPE_ALL);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('terminal lancé dans un SOUS-répertoire : worktree du projet (contenance, pas égalité)', () => {
|
||||||
|
const scope = resolveScope({ cwd: '/repos/web/packages/front' }, WORKTREES, GROUPS);
|
||||||
|
expect(scope).toEqual({ kind: 'worktree', repoId: 'web', wtPath: '/repos/web' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('worktrees imbriqués : le plus profond gagne', () => {
|
||||||
|
const scope = resolveScope({ cwd: '/repos/api/.worktrees/feature/src' }, WORKTREES, GROUPS);
|
||||||
|
expect(scope).toEqual({ kind: 'worktree', repoId: 'api', wtPath: '/repos/api/.worktrees/feature' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cwd hors de tout worktree connu, ou pas de session : null (l’appelant se rabat)', () => {
|
||||||
|
expect(resolveScope({ cwd: '/tmp/scratch' }, WORKTREES, GROUPS)).toBeNull();
|
||||||
|
expect(resolveScope(null, WORKTREES, GROUPS)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('scopeContains', () => {
|
||||||
|
it('all : tout ; worktree : la paire exacte ; groupe : tout worktree d’un dépôt du groupe', () => {
|
||||||
|
expect(scopeContains(SCOPE_ALL, { repoId: 'docs', wtPath: '/ailleurs/docs' }, GROUPS)).toBe(true);
|
||||||
|
|
||||||
|
const only = { kind: 'worktree', repoId: 'api', wtPath: '/repos/api' } as const;
|
||||||
|
expect(scopeContains(only, { repoId: 'api', wtPath: '/repos/api' }, GROUPS)).toBe(true);
|
||||||
|
expect(scopeContains(only, { repoId: 'api', wtPath: '/repos/api/.worktrees/feature' }, GROUPS)).toBe(false);
|
||||||
|
expect(scopeContains(only, { repoId: 'web', wtPath: '/repos/web' }, GROUPS)).toBe(false);
|
||||||
|
|
||||||
|
const group = { kind: 'group', groupId: 'stack' } as const;
|
||||||
|
expect(scopeContains(group, { repoId: 'web', wtPath: '/repos/web' }, GROUPS)).toBe(true);
|
||||||
|
expect(scopeContains(group, { repoId: 'api', wtPath: '/repos/api/.worktrees/feature' }, GROUPS)).toBe(true);
|
||||||
|
expect(scopeContains(group, { repoId: 'docs', wtPath: '/ailleurs/docs' }, GROUPS)).toBe(false);
|
||||||
|
// groupe supprimé entre-temps : plus rien ne matche, l'appelant doit déjà avoir replié sur 'all'
|
||||||
|
expect(scopeContains({ kind: 'group', groupId: 'disparu' }, { repoId: 'api', wtPath: '/repos/api' }, GROUPS)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('worktreesForSession / worktreesInScope', () => {
|
||||||
|
it('cwd + addedDirs, dédupliqués, le plus profond gagnant', () => {
|
||||||
|
const covered = worktreesForSession({ cwd: '/repos/api/src', addedDirs: ['/repos/api/lib', '/repos/web'] }, WORKTREES);
|
||||||
|
expect(covered.map((w) => w.path)).toEqual(['/repos/api', '/repos/web']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un répertoire hors worktree connu est simplement ignoré', () => {
|
||||||
|
expect(worktreesForSession({ cwd: '/tmp/x', addedDirs: ['/repos/web'] }, WORKTREES).map((w) => w.repoId)).toEqual(['web']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('worktreesInScope filtre la liste complète', () => {
|
||||||
|
expect(worktreesInScope(SCOPE_ALL, WORKTREES, GROUPS)).toHaveLength(4);
|
||||||
|
expect(worktreesInScope({ kind: 'group', groupId: 'stack' }, WORKTREES, GROUPS).map((w) => w.path)).toEqual([
|
||||||
|
'/repos/api',
|
||||||
|
'/repos/api/.worktrees/feature',
|
||||||
|
'/repos/web',
|
||||||
|
]);
|
||||||
|
expect(worktreesInScope({ kind: 'worktree', repoId: 'web', wtPath: '/repos/web' }, WORKTREES, GROUPS).map((w) => w.repoId)).toEqual(['web']);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,315 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
addPane,
|
||||||
|
activeColumnOf,
|
||||||
|
closePane,
|
||||||
|
DOCK_MIN_HEIGHT,
|
||||||
|
dockMaxHeight,
|
||||||
|
dockOpenHeight,
|
||||||
|
EMPTY_DOCK,
|
||||||
|
findPane,
|
||||||
|
focusColumn,
|
||||||
|
focusPane,
|
||||||
|
MAX_DOCK_COLUMNS,
|
||||||
|
MIN_DOCK_COLUMN_RATIO,
|
||||||
|
mergeColumns,
|
||||||
|
migrateDock,
|
||||||
|
movePane,
|
||||||
|
prunePanes,
|
||||||
|
setSplit,
|
||||||
|
type DockState,
|
||||||
|
} from '../src/lib/dock-model';
|
||||||
|
|
||||||
|
/** Ids déterministes : les assertions portent sur la structure, pas sur une horloge. */
|
||||||
|
function ids(): () => string {
|
||||||
|
let n = 0;
|
||||||
|
return () => `col${++n}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Les 5 invariants du modèle, vérifiés APRÈS chaque opération : sur une machine à états, c'est le
|
||||||
|
* filet qui rattrape les cas qu'on n'a pas pensé à écrire.
|
||||||
|
*/
|
||||||
|
function expectDockInvariants(s: DockState): void {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const c of s.columns) {
|
||||||
|
expect(c.sessionIds.length).toBeGreaterThan(0);
|
||||||
|
expect(c.sessionIds).toContain(c.activeSessionId);
|
||||||
|
for (const sid of c.sessionIds) {
|
||||||
|
expect(seen.has(sid)).toBe(false);
|
||||||
|
seen.add(sid);
|
||||||
|
}
|
||||||
|
expect(c.ratio).toBeGreaterThanOrEqual(Math.min(MIN_DOCK_COLUMN_RATIO, 1 / s.columns.length) - 1e-9);
|
||||||
|
}
|
||||||
|
if (s.columns.length === 0) {
|
||||||
|
expect(s.activeColumnId).toBeNull();
|
||||||
|
} else {
|
||||||
|
expect(s.columns.some((c) => c.id === s.activeColumnId)).toBe(true);
|
||||||
|
expect(s.columns.reduce((sum, c) => sum + c.ratio, 0)).toBeCloseTo(1, 9);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dock à N colonnes d'un pane chacune, parts égales. */
|
||||||
|
function dock(...columns: string[][]): DockState {
|
||||||
|
const cols = columns.map((sessionIds, i) => ({
|
||||||
|
id: `col${i + 1}`,
|
||||||
|
sessionIds,
|
||||||
|
activeSessionId: sessionIds[0]!,
|
||||||
|
ratio: 1 / columns.length,
|
||||||
|
}));
|
||||||
|
return { columns: cols, activeColumnId: cols[0]?.id ?? null };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('addPane', () => {
|
||||||
|
it('premier pane : une colonne pleine largeur, active', () => {
|
||||||
|
const s = addPane(EMPTY_DOCK, 's1', 'tab', ids());
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.ratio).toBe(1);
|
||||||
|
expect(s.activeColumnId).toBe('col1');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("'tab' ajoute un onglet à la colonne active et le rend visible", () => {
|
||||||
|
const make = ids();
|
||||||
|
let s = addPane(EMPTY_DOCK, 's1', 'tab', make);
|
||||||
|
s = addPane(s, 's2', 'tab', make);
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['s1', 's2']);
|
||||||
|
expect(s.columns[0]!.activeSessionId).toBe('s2');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("'split' insère une colonne APRÈS l'active, qui lui cède la moitié de sa part", () => {
|
||||||
|
const make = ids();
|
||||||
|
let s = addPane(EMPTY_DOCK, 's1', 'tab', make);
|
||||||
|
s = addPane(s, 's2', 'split', make);
|
||||||
|
expect(s.columns.map((c) => c.sessionIds)).toEqual([['s1'], ['s2']]);
|
||||||
|
expect(s.columns[0]!.ratio).toBeCloseTo(0.5);
|
||||||
|
expect(s.columns[1]!.ratio).toBeCloseTo(0.5);
|
||||||
|
expect(s.activeColumnId).toBe('col2');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("'split' ne touche pas les colonnes voisines de l'active", () => {
|
||||||
|
const make = ids();
|
||||||
|
let s = dock(['a'], ['b']);
|
||||||
|
s = focusColumn(s, 'col2');
|
||||||
|
s = addPane(s, 'c', 'split', () => 'new');
|
||||||
|
expect(s.columns.map((c) => c.sessionIds)).toEqual([['a'], ['b'], ['c']]);
|
||||||
|
expect(s.columns[0]!.ratio).toBeCloseTo(0.5);
|
||||||
|
expect(s.columns[1]!.ratio).toBeCloseTo(0.25);
|
||||||
|
expect(s.columns[2]!.ratio).toBeCloseTo(0.25);
|
||||||
|
expectDockInvariants(s);
|
||||||
|
expect(make).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('une session déjà ouverte est déplacée, jamais dupliquée', () => {
|
||||||
|
let s = dock(['a', 'b'], ['c']);
|
||||||
|
s = addPane(s, 'b', 'split', () => 'new');
|
||||||
|
expect(findPane(s, 'b')!.column.sessionIds).toEqual(['b']);
|
||||||
|
expect(s.columns.flatMap((c) => c.sessionIds).filter((id) => id === 'b')).toHaveLength(1);
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('au plafond de colonnes, un split retombe en onglet (et focalise)', () => {
|
||||||
|
const make = ids();
|
||||||
|
let s = dock(['a'], ['b'], ['c']);
|
||||||
|
expect(s.columns).toHaveLength(MAX_DOCK_COLUMNS);
|
||||||
|
s = addPane(s, 'd', 'split', make);
|
||||||
|
expect(s.columns).toHaveLength(MAX_DOCK_COLUMNS);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['a', 'd']);
|
||||||
|
expect(s.columns[0]!.activeSessionId).toBe('d');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('focusPane / focusColumn', () => {
|
||||||
|
it('focaliser un onglet active AUSSI sa colonne', () => {
|
||||||
|
const s = focusPane(dock(['a'], ['b', 'c']), 'c');
|
||||||
|
expect(s.activeColumnId).toBe('col2');
|
||||||
|
expect(s.columns[1]!.activeSessionId).toBe('c');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('session inconnue ou état déjà correct : identité', () => {
|
||||||
|
const s = dock(['a'], ['b']);
|
||||||
|
expect(focusPane(s, 'zzz')).toBe(s);
|
||||||
|
expect(focusPane(s, 'a')).toBe(s);
|
||||||
|
expect(focusColumn(s, 'col1')).toBe(s);
|
||||||
|
expect(focusColumn(s, 'inconnue')).toBe(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('closePane', () => {
|
||||||
|
it('fermer un onglet parmi plusieurs : le voisin devient visible', () => {
|
||||||
|
const s = closePane({ ...dock(['a', 'b', 'c']), columns: [{ id: 'col1', sessionIds: ['a', 'b', 'c'], activeSessionId: 'b', ratio: 1 }] }, 'b');
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['a', 'c']);
|
||||||
|
expect(s.columns[0]!.activeSessionId).toBe('c');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('colonne vidée : supprimée, sa part léguée au voisin de gauche', () => {
|
||||||
|
const s = closePane(dock(['a'], ['b']), 'b');
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['a']);
|
||||||
|
expect(s.columns[0]!.ratio).toBeCloseTo(1);
|
||||||
|
expect(s.activeColumnId).toBe('col1');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('première colonne vidée : la part va au voisin de droite', () => {
|
||||||
|
const s = closePane(dock(['a'], ['b']), 'a');
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['b']);
|
||||||
|
expect(s.columns[0]!.ratio).toBeCloseTo(1);
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dernier pane du dock : dock vide', () => {
|
||||||
|
const s = closePane(dock(['a']), 'a');
|
||||||
|
expect(s).toEqual(EMPTY_DOCK);
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('session inconnue : identité', () => {
|
||||||
|
const s = dock(['a']);
|
||||||
|
expect(closePane(s, 'zzz')).toBe(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('movePane', () => {
|
||||||
|
it('vers une autre colonne : la source vidée disparaît', () => {
|
||||||
|
const s = movePane(dock(['a'], ['b']), 'a', { columnId: 'col2' });
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['b', 'a']);
|
||||||
|
expect(s.columns[0]!.activeSessionId).toBe('a');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détacher un onglet crée une colonne à droite de la sienne', () => {
|
||||||
|
const s = movePane(dock(['a', 'b']), 'b', { split: true }, () => 'new');
|
||||||
|
expect(s.columns.map((c) => c.sessionIds)).toEqual([['a'], ['b']]);
|
||||||
|
expect(s.activeColumnId).toBe('new');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('détacher un pane déjà seul en colonne : identité de contenu, simple focus', () => {
|
||||||
|
const s = dock(['a'], ['b']);
|
||||||
|
const next = movePane(s, 'b', { split: true }, () => 'new');
|
||||||
|
expect(next.columns.map((c) => c.sessionIds)).toEqual([['a'], ['b']]);
|
||||||
|
expect(next.activeColumnId).toBe('col2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cible inconnue ou déjà la bonne colonne : identité', () => {
|
||||||
|
const s = dock(['a', 'b']);
|
||||||
|
expect(movePane(s, 'a', { columnId: 'col1' })).toBe(s);
|
||||||
|
expect(movePane(s, 'a', { columnId: 'zzz' })).toBe(s);
|
||||||
|
expect(movePane(s, 'zzz', { split: true })).toBe(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('setSplit', () => {
|
||||||
|
it('la somme de la paire est préservée, la 3e colonne intacte', () => {
|
||||||
|
const s = setSplit(dock(['a'], ['b'], ['c']), 0, 0.5);
|
||||||
|
expect(s.columns[0]!.ratio + s.columns[1]!.ratio).toBeCloseTo(2 / 3);
|
||||||
|
expect(s.columns[0]!.ratio).toBeCloseTo(0.5);
|
||||||
|
expect(s.columns[2]!.ratio).toBeCloseTo(1 / 3);
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clampé par MIN_DOCK_COLUMN_RATIO des deux côtés', () => {
|
||||||
|
const wide = setSplit(dock(['a'], ['b']), 0, 0.99);
|
||||||
|
expect(wide.columns[1]!.ratio).toBeCloseTo(MIN_DOCK_COLUMN_RATIO);
|
||||||
|
const narrow = setSplit(dock(['a'], ['b']), 0, 0.01);
|
||||||
|
expect(narrow.columns[0]!.ratio).toBeCloseTo(MIN_DOCK_COLUMN_RATIO);
|
||||||
|
expectDockInvariants(wide);
|
||||||
|
expectDockInvariants(narrow);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('frontière inexistante : identité', () => {
|
||||||
|
const s = dock(['a'], ['b']);
|
||||||
|
expect(setSplit(s, 1, 0.5)).toBe(s);
|
||||||
|
expect(setSplit(s, -1, 0.5)).toBe(s);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('prunePanes', () => {
|
||||||
|
it('retire les sessions mortes, supprime les colonnes vidées et renormalise', () => {
|
||||||
|
const s = prunePanes(dock(['a', 'b'], ['c']), new Set(['a']));
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['a']);
|
||||||
|
expect(s.columns[0]!.ratio).toBeCloseTo(1);
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("répare l'onglet visible quand c'est lui qui est mort", () => {
|
||||||
|
const base: DockState = { columns: [{ id: 'col1', sessionIds: ['a', 'b'], activeSessionId: 'b', ratio: 1 }], activeColumnId: 'col1' };
|
||||||
|
const s = prunePanes(base, new Set(['a']));
|
||||||
|
expect(s.columns[0]!.activeSessionId).toBe('a');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tout est vivant : identité (aucune écriture inutile dans le localStorage)', () => {
|
||||||
|
const s = dock(['a'], ['b']);
|
||||||
|
expect(prunePanes(s, new Set(['a', 'b']))).toBe(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('plus rien de vivant : dock vide', () => {
|
||||||
|
expect(prunePanes(dock(['a'], ['b']), new Set())).toEqual(EMPTY_DOCK);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('mergeColumns', () => {
|
||||||
|
it("conserve l'ordre des onglets et l'onglet focalisé", () => {
|
||||||
|
const s = mergeColumns(focusPane(dock(['a', 'b'], ['c']), 'c'));
|
||||||
|
expect(s.columns).toHaveLength(1);
|
||||||
|
expect(s.columns[0]!.sessionIds).toEqual(['a', 'b', 'c']);
|
||||||
|
expect(s.columns[0]!.activeSessionId).toBe('c');
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('une seule colonne (ou aucune) : identité', () => {
|
||||||
|
const one = dock(['a']);
|
||||||
|
expect(mergeColumns(one)).toBe(one);
|
||||||
|
expect(mergeColumns(EMPTY_DOCK)).toBe(EMPTY_DOCK);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('migrateDock', () => {
|
||||||
|
it('ancien dock à plat : une colonne, ordre et onglet actif conservés', () => {
|
||||||
|
const s = migrateDock(['a', 'b'], 'b', () => 'col1');
|
||||||
|
expect(s).toEqual({ columns: [{ id: 'col1', sessionIds: ['a', 'b'], activeSessionId: 'b', ratio: 1 }], activeColumnId: 'col1' });
|
||||||
|
expectDockInvariants(s);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('actif périmé ou absent : premier onglet ; liste vide : dock vide', () => {
|
||||||
|
expect(migrateDock(['a'], 'zzz', () => 'col1').columns[0]!.activeSessionId).toBe('a');
|
||||||
|
expect(migrateDock([], null)).toEqual(EMPTY_DOCK);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('géométrie du dock', () => {
|
||||||
|
it('plafond à 80 % du viewport, plancher garanti', () => {
|
||||||
|
expect(dockMaxHeight(1080)).toBe(864);
|
||||||
|
expect(dockMaxHeight(1000)).toBe(800);
|
||||||
|
expect(dockMaxHeight(600)).toBe(400); // 600-200 borne avant les 80 %
|
||||||
|
expect(dockMaxHeight(150)).toBe(DOCK_MIN_HEIGHT);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hauteur d'ouverture : ~45 %, jamais au-delà du plafond ni sous le plancher", () => {
|
||||||
|
expect(dockOpenHeight(1080)).toBe(486);
|
||||||
|
expect(dockOpenHeight(600)).toBe(270);
|
||||||
|
expect(dockOpenHeight(200)).toBe(DOCK_MIN_HEIGHT);
|
||||||
|
for (const h of [200, 400, 768, 1080, 1440, 2160]) {
|
||||||
|
expect(dockOpenHeight(h)).toBeLessThanOrEqual(dockMaxHeight(h));
|
||||||
|
expect(dockOpenHeight(h)).toBeGreaterThanOrEqual(DOCK_MIN_HEIGHT);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('activeColumnOf', () => {
|
||||||
|
it('rend la colonne active, ou null', () => {
|
||||||
|
expect(activeColumnOf(dock(['a']))!.sessionIds).toEqual(['a']);
|
||||||
|
expect(activeColumnOf(EMPTY_DOCK)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
// Store IDE : onglets (ouverture/dedup/fermeture), dock terminaux, activité, réconciliation.
|
// Store IDE : onglets (ouverture/dedup/fermeture), dock terminaux, activité, réconciliation.
|
||||||
import { describe, it, expect, beforeEach } from 'vitest';
|
import { describe, it, expect, beforeEach } from 'vitest';
|
||||||
import { createPinia, setActivePinia } from 'pinia';
|
import { createPinia, setActivePinia } from 'pinia';
|
||||||
import { useIdeStore, tabId, wtKey } from '../src/stores/ide';
|
import { MOBILE_PANELS, parseWtKey, useIdeStore, tabId, wtKey } from '../src/stores/ide';
|
||||||
|
|
||||||
function fakeStorage() {
|
function fakeStorage() {
|
||||||
const m = new Map<string, string>();
|
const m = new Map<string, string>();
|
||||||
@@ -111,6 +111,80 @@ describe('store IDE', () => {
|
|||||||
expect(ide.bottomVisible).toBe(false);
|
expect(ide.bottomVisible).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- dock en colonnes (plusieurs terminaux visibles côte à côte) ---
|
||||||
|
|
||||||
|
it('dock : openTerminal { split } crée une seconde colonne, les deux panes restent visibles', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
ide.openTerminal('s2', { split: true });
|
||||||
|
expect(ide.dockColumns).toHaveLength(2);
|
||||||
|
expect(ide.dockSessionIds).toEqual(['s1', 's2']);
|
||||||
|
expect(ide.visibleDockSessionIds).toEqual(['s1', 's2']);
|
||||||
|
expect(ide.activeDockSessionId).toBe('s2');
|
||||||
|
expect(ide.canSplitTerminal).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dock : splitTerminal détache le pane focalisé, mergeDockColumns ramène tout en une colonne', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
ide.openTerminal('s2');
|
||||||
|
ide.splitTerminal(); // s2 est focalisé
|
||||||
|
expect(ide.dockColumns.map((c) => c.sessionIds)).toEqual([['s1'], ['s2']]);
|
||||||
|
ide.mergeDockColumns();
|
||||||
|
expect(ide.dockColumns.map((c) => c.sessionIds)).toEqual([['s1', 's2']]);
|
||||||
|
expect(ide.activeDockSessionId).toBe('s2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dock : focusDockColumn change la colonne active, donc le terminal focalisé', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
ide.openTerminal('s2', { split: true });
|
||||||
|
ide.focusDockColumn(ide.dockColumns[0]!.id);
|
||||||
|
expect(ide.activeDockSessionId).toBe('s1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dock : une session n’est jamais dans deux colonnes (2e attache = PTY figé)', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
ide.openTerminal('s2');
|
||||||
|
ide.openTerminal('s2', { split: true }); // déjà ouvert : déplacé, pas dupliqué
|
||||||
|
expect(ide.dockSessionIds.filter((s) => s === 's2')).toHaveLength(1);
|
||||||
|
expect(ide.dockColumns.map((c) => c.sessionIds)).toEqual([['s1'], ['s2']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dock : fermer le dernier pane d’une colonne supprime la colonne, pas le dock', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
ide.openTerminal('s2', { split: true });
|
||||||
|
ide.closeTerminal('s2');
|
||||||
|
expect(ide.dockColumns).toHaveLength(1);
|
||||||
|
expect(ide.bottomVisible).toBe(true);
|
||||||
|
ide.closeTerminal('s1');
|
||||||
|
expect(ide.dockColumns).toEqual([]);
|
||||||
|
expect(ide.bottomVisible).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dock : setDockColumnSplit redistribue la paire saisie', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
ide.openTerminal('s2', { split: true });
|
||||||
|
ide.setDockColumnSplit(0, 0.7);
|
||||||
|
expect(ide.dockColumns[0]!.ratio).toBeCloseTo(0.7);
|
||||||
|
expect(ide.dockColumns[1]!.ratio).toBeCloseTo(0.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dock : migration silencieuse de l’ancien état mono-colonne, et oubli des clés legacy', () => {
|
||||||
|
localStorage.setItem('arb.ide.dock', JSON.stringify(['a', 'b']));
|
||||||
|
localStorage.setItem('arb.ide.activeDock', JSON.stringify('b'));
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
const ide = useIdeStore();
|
||||||
|
expect(ide.dockColumns).toHaveLength(1);
|
||||||
|
expect(ide.dockSessionIds).toEqual(['a', 'b']);
|
||||||
|
expect(ide.activeDockSessionId).toBe('b');
|
||||||
|
expect(localStorage.getItem('arb.ide.dock')).toBeNull();
|
||||||
|
expect(localStorage.getItem('arb.ide.activeDock')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
it('toggleActivity : re-clic sur la vue active replie le panneau', () => {
|
it('toggleActivity : re-clic sur la vue active replie le panneau', () => {
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
expect(ide.activeActivity).toBe('explorer');
|
expect(ide.activeActivity).toBe('explorer');
|
||||||
@@ -130,13 +204,90 @@ describe('store IDE', () => {
|
|||||||
ide.setTabDirty(tabId('r', '/w2', 'b'), true);
|
ide.setTabDirty(tabId('r', '/w2', 'b'), true);
|
||||||
ide.openTerminal('sLive');
|
ide.openTerminal('sLive');
|
||||||
ide.openTerminal('sDead');
|
ide.openTerminal('sDead');
|
||||||
|
ide.openTerminal('sDeadAlone', { split: true }); // colonne entière à supprimer
|
||||||
|
|
||||||
ide.pruneDeadResources(new Set(['sLive']), new Set([wtKey('r', '/w1')]));
|
ide.pruneDeadResources(new Set(['sLive']), new Set([wtKey('r', '/w1')]));
|
||||||
|
|
||||||
|
expect(ide.dockColumns).toHaveLength(1);
|
||||||
|
expect(ide.dockColumns[0]!.ratio).toBeCloseTo(1);
|
||||||
|
|
||||||
expect(ide.editorTabs.map((t) => t.wtPath)).toEqual(['/w1']);
|
expect(ide.editorTabs.map((t) => t.wtPath)).toEqual(['/w1']);
|
||||||
expect(ide.dockSessionIds).toEqual(['sLive']); // sDead retiré
|
expect(ide.dockSessionIds).toEqual(['sLive']); // sDead retiré
|
||||||
expect(ide.isDirty(tabId('r', '/w1', 'a'))).toBe(true); // onglet gardé : dirty conservé
|
expect(ide.isDirty(tabId('r', '/w1', 'a'))).toBe(true); // onglet gardé : dirty conservé
|
||||||
expect(ide.isDirty(tabId('r', '/w2', 'b'))).toBe(false); // onglet retiré : dirty nettoyé
|
expect(ide.isDirty(tabId('r', '/w2', 'b'))).toBe(false); // onglet retiré : dirty nettoyé
|
||||||
expect(ide.hasUnsaved).toBe(true); // il reste l'onglet /w1 modifié
|
expect(ide.hasUnsaved).toBe(true); // il reste l'onglet /w1 modifié
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// --- zone centrale : mode fichiers / changements, et cohérence du layout mobile ---
|
||||||
|
|
||||||
|
it('setCenterMode amène le bon panneau au premier plan sur mobile', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.setCenterMode('changes');
|
||||||
|
expect(ide.centerMode).toBe('changes');
|
||||||
|
expect(ide.mobilePanel).toBe('changes');
|
||||||
|
ide.setCenterMode('files');
|
||||||
|
expect(ide.mobilePanel).toBe('editor');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ouvrir un fichier ou un onglet ramène la zone centrale aux fichiers', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.setCenterMode('changes');
|
||||||
|
ide.openFile('r1', '/wt/a', 'src/x.ts');
|
||||||
|
expect(ide.centerMode).toBe('files');
|
||||||
|
expect(ide.mobilePanel).toBe('editor');
|
||||||
|
|
||||||
|
ide.setCenterMode('changes');
|
||||||
|
ide.setActiveTab(tabId('r1', '/wt/a', 'src/x.ts'));
|
||||||
|
expect(ide.centerMode).toBe('files');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('openChanges rend le worktree actif, déplie son bloc et bascule la vue', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
ide.openChanges('r1', '/wt/a');
|
||||||
|
expect(ide.activeContext).toEqual({ repoId: 'r1', wtPath: '/wt/a' });
|
||||||
|
expect(ide.changesExpanded).toEqual([wtKey('r1', '/wt/a')]);
|
||||||
|
expect(ide.centerMode).toBe('changes');
|
||||||
|
ide.openChanges('r1', '/wt/a'); // idempotent
|
||||||
|
expect(ide.changesExpanded).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('toggleChangesWt bascule et réassigne le tableau (persistedRef non profond)', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const before = ide.changesExpanded;
|
||||||
|
ide.toggleChangesWt('k1');
|
||||||
|
expect(ide.changesExpanded).toEqual(['k1']);
|
||||||
|
expect(ide.changesExpanded).not.toBe(before); // nouvelle référence, donc persistée
|
||||||
|
ide.toggleChangesWt('k1');
|
||||||
|
expect(ide.changesExpanded).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('setActivity pose un panneau mobile que le layout sait rendre', () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
for (const view of ['explorer', 'sessions', 'groups'] as const) {
|
||||||
|
ide.setActivity(view);
|
||||||
|
expect(ide.mobilePanel).toBe(view);
|
||||||
|
expect(MOBILE_PANELS).toContain(ide.mobilePanel);
|
||||||
|
}
|
||||||
|
// 'git' est l'index de la sidebar desktop : sur mobile, c'est la vue Changements qui le remplace.
|
||||||
|
ide.setActivity('git');
|
||||||
|
expect(ide.mobilePanel).toBe('changes');
|
||||||
|
expect(ide.centerMode).toBe('changes');
|
||||||
|
expect(MOBILE_PANELS).toContain(ide.mobilePanel);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('un mobilePanel persisté obsolète est ramené à une valeur gérée', () => {
|
||||||
|
localStorage.setItem('arb.ide.mobilePanel', JSON.stringify('sidebar')); // persistedRef stocke du JSON
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
expect(useIdeStore().mobilePanel).toBe('explorer');
|
||||||
|
|
||||||
|
localStorage.setItem('arb.ide.mobilePanel', JSON.stringify('git'));
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
expect(useIdeStore().mobilePanel).toBe('changes');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parseWtKey est l’inverse de wtKey', () => {
|
||||||
|
expect(parseWtKey(wtKey('r1', '/wt/mon projet'))).toEqual({ repoId: 'r1', wtPath: '/wt/mon projet' });
|
||||||
|
expect(parseWtKey('sans-separateur')).toBeNull();
|
||||||
|
expect(parseWtKey('')).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// persistedRef : lecture initiale depuis localStorage, repli sur défaut, réécriture, robustesse.
|
// persistedRef : lecture initiale depuis localStorage, repli sur défaut, réécriture, robustesse.
|
||||||
import { describe, it, expect, beforeEach } from 'vitest';
|
import { describe, it, expect, beforeEach } from 'vitest';
|
||||||
import { nextTick } from 'vue';
|
import { nextTick } from 'vue';
|
||||||
import { persistedRef } from '../src/lib/persisted-ref';
|
import { forgetPersisted, persistedRef, readPersisted } from '../src/lib/persisted-ref';
|
||||||
|
|
||||||
function fakeStorage() {
|
function fakeStorage() {
|
||||||
const m = new Map<string, string>();
|
const m = new Map<string, string>();
|
||||||
@@ -45,3 +45,29 @@ describe('persistedRef', () => {
|
|||||||
expect(persistedRef('x', 5).value).toBe(5);
|
expect(persistedRef('x', 5).value).toBe(5);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('readPersisted / forgetPersisted', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
(globalThis as unknown as { localStorage: unknown }).localStorage = fakeStorage();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lit une valeur brute sans créer de ref, et retombe sur le défaut', () => {
|
||||||
|
localStorage.setItem('legacy', JSON.stringify(['a', 'b']));
|
||||||
|
expect(readPersisted<string[]>('legacy', [])).toEqual(['a', 'b']);
|
||||||
|
expect(readPersisted('absente', 'def')).toBe('def');
|
||||||
|
localStorage.setItem('cassee', '{not json');
|
||||||
|
expect(readPersisted('cassee', 'def')).toBe('def');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('oublie une clé migrée (sans quoi la migration rejouerait au démarrage suivant)', () => {
|
||||||
|
localStorage.setItem('legacy', '1');
|
||||||
|
forgetPersisted('legacy');
|
||||||
|
expect(localStorage.getItem('legacy')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ne jette pas sans localStorage', () => {
|
||||||
|
delete (globalThis as unknown as { localStorage?: unknown }).localStorage;
|
||||||
|
expect(readPersisted('x', 5)).toBe(5);
|
||||||
|
expect(() => forgetPersisted('x')).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// useTerminalContext : le terminal focalisé impose le worktree actif. C'était le chaînon manquant
|
||||||
|
// (openTerminal / focusTerminal ne posaient pas `activeContext`), et c'est ce qui fait suivre la vue
|
||||||
|
// Changements, la barre de statut et les abonnements FS.
|
||||||
|
import { describe, it, expect, beforeEach } from 'vitest';
|
||||||
|
import { createPinia, setActivePinia } from 'pinia';
|
||||||
|
import { effectScope, nextTick } from 'vue';
|
||||||
|
import type { GroupSummary, SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
import { useTerminalContext } from '../src/composables/useTerminalContext';
|
||||||
|
import { useIdeStore } from '../src/stores/ide';
|
||||||
|
import { useWorktreesStore } from '../src/stores/worktrees';
|
||||||
|
import { useSessionsStore } from '../src/stores/sessions';
|
||||||
|
import { useGroupsStore } from '../src/stores/groups';
|
||||||
|
|
||||||
|
function fakeStorage() {
|
||||||
|
const m = new Map<string, string>();
|
||||||
|
return {
|
||||||
|
getItem: (k: string) => (m.has(k) ? (m.get(k) as string) : null),
|
||||||
|
setItem: (k: string, v: string) => void m.set(k, v),
|
||||||
|
removeItem: (k: string) => void m.delete(k),
|
||||||
|
clear: () => m.clear(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function wt(repoId: string, path: string): WorktreeSummary {
|
||||||
|
return {
|
||||||
|
repoId,
|
||||||
|
path,
|
||||||
|
branch: 'main',
|
||||||
|
head: 'abc1234',
|
||||||
|
detached: false,
|
||||||
|
locked: false,
|
||||||
|
prunable: false,
|
||||||
|
isMain: true,
|
||||||
|
git: { ahead: 0, behind: 0, dirtyCount: 0, upstream: null },
|
||||||
|
sessions: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function session(id: string, cwd: string, extra: Partial<SessionSummary> = {}): SessionSummary {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
cwd,
|
||||||
|
command: 'claude',
|
||||||
|
title: null,
|
||||||
|
status: 'running',
|
||||||
|
live: true,
|
||||||
|
createdAt: '2026-01-01T00:00:00.000Z',
|
||||||
|
endedAt: null,
|
||||||
|
exitCode: null,
|
||||||
|
clients: 0,
|
||||||
|
source: 'managed',
|
||||||
|
claudeSessionId: null,
|
||||||
|
pid: 1234,
|
||||||
|
resumable: false,
|
||||||
|
attachable: true,
|
||||||
|
registryStatus: null,
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const group = (id: string, repoIds: string[]): GroupSummary => ({
|
||||||
|
id,
|
||||||
|
label: id,
|
||||||
|
description: null,
|
||||||
|
color: null,
|
||||||
|
repoIds,
|
||||||
|
createdAt: '2026-01-01T00:00:00.000Z',
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('useTerminalContext', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
(globalThis as unknown as { localStorage: unknown }).localStorage = fakeStorage();
|
||||||
|
setActivePinia(createPinia());
|
||||||
|
});
|
||||||
|
|
||||||
|
it('focaliser un terminal pose le worktree actif', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a'), wt('r2', '/wt/b')];
|
||||||
|
sessions.sessions = [session('s1', '/wt/b')];
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useTerminalContext());
|
||||||
|
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
await nextTick();
|
||||||
|
expect(ide.activeContext).toEqual({ repoId: 'r2', wtPath: '/wt/b' });
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rattache par contenance un terminal lancé dans un sous-répertoire', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a')];
|
||||||
|
sessions.sessions = [session('s1', '/wt/a/packages/api')];
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useTerminalContext());
|
||||||
|
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
await nextTick();
|
||||||
|
expect(ide.activeContext).toEqual({ repoId: 'r1', wtPath: '/wt/a' });
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('session de GROUPE : le contexte n’est pas écrasé (un groupe n’a pas de worktree unique)', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
const groups = useGroupsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a'), wt('r2', '/wt/b')];
|
||||||
|
groups.groups = [group('g1', ['r1', 'r2'])];
|
||||||
|
sessions.sessions = [session('sg', '/wt', { addedDirs: ['/wt/a', '/wt/b'], groupId: 'g1' })];
|
||||||
|
ide.setActiveWorktree('r1', '/wt/a');
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useTerminalContext());
|
||||||
|
|
||||||
|
ide.openTerminal('sg');
|
||||||
|
await nextTick();
|
||||||
|
expect(ide.activeContext).toEqual({ repoId: 'r1', wtPath: '/wt/a' });
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('cwd hors de tout worktree connu : contexte inchangé', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a')];
|
||||||
|
sessions.sessions = [session('s1', '/tmp/scratch')];
|
||||||
|
ide.setActiveWorktree('r1', '/wt/a');
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useTerminalContext());
|
||||||
|
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
await nextTick();
|
||||||
|
expect(ide.activeContext).toEqual({ repoId: 'r1', wtPath: '/wt/a' });
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('la session peut arriver APRÈS le terminal (dock persisté, liste encore vide)', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a')];
|
||||||
|
ide.openTerminal('s1'); // session pas encore connue
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useTerminalContext());
|
||||||
|
await nextTick();
|
||||||
|
expect(ide.activeContext).toBeNull();
|
||||||
|
|
||||||
|
sessions.sessions = [session('s1', '/wt/a')];
|
||||||
|
await nextTick();
|
||||||
|
expect(ide.activeContext).toEqual({ repoId: 'r1', wtPath: '/wt/a' });
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// Contrat de loadMonaco : le SUCCÈS est partagé, l'ÉCHEC est réessayable. Un chunk manquant ne doit
|
||||||
|
// pas condamner l'éditeur pour toute la session (c'était le cas : la promesse rejetée restait
|
||||||
|
// mémoïsée, donc la zone d'édition restait vide et muette jusqu'au rechargement de la page).
|
||||||
|
// Le cache vit au niveau du module : ce fichier garde donc UN seul test, ordonné.
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type * as Monaco from 'monaco-editor';
|
||||||
|
import { loadMonaco } from '../src/composables/useMonaco';
|
||||||
|
|
||||||
|
const fake = { editor: {} } as unknown as typeof Monaco;
|
||||||
|
|
||||||
|
describe('loadMonaco', () => {
|
||||||
|
it('ne mémoïse pas un échec, mémoïse un succès', async () => {
|
||||||
|
let failed = 0;
|
||||||
|
const failing = (): Promise<typeof Monaco> => {
|
||||||
|
failed++;
|
||||||
|
return Promise.reject(new Error('chunk absent'));
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(loadMonaco(failing)).rejects.toThrow('chunk absent');
|
||||||
|
await expect(loadMonaco(failing)).rejects.toThrow('chunk absent');
|
||||||
|
expect(failed).toBe(2); // l'import est réellement retenté
|
||||||
|
|
||||||
|
let ok = 0;
|
||||||
|
const working = (): Promise<typeof Monaco> => {
|
||||||
|
ok++;
|
||||||
|
return Promise.resolve(fake);
|
||||||
|
};
|
||||||
|
await expect(loadMonaco(working)).resolves.toBe(fake);
|
||||||
|
await expect(loadMonaco(working)).resolves.toBe(fake);
|
||||||
|
expect(ok).toBe(1); // succès partagé : un seul import
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -22,4 +22,22 @@ describe('useSplitter · nextSize', () => {
|
|||||||
it('taille inchangée si la position ne bouge pas', () => {
|
it('taille inchangée si la position ne bouge pas', () => {
|
||||||
expect(nextSize(300, 150, 150, { min: 100, max: 400 })).toBe(300);
|
expect(nextSize(300, 150, 150, { min: 100, max: 400 })).toBe(300);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Régression : PanelSplitter passait ses bornes PAR VALEUR, capturées au premier rendu. Avec des
|
||||||
|
// bornes dérivées du viewport ou d'une largeur mesurée, un drag clampait sur des valeurs périmées
|
||||||
|
// (le clavier, lui, relisait les props : les deux voies ne s'accordaient plus).
|
||||||
|
it('relit min/max à chaque appel (bornes réactives)', () => {
|
||||||
|
const bounds = { min: 100, max: 200 };
|
||||||
|
const opts = {
|
||||||
|
get min() {
|
||||||
|
return bounds.min;
|
||||||
|
},
|
||||||
|
get max() {
|
||||||
|
return bounds.max;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(nextSize(150, 0, 500, opts)).toBe(200);
|
||||||
|
bounds.max = 900;
|
||||||
|
expect(nextSize(150, 0, 500, opts)).toBe(650);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||||
import { createPinia, setActivePinia } from 'pinia';
|
import { createPinia, setActivePinia } from 'pinia';
|
||||||
import { effectScope, nextTick } from 'vue';
|
import { effectScope, nextTick } from 'vue';
|
||||||
import type { WorktreeSummary } from '@arboretum/shared';
|
import type { SessionSummary, WorktreeSummary } from '@arboretum/shared';
|
||||||
|
|
||||||
const watched: string[] = [];
|
const watched: string[] = [];
|
||||||
const released: string[] = [];
|
const released: string[] = [];
|
||||||
@@ -24,6 +24,7 @@ vi.mock('../src/lib/ws-client', () => ({
|
|||||||
const { useWatchedWorktrees, MAX_WATCHED } = await import('../src/composables/useWatchedWorktrees');
|
const { useWatchedWorktrees, MAX_WATCHED } = await import('../src/composables/useWatchedWorktrees');
|
||||||
const { useIdeStore } = await import('../src/stores/ide');
|
const { useIdeStore } = await import('../src/stores/ide');
|
||||||
const { useWorktreesStore } = await import('../src/stores/worktrees');
|
const { useWorktreesStore } = await import('../src/stores/worktrees');
|
||||||
|
const { useSessionsStore } = await import('../src/stores/sessions');
|
||||||
|
|
||||||
function fakeStorage() {
|
function fakeStorage() {
|
||||||
const m = new Map<string, string>();
|
const m = new Map<string, string>();
|
||||||
@@ -50,6 +51,28 @@ function wt(repoId: string, path: string): WorktreeSummary {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function session(id: string, cwd: string, extra: Partial<SessionSummary> = {}): SessionSummary {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
cwd,
|
||||||
|
command: 'claude',
|
||||||
|
title: null,
|
||||||
|
status: 'running',
|
||||||
|
live: true,
|
||||||
|
createdAt: '2026-01-01T00:00:00.000Z',
|
||||||
|
endedAt: null,
|
||||||
|
exitCode: null,
|
||||||
|
clients: 0,
|
||||||
|
source: 'managed',
|
||||||
|
claudeSessionId: null,
|
||||||
|
pid: 1234,
|
||||||
|
resumable: false,
|
||||||
|
attachable: true,
|
||||||
|
registryStatus: null,
|
||||||
|
...extra,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
describe('useWatchedWorktrees', () => {
|
describe('useWatchedWorktrees', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
watched.length = 0;
|
watched.length = 0;
|
||||||
@@ -117,6 +140,70 @@ describe('useWatchedWorktrees', () => {
|
|||||||
scope.stop();
|
scope.stop();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('observe un bloc déplié de la vue Changements, sans dépôt déplié dans l’explorateur', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a'), wt('r2', '/wt/b')];
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useWatchedWorktrees());
|
||||||
|
expect(watched).toEqual([]);
|
||||||
|
|
||||||
|
ide.toggleChangesWt('r2\0/wt/b');
|
||||||
|
await nextTick();
|
||||||
|
expect(watched).toEqual(['r2\0/wt/b']);
|
||||||
|
|
||||||
|
ide.toggleChangesWt('r2\0/wt/b');
|
||||||
|
await nextTick();
|
||||||
|
expect(released).toEqual(['r2\0/wt/b']);
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignore une clé de bloc dont le worktree n’existe plus', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a')];
|
||||||
|
ide.toggleChangesWt('r9\0/wt/disparu');
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useWatchedWorktrees());
|
||||||
|
await nextTick();
|
||||||
|
expect(watched).toEqual([]);
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Un terminal visible travaille dans son worktree : son statut git doit rester frais, sinon les
|
||||||
|
// compteurs du bloc Changements d'à côté restent figés pendant toute la session.
|
||||||
|
it('observe le worktree d’un terminal visible, sans rien de déplié', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a'), wt('r2', '/wt/b')];
|
||||||
|
sessions.sessions = [session('s1', '/wt/b/packages/front')];
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useWatchedWorktrees());
|
||||||
|
|
||||||
|
ide.openTerminal('s1');
|
||||||
|
await nextTick();
|
||||||
|
// rattaché par CONTENANCE : le terminal tourne dans un sous-répertoire du worktree
|
||||||
|
expect(watched).toContain('r2\0/wt/b');
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('une session de groupe fait observer TOUS ses répertoires reliés', async () => {
|
||||||
|
const ide = useIdeStore();
|
||||||
|
const worktrees = useWorktreesStore();
|
||||||
|
const sessions = useSessionsStore();
|
||||||
|
worktrees.worktrees = [wt('r1', '/wt/a'), wt('r2', '/wt/b')];
|
||||||
|
sessions.sessions = [session('sg', '/wt', { addedDirs: ['/wt/a', '/wt/b'], groupId: 'g1' })];
|
||||||
|
const scope = effectScope();
|
||||||
|
scope.run(() => useWatchedWorktrees());
|
||||||
|
|
||||||
|
ide.openTerminal('sg');
|
||||||
|
await nextTick();
|
||||||
|
expect(watched).toContain('r1\0/wt/a');
|
||||||
|
expect(watched).toContain('r2\0/wt/b');
|
||||||
|
scope.stop();
|
||||||
|
});
|
||||||
|
|
||||||
it('incrémente le jeton d’invalidation du store à chaque worktree_changes', () => {
|
it('incrémente le jeton d’invalidation du store à chaque worktree_changes', () => {
|
||||||
const ide = useIdeStore();
|
const ide = useIdeStore();
|
||||||
const worktrees = useWorktreesStore();
|
const worktrees = useWorktreesStore();
|
||||||
|
|||||||
Reference in New Issue
Block a user